赞
踩
第一步
下载官方给的解密文件‘mWXBizDataCrypt’
没有文件就复制该文件的代码创建一个
- var crypto = require('crypto')
-
- function WXBizDataCrypt(appId, sessionKey) {
- this.appId = appId
- this.sessionKey = sessionKey
- }
-
- WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
- // base64 decode
- var 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
第二步
在date里面放入这几个数据待会要用到
- sessionKey :'',
- appID:' 你的appid',
- secret:'你的secret 在公众平台里获取',
- openId:'',
- session_key:'',
- phoneNumber:''
登录获取授权信息 可放在mounted里面
- uni.getProvider({
- service: 'oauth',
- success: function(res) {
- if (~res.provider.indexOf('weixin')) {
- uni.login({
- provider: 'weixin',
- success: (res2) => {
- const code = res2.code
- uni.getUserInfo({
- provider: 'weixin',
- success: (info) => { //这里请求接口
- console.log('res2');
- console.log(res2);
- console.log('info');
- console.log(info);
- uni.request({
- url:'https://api.weixin.qq.com/sns/jscode2session?appid='+that.appID+'&secret='+that.secret+ '&js_code=' + res2.code + '&grant_type=authorization_code',
- data: {},
- method: 'GET',
- success(r) {
- console.log(r.data)
- that.openId = r.data.openid
- that.session_key = r.data.session_key
- }
- })
-
- },
- fail: () => {
- uni.showToast({
- title: "微信登录授权失败",
- icon: "none"
- });
- }
- })
-
- },
- fail: () => {
- uni.showToast({
- title: "微信登录授权失败",
- icon: "none"
- });
- }
- })
-
- } else {
- uni.showToast({
- title: '请先安装微信或升级版本',
- icon: "none"
- });
- }
- }
- });
第三步
使用手机号一键登录
按钮
<u-button type="primary" open-type="getPhoneNumber" @getphonenumber="submitlogin" shape="circle" text="微信授权登录" ></u-button>
方法体:submitlogin
然后解密信息
- if(e.detail.errMsg=="getPhoneNumber:ok"){
- // console.log(e);
- // console.log(e.detail.errMsg);
- // console.log(e.detail.iv);
- // console.log(e.detail.encryptedData);
- // console.log('用户点击了接受');
- this.showModal = false
- // this.api.phone({
- // session_key:this.sessionKey,
- // encryptedData:e.detail.encryptedData,
- // iv:e.detail.iv
- // })
- let mWXBizDataCrypt = new WXBizDataCrypt('wxf679991a6d85beb2',that.session_key)
- let crDate = mWXBizDataCrypt.decryptData(e.detail.encryptedData,e.detail.iv)
- if(crDate.countryCode != '86'){
- uni.$u.toast('仅限于中国大陆手机号用户使用')
- return
- }
- that.phoneNumber = crDate.phoneNumber
- console.log()
-
-
- }else{
- console.log('用户点击了拒绝') ;
- }
登录成功!
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。