微信小程序获取手机号码有两种方式:
1.通过sessionKey,encryptedData,iv进行解密,可在前端和后端解密
2.可以通过传code,调api获取https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
在onLoad中获取SessionKey可避免使用方法1第一次报错的情况。
方法2使用到了access_token,体验版和正式版都会去刷新access_token会使一端失效。可以将access_token存在redis,两个版本都连同一个redis。
<template>
<view class="content">
<button class="btn-login" @getphonenumber="getPhoneNumber" open-type="getPhoneNumber">微信获取手机号码</button>
</view>
</template>
<script>
/* 调后端的方法 start*/
import { getOpenIdAndSessionKey, getPhone} from "@/api/login.js"
/* 调后端的方法 end*/
import { mapState } from 'vuex'
export default {
data() {
return {
params:{
encryptedData:'',
iv:'',
sessionkey:'',
openid:'',
code:'',
phone:''
}
}
},
computed: {
...mapState({
phone:state => {
return state.phone
}
})
},
onLoad: async function () {
this.getSessionKey()
},
methods: {
async getSessionKey() {
const _this = this
uni.login({
provider:'weixin',
success(data) {
getOpenIdAndSessionKey(data.code)
.then(res => {
_this.params.sessionkey = res.data.sessionKey
_this.params.openid = res.data.openid
})
}
})
},
getPhoneNumber(e){
const _this = this
if(e.detail.errMsg=='getPhoneNumber:ok'){
this.params.code = e.detail.code;
const { encryptedData, iv } = e.mp.detail;
this.params.encryptedData = encryptedData
this.params.iv = iv
_this.getPhoneNum()
}
},
getPhoneNum(){
getPhone(this.params).then(res => {
console.log(res)
this.params.phone = res.data
}).catch(error => {
});
}
}
}
</script>