1、WXBizDataCrypt.js-下载地址
2、UNIAPP代码
<template>
<view class="work-container">
<view class="login">
<view class="content">
<button class="button_wx" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
<u-icon name="weixin-fill" color="#FFFFFF" size="50"></u-icon>
<text class="button_text">授 权 登 录</text>
</button>
</view>
</view>
</view>
</template>
<script>
import WXBizDataCrypt from "@/utils/WXBizDataCrypt.js";//必要解密js
let that;
export default {
data() {
return {
appid: '',//必要
secret: '',//必要
code: '',//临时登录凭证
};
},
mounted() {
that = this;
that.isLogin();
that.getWxCode();
},
methods: {
isLogin() {
try {
const phoneNumber = uni.getStorageSync('phoneNumber');
if (phoneNumber) {//自动登录
// 业务登录方法
}
} catch (e) {
// error
}
},
// 获取临时登录凭证
getWxCode() {
wx.login({
success: res => {
console.log('获取用户临时登录凭证code:', res.code);
that.code = res.code;
}
})
},
// 获取手机号的回调函数
getPhoneNumber(e) {
const {
errMsg,
encryptedData,
iv
} = e.detail;
if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
console.log('用户拒绝授权=>');
} else {
console.log('用户同意授权=>', errMsg);
console.log('用户手机号加密数据:', e.detail.encryptedData);
console.log('加密算法的初始向量:', iv);
console.log('开始校验登录凭证code=>');
//登录凭证校验,返回用户唯一标识、会话密钥
uni.request({
url: 'https://api.weixin.qq.com/sns/jscode2session',//微信登录凭证校验接口
data: {
appid: that.appid,
secret: that.secret,
js_code: that.code,
grant_type: 'authorization_code'
},
success(sessionRes) {
console.log('登录凭证code校验成功=>');
const {
openid,
session_key
} = sessionRes.data;
console.log('用户唯一标识:', openid);
console.log('会话密钥:', session_key);
console.log('开始解密用户手机号=>');
var pc = new WXBizDataCrypt(that.appid, session_key);
//解密用户数据
var data = pc.decryptData(encryptedData, iv);
if (data) {
console.log('用户手机号解密成功: ', data.phoneNumber);
uni.setStorageSync("phoneNumber", data.phoneNumber);
// 业务登录方法
// that.startLogin(data.phoneNumber);
}
}
});
}
},
}
}
</script>
<style lang="scss" scoped>
.login {
min-height: 100vh;
}
.content {
margin-top: 500rpx;
}
.button_wx {
background-color: #07c160;
display: flex;
justify-content: center;
align-items: center;
color: #FFFFFF;
font-size: 30rpx;
width: 601rpx;
height: 100rpx;
border-radius: 2.5rem;
}
.button_text {
font-size: 20px;
margin-left: 0.5em;
}
</style>