bindGetUserInfo: function (e) {
let that = this;
that.setData({
'userInfo.nickName': e.detail.userInfo.nickName,
'userInfo.Avatar': e.detail.userInfo.avatarUrl,
'userInfo.province': e.detail.userInfo.province,
'userInfo.city': e.detail.userInfo.city,
'userInfo.autograph': e.detail.signature,
'userInfo.iv': e.detail.iv,
"userInfo.encryptedData": e.detail.encryptedData
})
wx.login({
success: function (r) {
var code = r.code; //登录凭证
if (code) {
//2、调用获取用户信息接口
//...
console.log(code);
wx.request({
url: 'openid.php', //自己的地址
data: {
"encryptedData": that.data.userInfo.encryptedData,
"code": code,
"iv": that.data.userInfo.iv
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
console.log(res.data);
if (!res.data) {
return;
}
that.setData({
"userInfo.openId": res.data
});
}
})
} else {
console.log('获取用户登录态失败!' + r.errMsg)
}
},
fail: function () {
}
})
}
openid.php 内
<?php
include_once "./wxBizDataCrypt.php"; //改文件可在微信官网下载
function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
$code = $_GET['code'];
$iv = $_GET['iv'];
$encryptedData = $_GET['encryptedData'];
$appid = ' ';//小程序唯一标识 (在微信小程序管理后台获取)
$appsecret = ' ';//小程序的 app secret (在微信小程序管理后台获取)
$grant_type = "authorization_code"; //授权(必填)
$params = "appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
$url = "https://api.weixin.qq.com/sns/jscode2session?".$params;
$res = json_decode(httpGet($url),true);
//json_decode不加参数true,转成的就不是array,而是对象。 下面的的取值会报错 Fatal error: Cannot use object of type stdClass as array in
$sessionKey = $res['session_key'];
echo $res['openid'];
?>