一、登录界面:
1、授权按钮
1 | < button open-type = "getUserInfo" bindgetuserinfo = "bindGetUserInfo" >点击授权</ button > |
1 | bindGetUserInfo(res) { |
2 | if (res.detail.userInfo) { |
3 | //这里表示同意授权,通常在这里面执行wx.login,如果直接调用wx.login,就是静默登录 |
4 | } else { |
5 | console.log( "点击了拒绝授权" ); |
6 | } |
7 | } |

4、点击允许会返回用户除了openid以外的基本信息(即上面的bindGetUserInfo方法得到的res):

5、接着是用wx.login获取一个临时登录凭证code,这个code是和后台程序获取 unionid或者openid以及sessionKey。下面只是个例子。注意:这一步通常放在第二部同意授权里面。如果直接调用wx.login,则不会弹出上面的弹窗,就是静默登录
01 | wx.login({ |
02 | success(res) { |
03 | if (res.code) { |
04 | //根据code获取openId |
05 | $.ajax(api.xcxlogin, { |
06 | code: res.code |
07 | }, function (r) { |
08 | if (!r.openid) { |
09 | $.msg( '获取openId失败!' ); |
10 | } else { |
11 | let sessionKey = r.sessionKey; |
12 | let openid = r.openid; |
13 | let unionid = r.unionid; |
14 | $.ajax(api.WxQQLogin, { |
15 | providerId: 'weixin' , |
16 | openId: unionid //这里的openId传unionid |
17 | }, function (r) { |
18 | wx.hideLoading() |
19 | if (!r.access_token) { |
20 | ///跳转到绑定界面 |
21 | wx.showModal({ |
22 | title: '提示' , |
23 | content: '您还没有绑定手机号,现在去绑定!' , |
24 | success(res) { |
25 | if (res.confirm) { |
26 | wx.navigateTo({ |
27 | url: '../bind/bind?openId=' + openid + '&unionid=' + unionid, |
28 | }) |
29 | } |
30 | } |
31 | }) |
32 | } else { |
33 | ///登录成功,保存用户信息,跳转到首页 |
34 | $.msg( '登录成功!' ); |
35 | wx.setStorageSync( 'userInfo' , JSON.stringify({ |
36 | tokenType: r.token_type, |
37 | token: r.access_token, |
38 | userId: r.userId, |
39 | userName: r.userName |
40 | })) |
41 | } |
42 | }, '' , true , true ) |
43 | } |
44 | }) |
45 | } else { |
46 | console.log( '登录失败!' + res.errMsg) |
47 | } |
48 | } |
49 | }) |
1、依然用授权按钮,只不过这次是获取此微信号绑定的手机号,当然,和上面一样,直接获取不到,只能得到微信服务器返回的加密数据, 然后在第三方服务端结合 session_key 以及 app_id 进行解密获取手机号。
1 | < button open-type = "getPhoneNumber" class = "btn-radio" bindgetphonenumber = "bindGetPhoneNumber" >获取手机号</ button > |
1 | bindGetPhoneNumber(res) { |
2 | if (e.detail.errMsg == 'getPhoneNumber:ok' ) |
3 | //这里表示同意用户获取手机号,在这里,将得到的加密数据encryptedData,传给后台,后台返回真实的手机号回来,然后再进行绑定操作。 |
4 | } else { |
5 | console.log( "点击了拒绝授权" ); |
6 | } |
7 | } |

4、通过上面返回的encryptedData,调用后台接口,得到手机号进行绑定逻辑,这里就不写了。大致流程就是这样。