PHP实现微信小程序用户授权的工具类示例(2)
实现步骤
用户授权时序图
关键代码
小程序端
小程序端的获取用户信息流程
1)调用login方法获取code
2)调用getUserInfo方法获取用户的加密数据
3)调用后端的用户授权接口将用户信息保存到服务端
4)保存后端接口返回的uid和unionid到localstorage中,作为全局参数
获取用户的授权信息
getUid:function(cf){ var that = this wx.login({ success: function (ress) { var code = ress.code wx.getUserInfo({ withCredentials: true, success: function (res) { that.globalData.userInfo = res.userInfo; that.authorize(code, res.signature, res.iv, res.rawData, res.encryptedData, cf) } }) } }) }, authorize: function (code, signature, iv, rawData, encryptedData, cf) { var that =this var dataobj = { code: code, signature: signature, iv: iv, raw_data: rawData, encrypted_data: encryptedData } console.log("code:",code) var param = JSON.stringify(dataobj) param = that.Encrypt(param) var url = that.data.API_DOMAIN2 + "/user/authorization?param=" + param wx.request({ url: url, method: "GET", header: { 'content-type': 'application/json' }, success: function (res) { if (res.data.errcode == 200) { wx.hideToast() wx.setStorage({ key: "uid", data: res.data.data.uid, success: function () { if (cf) { typeof cf == "function" && cf(res.data.data.uid) } } }) } else { that.exceptionHandle('uid', url, res.data.errcode, res.data.msg) } } }) },
服务端
入口方法
/** * api接口开发 * 获取详情的接口 * @param $uid 用户编号 * @param $iv 向量 * @param $encryptedData 微信加密的数据 * @param $rawData 判断是否为今天 * @param $signature 签名 * @return array */ public static function authorization($appid,$appsecret,$code,$iv,$encryptedData,$rawData,$signature){ $result = self::decodeWxData($appid,$appsecret,$code,$iv,$encryptedData); if($result['errcode'] != 200){ return $result; } //处理微信授权的逻辑 $wxUserData = $result['data']; error_log("authorization data=============>"); error_log(json_encode($wxUserData)); $uid = WxaUserService::regWxaUser($wxUserData); $data['uid'] = $uid['uid']; $data['unionid'] = $uid['unionid']; $result['data'] = $data; return $result; } /** * 解密微信的数据 * @param $code wx.login接口返回的code * @param $iv wx.getUserInfo接口或者wx.getWeRunData返回的iv * @param $encryptedData wx.getUserInfo接口或者wx.getWeRunData返回的加密数据 * @return array */ public static function decodeWxData($appid,$appsecret,$code,$iv,$encryptedData){ $sessionKeyUrl = sprintf('%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code',config('param.wxa_user_info_session_key_url'),$appid,$appsecret,$code); $rtnJson = curlRequest($sessionKeyUrl); $data = json_decode($rtnJson,true); error_log('authorization wx return data========>'); error_log($rtnJson); if(isset($data['errcode'])){ return $data; } $sessionKey = $data['session_key']; $wxHelper = new WxBizDataHelper($appid,$sessionKey,$encryptedData,$iv); $data['errcode'] = 200; $data['data'] = []; if(!$wxData = $wxHelper->getData()){ $data['errcode'] = -1; }else{ error_log('current wx return data is =========>'.json_encode($wxData)); $data['data'] = $wxData; } return $data; }
内容版权声明:除非注明,否则皆为本站原创文章。