regist/index.js 云函数
const appid = 'xxxxxxxxxxxxx';
const secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const envid = "test-lezhi";
const cloud = require('wx-server-sdk');
const TcbRouter = require('tcb-router');
const rq = require('request');
const wxurl = 'https://api.weixin.qq.com';
var WXBizDataCrypt = require('./RdWXBizDataCrypt')
cloud.init({
env: envid
})
const db = cloud.database();
const _ = db.command;
exports.main = async (event, context) => {
const app = new TcbRouter({
event
});
app.router('phone', async (ctx) => {
ctx.body = new Promise(resolve => {
rq({
url: wxurl + '/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + event.code + '&grant_type=authorization_code',
method: "GET",
json: true,
}, function (error, response, body) {
const decrypt1 = new WXBizDataCrypt(appid, body.session_key)
const decrypt2 = decrypt1.decryptData(event.encryptedData, event.iv)
resolve(
ctx.body ={decrypt2}
)
});
});
});
前端页 index.wxml
<button class="phone" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">
<block wx:if="{{phone==''}}"> 请点击获取您的手机号</block>
<block wx:if="{{phone!==''}}"> {{phone}}</block>
</button>
前端 index.js
getPhoneNumber: function (e) {
console.log(e)
let that = this;
if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
wx.showToast({
title: '获取手机号失败',
icon: 'none'
})
return;
}
wx.showLoading({
title: '获取手机号中...',
})
wx.login({
success(re) {
console.log(re)
wx.cloud.callFunction({
name: 'regist',
data: {
$url: "phone",
encryptedData: e.detail.encryptedData,
iv: e.detail.iv,
code: re.code
},
success: res => {
console.log(res);
wx.hideLoading();
if (res.result == null) {
wx.showToast({
title: '获取失败,请重新获取',
icon: 'none',
duration: 2000
})
return false;
}
that.setData({
phone: res.result.decrypt2.phoneNumber
})
},
fail: err => {
console.error(err);
wx.hideLoading()
wx.showToast({
title: '获取失败,请重新获取',
icon: 'none',
duration: 2000
})
}
})
},
fail: err => {
console.error(err);
wx.hideLoading()
wx.showToast({
title: '获取失败,请重新获取',
icon: 'none',
duration: 2000
})
}
})
},
补充:regist/index.js 中引入的RdWXBizDataCrypt 是一个外部js文件,它需要一些其他文件一起配合使用,文件个数较多,所以我上传到了下载文件中。