微信小程序登录实现

嗯,对,你说得对。

调用wx.login

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//app.js
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 //性别 0:未知、1:男、2:女
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(){
//session 未过期,并且在本生命周期一直有效
},
fail: function(){
//登录态过期
wx.login() //重新登录
....
}
})