The safe and correct way for the WeChat applet to obtain the user's mobile phone number is to pass the obtained iv and other information to the backend, let the backend decrypt it, and then provide an interface to return to the frontend.
But if you encounter a more general backend or a lazy backend, the frontend can also try to complete the phone number decryption by itself.
1. Use the authorized mobile phone number component button
<view class="button">
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button>
</view>
2. Download RdWXBizDataCrypt decrypted file
https://download.csdn.net/download/qq_35946021/87123755 free download
3. Reference the file where it needs to be decrypted
var WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt');
4. Use the login interface first, and then get the session_key given by the backend
login(){
wx.login({
success: (res) => {
console.log(res)
api.getOpenidAction({
js_code:res.code
}).then(re=>{
console.log(re)
this.setData({
openid:re.Data.openid,
code:res.code,
session_key:re.Data.session_key
})
})
}
})
},
5. Then use the mobile phone number component to pass the encryptedData and iv value of the parameter
key code:
new a WXBizDataCrypt object, pass APPID and session_key
Then use the decryptData decryption method, pass parameters encryptedData and iv
getPhoneNumber (e) {
console.log(e.detail.errMsg)
console.log(e.detail.iv)
console.log(e)
var pc = new WXBizDataCrypt("wxexxxxxxxxxxxxx6", this.data.session_key)
var data = pc.decryptData(e.detail.encryptedData , e.detail.iv)
console.log('解密后 data: ', data)
},
The console prints the encrypted data and it can be used