public function register(){
$data['openid'] = input('openid','');
//解密用戶信息
$userData = $this->getSessionKey();
if($userData){
$data['nickname'] = $userData['nickName'];
$data['head'] = $userData['avatarUrl'];
}
$data['token'] = getRandChar(32);
$data['token_time'] = time();
$id = Db::name('store_member')->strict(false)->insertGetId($data);
if($id){
$user = Db::name('store_member')->where('id', $id)->find();
return json_encode(['code'=>200, 'msg'=>'注冊成功', 'data'=>$user]);
}else{
return json_encode(['code'=>400, 'msg'=>'注冊失敗']);
}
}
//獲取session_key
public function getSessionKey(){
$url = 'https://api.weixin.qq.com/sns/jscode2session';
$data = array(
'appid' =>$this->wxpay['appid'],
'secret' => $this->wxpay['secret'],
'js_code' => input('js_code',''),
'grant_type' => 'authorization_code'
);
$res = httpRequest($url, 'POST', $data);
$session_key = json_decode($res,true);
if(!empty($session_key['session_key'])){
$encryptedData = str_replace(' ', '+', input('encryptedData'));
$iv = str_replace(' ', '+', input('iv'));
$aesKey = base64_decode($session_key['session_key']);
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($encryptedData);
$result = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, 1, $aesIV);
return json_decode($result,true);
}else{
return false;
}
}
小程序端
login: function (e) {
var that = this;
wx.login({
success: function (res_) {
that.setData({
session: res_.code,
})
}
})
wx.getUserProfile({
desc: '用于完善會員資料', // 聲明獲取用戶個人信息后的用途,后續(xù)會展示在彈窗中,請謹慎填寫
success: (res) => {
var url = 'User/getUser'
var params = {
js_code: that.data.session,
openid: app.globalData.openid,
iv: res.iv,
encryptedData: res.encryptedData,
// 修正
// nickname: e.detail.userInfo.nickName,
// head: e.detail.userInfo.avatarUrl
}
util.wxRequest(url, params, data => {
if (data.code == 200) {
app.globalData.userInfo = data.data
app.globalData.login = true
this.setData({ login:true })
wx.showToast({
title: '登錄成功',
icon: 'success',
duration: 2000
})
} else {
//錯誤,需用戶重新授權(quán)登錄
app.globalData.login = false
wx.showToast({
title: data.msg,
icon: 'none',
duration: 2000
})
}
}, data => { }, data => { })
}
})
},
以上代碼大致流程為:
1.在小程序界面點擊按鈕發(fā)送js_code與encryptedData和iv到自己的服務(wù)器
2.服務(wù)器接收到j(luò)s_code后配合appid與secret共同調(diào)用微信接口獲取session_key與openid
3.使用獲取到的encryptedData與iv以及獲取到的session_key進行解密,將返回的數(shù)據(jù)轉(zhuǎn)化為數(shù)組,提取其中的nickName與avatarUrl文章來源:http://www.zghlxwxcb.cn/news/detail-509931.html
4.連接服務(wù)器,將openid,nickName,avatarUrl,存入數(shù)據(jù)庫之中文章來源地址http://www.zghlxwxcb.cn/news/detail-509931.html
到了這里,關(guān)于微信小程序session_key、encryptedData、iv進行解密獲取用戶頭像名稱的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!