微信小程序 自动登陆PHP源码实例
app.js
App({ onLaunch: function () { /*初始化APP自动登陆 * 您也可以在任何地方进行用户登陆验证 *用法:首先在js文件中定义 var app = getApp(); app.getUserDataToken(); */ this.getUserDataToken(); }, getUserDataToken:function(){ var that = this; //获取用户缓存token 此token是服务器作为用户唯一验证的标识,具体请看后端代码 var utoken=wx.getStorageSync("utoken"); wx.login({ success: function (res) { var code=res.code; wx.getUserInfo({ success: function (res) { wx.request({ //用户登陆URL地址,请根据自已项目修改 url: 'https://66018954.qcloud.la/WxApp/index.php/UserApi/userAuthSlogin', method:"POST", data: { utoken:utoken, code: code, encryptedData:res.encryptedData, iv:res.iv }, fail:function(res){ }, success: function(res) { var utoken=res.data.utoken; //设置用户缓存 wx.setStorageSync("utoken",utoken); } }) } }) } }) } })
php代码:
public function userAuthSlogin(){ $content = file_get_contents ( 'php://input' ); $content=json_decode($content,true); $utoken=$content["utoken"]; if(!empty($utoken)&&S($utoken)){ $result["success"]=1; $result['utoken']=$utoken; echo json_encode($result); exit(); } $code=$content["code"]; $encryptedData=$content["encryptedData"]; $iv = $content['iv']; /*获取session_key*/ $s_result=$this->getSession($code); $WxData = new WXBizDataCrypt($s_result['appid'],$s_result['session_key']); /*解密用户数据*/ $errCode = $WxData->decryptData($encryptedData, $iv, $user_data); $wxap_key = md5(uniqid(md5(microtime(true)),true)); $result=array(); if($errCode==0){ $user_data=json_decode($user_data,true); $result["success"]=1; $result['utoken']=$wxap_key; $user_id = $this->wxUserAdd($user_data); if($user_id < 1 || empty($user_id)){ $result["success"]=-1; $result['errCode']=0; $result['msg']="获取用户信息出错!"; echo json_encode($result); exit(); } $user_data['uid']=$user_id; S($wxap_key,$user_data,7200); echo json_encode($result); exit(); }else{ $result["success"]=-1; $result['errCode']=$errCode; $result['msg']="获取用户信息出错!"; echo json_encode($result); exit(); } }
项目下载:http://xiazai.jb51.net/201705/yuanma/zddl(jb51.net).rar