小程序获取手机号和openid |
您所在的位置:网站首页 › 微信绑定的手机号怎么能不显示号码信息 › 小程序获取手机号和openid |
获取微信用户绑定的手机号,需先调用wx.login接口。 在登录页的onShow事件中调用wx.login接口获取登录凭证(code)。 用户登录凭证(code)有效期五分钟,需要在开发者服务器后台调用 auth.code2Session,使用 code 换取用户登录态信息,包括用户在当前小程序的唯一标识(openid)、微信开放平台帐号下的唯一标识(unionid,若当前小程序已绑定到微信开放平台帐号)及本次登录的会话密钥(session_key)等。 用户数据的加解密通讯需要依赖会话密钥session_key完成。 Page({ /** * 生命周期函数--监听页面显示 */ onShow: function () { this.wxlogin(); }, /** * 微信登录 */ wxlogin: function () { let that = this; wx.login({ success(res) { console.log(res) if (res.code) { // 获取openid that.getOpenId(res.code) } else { console.log('登录失败!' + res.errMsg) } } }) }, /** * 调用后台接口获取openId */ getOpenId: function (code) { //发起网络请求 wx.request({ url: app.globalData.serverUrl + 'login/get_openid', data: { code: code, }, success(res) { let data = res.data; console.log(res.data) if (data.code == 0) { that.setData({ openid: data.data.openid, session_key: data.data.session_key, }) } }, fail(e) { console.log(e.data) }, }) }, })在登录页面加入登录按钮,需要将 button 组件 open-type 的值设置为 getPhoneNumber,点击按钮时会弹出微信授权页,当用户点击并同意之后,可以通过 bindgetphonenumber 事件回调获取到微信返回的加密数据 encryptedData 和 iv, 然后在开发者服务端后台结合 session_key 以及 app_id 进行解密获取手机号。 返回参数说明 参数类型说明最低版本encryptedDataString包括敏感数据在内的完整用户信息的加密数据,详细见加密数据解密算法 ivString加密算法的初始向量,详细见加密数据解密算法 cloudIDstring敏感数据对应的云 ID,开通云开发的小程序才会返回,可通过云调用直接获取开放数据,详细见云调用直接获取开放数据基础库 2.8.0官方提供的后台解密示例代码 获取得到的用户信息数据解密后为以下 json 结构: { "phoneNumber": "13580006666", "purePhoneNumber": "13580006666", "countryCode": "86", "watermark": { "appid":"APPID", "timestamp": TIMESTAMP } } /** * 微信登录按钮响应事件 */ getPhoneNumber(e) { console.log(e.detail); var that = this var ency = e.detail.encryptedData; var iv = e.detail.iv; var errMsg = e.detail.errMsg if (iv == null || ency == null) { wx.showToast({ title: "授权失败,请重新授权!", icon: 'none', }) return } //把获取手机号需要的参数取到,然后存到data里面 that.setData({ ency: ency, iv: iv, errMsg: errMsg }) that.checkWXSession(); }, /** * 判断微信登录状态 */ checkWXSession() { let that = this; wx.checkSession({ success: function () { if (wx.getExtConfig) { wx.getExtConfig({ success: function (res) { console.log(res); var rescode = res.extConfig.code that.getWXPhoneByServer(); } }) } }, fail: function () { //如果失败,就重新登录,并且重新获取手机号 //登录 that.wxlogin(); } }) }, /** * 调用服务端接口对数据进行解密 */ getWXPhoneByServer() { let that = this; console.log(that.data); wx.request({ method: "POST", url: (app.globalData.serverUrl + "login/get_wxbiz"), data: { data: that.data.ency, iv: that.data.iv, session_key: that.data.session_key }, header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { console.log(res); if (res.data.code == 0) { const data = JSON.parse(res.data.data); console.log(data); that.wxloginServer(data.phoneNumber); } } }); }
|
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |