项目场景:
本文主要:
官方文档
官方文档指出需要先进行login基础授权,获取code,然后后台换取sessionKey,注意这个==sessionKey ==是会过期的,但是有时候你可能会发现就算没过期也会获取手机号失败. 文章很乱,感谢浏览,如果有错误欢迎指出.非常感谢.
正常获取手机号:
前提是你已经进行过wx.login(文档)得到sessionKey
vue+uni框架小程序
下面展示一些内联代码片
。
// 引入.js解密文件,官方的,放最下面了import WXBizDataCrypt from "@/common/WXBizDataCrypt";
// 获取手机号按钮<buttonclass="onQuick"open-type="getPhoneNumber"@getphonenumber="getPhoneNumber">切换至微信手机号授权</button>
// 按钮事件getPhoneNumber(e) {//判断下是否过期sessionKey,就判断下,没啥意义wx.checkSession({success() {console.log("session未过期");},fail() {console.log("session过期 ");},});let sessionKey = uni.getStorageSync("originSessionKey");let phoneNumber = new WXBizDataCrypt("你的appid", sessionKey);let data = phoneNumber.decryptData(e.detail.encryptedData, e.detail.iv);if (data.purePhoneNumber) {let params = {platformPhone: data.purePhoneNumber,//手机号};}},
// 这个是解密用的,创建一个JS文件,调用就行,这个直接复制,官方的,忘了在哪找到得了var crypto = require('crypto')function WXBizDataCrypt(appId, sessionKey) {this.appId = appIdthis.sessionKey = sessionKey}WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {// base64 decodevar sessionKey = new Buffer(this.sessionKey, 'base64')encryptedData = new Buffer(encryptedData, 'base64')iv = new Buffer(iv, 'base64')try {// 解密var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)// 设置自动 padding 为 true,删除填充补位decipher.setAutoPadding(true)var decoded = decipher.update(encryptedData, 'binary', 'utf8')decoded += decipher.final('utf8')decoded = JSON.parse(decoded)} catch (err) {throw new Error('Illegal Buffer')}if (decoded.watermark.appid !== this.appId) {throw new Error('Illegal Buffer')}return decoded}module.exports = WXBizDataCrypt
#:
本来整个场这样获取没一点问题,获取并解密,前端就能获取到用户手机号(后端使用code提供*sessionKey *的前提下)
写着玩的,有点乱,这个报错应该是login久了,但是sessionKey 没过期,所以不能只依靠wx.checkSession来判断,最好还是做一个报错的监测,没执行完就说明报错了,就让它跳login,
:报错
有时候就是会这样没过期还是会报错,就很奇怪,我解决是报错就清掉用户信息,再跳login,因为他应该很久前的login…文章很乱,感谢浏览,如果有错误欢迎指出.