cocos creator 登录流程
安装minigame-api-typings
1
npm install minigame-api-typings
代码中引用import ‘minigame-api-typings’;
调用wx登录接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51wx.login({
complete: (res) => {
console.log("login complete:" + JSON.stringify(res));
},
fail: (res) => {
console.log("login fail:" + JSON.stringify(res));
},
success: (login_res) => {
console.log("login success:" + JSON.stringify(login_res));
wx.getSetting({
complete: (res) => {
console.log("authSetting complete:", JSON.stringify(res));
},
fail: (res) => {
console.log("authSetting fail:", JSON.stringify(res));
},
success: (res) => {
console.log("authSetting:", JSON.stringify(res));
if (res.authSetting['scope.userInfo']) {
this.get_user_info_login(login_res.code)
}
else {
let wxSize = wx.getSystemInfoSync();
let btn = wx.createUserInfoButton({
type: 'text',
text: '微信登录',
style: {
left: wxSize.screenWidth / 2 - 100,
top: wxSize.screenHeight / 2 - 40,
width: 200,
height: 40,
lineHeight: 40,
backgroundColor: '#ffffff',
borderColor: '#ffffff',
borderWidth: 1,
color: '#000000',
textAlign: 'center',
fontSize: 16,
borderRadius: 4
}
});
btn.onTap((res) => {
console.log("createUserInfoButton:" + JSON.stringify(res));
this.get_user_info_login(login_res.code)
btn.destroy();
});
}
}
});
}
});1
2
3
4
5
6
7
8
9
10
11
12
13
14get_user_info_login(code:string) {
wx.getUserInfo({
withCredentials:false,
success: (result) => {
login.login_player_no_author(code, result.userInfo.nickName, result.userInfo.avatarUrl);
},
fail: (res) => {
console.log("fail:" + JSON.stringify(res));
},
complete: (res) => {
console.log("complete:" + JSON.stringify(res));
}
});
}login_player_no_author接口上传code到服务器端,服务器端收到code之后通过http请求到微信后台验证(AppID,Secret从微信小游戏管理后台获取):
1
2
3
4
5
6
7
8
9
10var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={AppID}&secret={Secret}&js_code={code}&grant_type=authorization_code";
var result = await HttpClientWrapper.GetRspAsync(url);
if (result != null && result.StatusCode == System.Net.HttpStatusCode.OK)
{
var ret = await result.Content.ReadAsStringAsync();
var ret_obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Hashtable>(ret);
var token = await player.client_Mng.token_player_login(ret_obj["openid"] as string);
rsp.rsp(token);
}