嗯,对,你说得对。
调用wx.login 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 App({ onLaunch : function ( ) { wx.login({ success : function (res ) { if (res.code) { wx.request({ url : 'https://test.com/onLogin' , data : { code : res.code } }) } else { console .log('登录失败!' + res.errMsg) } } }); } })
onLogin接口,php实现 1 2 3 4 5 6 7 $APPID = 'wxf007410...' ;$SECRET = '1bb26d74f33910588ee....' ;$request = request();$code = $request ->code;$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' .$APPID .'&secret=' .$SECRET .'&js_code=' .$code .'&grant_type=authorization_code' ;$client = new \GuzzleHttp\Client();$response = $client ->get($url )->getBody()->getContents();
返回数据
1 {"session_key" :"VUNQTngHJYeceYRrQpj0cQ==" ,"openid" :"o3CTb4kuzH674QgeFsKhyoipfPi4" }
登录成功后调用获取用户接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 success: function (res ) { console .log(res.data) wx.getUserInfo({ success : function (res ) { var userInfo = res.userInfo var nickName = userInfo.nickName var avatarUrl = userInfo.avatarUrl var gender = userInfo.gender var province = userInfo.province var city = userInfo.city var country = userInfo.country console .log('获取用户信息返回' ) console .log(res); } })
在登录状态下返回的信息包含敏感数据,将这些敏感数据提交到服务器进行解密
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 console .log('获取用户信息返回' ); console .log(res); wx.request({ method : 'POST' , url : 'https://vxndy.com/user' , data : { rawData : res.rawData, signature : res.signature, encryptedData : res.encryptedData, iv : res.iv }, header : { 'content-type' : 'application/json' }, success : function (res ) { console .log('调用解密接口返回' ) console .log(res) } })
user接口实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 $APPID = 'wxf0074104e....' ;$request = request();$rawData = $request ->rawData;$signature = $request ->signature;$encryptedData = $request ->encryptedData;$iv = $request ->iv;$path = storage_path('session_key' );info('从文件中获取session_key' ); $session_key = file_get_contents($path );$pc = new \App\Wx\WXBizDataCrypt($APPID , $session_key );$errCode = $pc ->decryptData($encryptedData , $iv , $data );if ($errCode == 0 ) { return response()->json($data ); } else { info('错误' ); info($errCode ); } return response()->json(['status' => 200 ]);
返回的数据包括 openId 和 用户其他信息
注意 每次发起登录请求的时候应该先检测是否需要登录
1 2 3 4 5 6 7 8 9 10 wx.checkSession({ success: function ( ) { }, fail: function ( ) { wx.login() .... } })