public function authorization() { $mall_config = config('mall_config'); $APPID = $mall_config['APPID'];//自己配置 $AppSecret = $mall_config['AppSecret'];//自己配置 $data = request()->get(); $code = $data['code']; $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $APPID . "&secret=" . $AppSecret . "&js_code=" . $code . "&grant_type=authorization_code"; $arr = vget($url); $arr = json_decode($arr, true); $session_key = $arr['session_key']; // 数据签名校验 $signature = $data['signature']; $rawData = $data['rawData']; $signature2 = sha1($rawData . $session_key); if ($signature != $signature2) { return ApiReturn::r(0, [], '验证失败,请重试'); } $ruseut = getUserBySessionKey($APPID, $data['encryptedData'], $data['iv'], $session_key); $wxuserInfo = [ 'open_id' => $ruseut->openId, 'nickName' => $ruseut->nickName, 'gender' => $ruseut->gender, 'avatarUrl' => $ruseut->avatarUrl, ]; $uid = $data['uid']; $res = User::user_save($wxuserInfo, $uid); if (!$res) { return ApiReturn::r(0, [], '会员信息更新失败'); } return ApiReturn::r(1, $wxuserInfo, '授权成功'); }
function vget($url) { $info = curl_init(); curl_setopt($info, CURLOPT_RETURNTRANSFER, true); curl_setopt($info, CURLOPT_HEADER, 0); curl_setopt($info, CURLOPT_NOBODY, 0); curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($info, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($info, CURLOPT_URL, $url); $output = curl_exec($info); curl_close($info); return $output; }
小程序通过session_key解密获取
function getUserBySessionKey($app_id, $encrypted_data, $iv, $session_key) { if (strlen($session_key) != 24) { return json(['code' => 500, 'msg' => 'session_key错误!']); } $aesKey = base64_decode($session_key); if (strlen($iv) != 24) { return json(['code' => 500, 'msg' => 'iv错误']); } $aesIV = base64_decode($iv); $aesCipher = base64_decode($encrypted_data); $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV); $dataObj = json_decode($result); if ($dataObj == NULL) { return json(['code' => 500, 'msg' => '数据解析失败']); } if ($dataObj->watermark->appid != $app_id) { return json(['code' => 500, 'msg' => 'appid解析错误']); } return $dataObj; }