废话不多说直接看效果


结果

具体代码
.wxml
<button bindgetphonenumber="getPhoneNumber" open-type='getPhoneNumber' class='inter-top-button'>登陆</button>
.js
// 获取手机号
getPhoneNumber(e) {
// 获取包含用户手机号的加密字段 和 用于解密的iv
// console.log(e.detail.errMsg)
// console.log("iv:" + e.detail.iv)
// console.log("data:" + e.detail.encryptedData)
// 1. 调用登陆借口获取code
wx.login({
success: function (r) {
var code = r.code;//登录凭证
if (code) {
// console.log("code:"+code);
//2.解密用户信息 获取unionId
// 发起网络请求
wx.request({
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'get',
url: 'https://xcx.xxoo.com./xxoologin/xxxoo',
data: { encryptedData: e.detail.encryptedData, iv: e.detail.iv, code: code },
success(res) {
console.log(res)
}
})
} else {
console.log('获取用户登录态失败!' + r.errMsg)
}
},
})
},
服务器后台控制器代码:
// 报名接口 获取电话号
public function getsign(){
$code = input('code');
$appid = 'wx3cbbfbf6d04b7e45';
$secret = '280d830609480993071419e106087152';
$encryptedData = input('encryptedData');
$iv = input('iv');
if($code != ''){
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
$html = file_get_contents($url);
$obj = json_decode($html);
if(isset($obj->errcode)){
// 获取用户信息失败
return $html;
}else{
$arrlist['openid'] = $obj->openid;
$arrlist['session_key'] = $obj->session_key;
/**
* 解密用户敏感数据
*
* @param encryptedData 明文,加密数据
* @param iv 加密算法的初始向量
* @param code 用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台,使用code 换取 session_key api,将 code 换成 openid 和 session_key
* @return
*/
include_once "wxBizDataCrypt.php";
$pc = new \WXBizDataCrypt( $appid, $arrlist['session_key']);
$errCode = $pc->decryptData($encryptedData, $iv, $data );
//判断获取信息是否成功
if ($errCode != 0) {
return $errCode;
}
return $data;
}
}else{
return json_encode('code为空');
}
}
注:服务器后台代码中引用了微信小程序的解密工具包 自行去微信服务器下载即可
可以访问以下地址:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#%E5%8A%A0%E5%AF%86%E6%95%B0%E6%8D%AE%E8%A7%A3%E5%AF%86%E7%AE%97%E6%B3%95
个人项目经验 不喜勿喷 欢迎添加微信共同探讨
微信:yx159337
qq:1366860941
网友评论