开发前提,注册小程序获取appid和secret
小程序端添加获取手机号码按钮
<button size="mini" class="mobile" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" wx:if="{{!mobile}}">获取手机号码</button>
添加绑定事件
getPhoneNumber: function (e) {
console.log(e)
var that = this;
that.getMobile(e.detail.encryptedData, e.detail.iv);
},
getMobile: function (encryptedData, iv) {
var that = this;
wx.request({
url: app.globalData.domain + '/app/wechat/phone',
data: {
storeId: app.globalData.storeId,
sessionKey: app.globalData.sessionKey,
encryptedData: encryptedData,
iv: iv
},
success: function (res) {
if (res.data.code == 0) {
that.setData({
mobile: res.data.phone
});
}
}
})
},
后台接口实现
@RequestMapping("phone")
public R phone(Long storeId, String sessionKey, String encryptedData, String iv) throws WxErrorException {
WxMaPhoneNumberInfo phoNumberInfo = WxMaFactory.getWxMaService(storeId).getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
return R.ok().put("phone", phoNumberInfo.getPhoneNumber());
}