1.小程序端代码
var app = getApp();
var url = '';
var login = function (code, encrypteData, iv) {
var that = this
//创建一个dialog提示
wx.showToast({
title: '正在登录...',
icon: 'loading',
duration: 5000
});
wx.request({
url: url,
method: 'get',
data: {
code: code,
encrypteData: encrypteData,
iv: iv
},
header: {
'Content-Type': 'application/json'
},
success: function (res) {
wx.hideToast()
//console.log('服务器返回' + res.data)
app.globalData.userInfo = res.data
},
fail: function () {
wx.showToast({
title: '网络错误!',
duration: 2000
})
},
complete: function () {
}
})
}
Page({
data: {
//判断小程序的API,回调,参数,组件等是否在当前版本可用。
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function () {
var that = this
wx.login({
success: function (res) { //登录成功
//console.log(res)
if (res.code) {
var code = res.code
wx.getUserInfo({ //getUserInfo流程
success: function (data) { //getUserInfo获取用户信息成功
//console.log(data)
//encrypteData加密密文,iv偏移向量,encodeURIComponent把加密字符串解密成URI字符串
var encryptedData = encodeURIComponent(data.encryptedData);
var iv = data.iv;
//请求自己的服务器
login(code, encryptedData, iv);
//已经授权的用户
wx.switchTab({
url: '../rec/rec',
})
}
})
} else {
console.log('用户没有进行授权!' + res.errMsg)
}
}
});
},
bindGetUserInfo: function (e) {
//console.log(e)
if (e.detail.userInfo) {
//用户按了允许授权的按钮
var that = this
wx.login({
success: function (res) {
if (res.code) {
var code = res.code
wx.getUserInfo({
success: function (data) {
var encryptedData = encodeURIComponent(data.encryptedData);
var iv = data.iv;
//请求自己的服务器
login(code, encryptedData, iv);
}
})
}
}
})
//授权成功后,跳转进入小程序首页
wx.switchTab({
url: '../rec/rec'
})
} else {
//用户按了拒绝按钮
wx.showModal({
title: '警告',
content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
showCancel: false,
confirmText: '返回授权',
success: function (res) {
if (res.confirm) {
console.log('用户点击了“返回授权”')
}
}
})
}
},
})
2.php 端代码
public function wxlogin(){
$get = input('get.');
$param['appid'] = ''; //小程序id
$param['secret'] = ''; //小程序密钥
$param['js_code'] = str_replace(' ','+',$get['code']);
$param['grant_type'] = 'authorization_code';
function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false){
date_default_timezone_set('PRC');
$opts = array(
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => $header,
CURLOPT_COOKIESESSION => true,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_COOKIE =>session_name().'='.session_id(),
);
/* 根据请求类型设置特定参数 */
switch(strtoupper($method)){
case 'GET':
// $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
// 链接后拼接参数 & 非?
$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
break;
case 'POST':
//判断是否传输文件
$params = $multi ? $params : http_build_query($params);
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = $params;
break;
default:
throw new Exception('不支持的请求方式!');
}
/* 初始化并执行curl请求 */
$ch = curl_init();
curl_setopt_array($ch, $opts);
$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if($error) throw new Exception('请求发生错误:' . $error);
return $data;
}
$http_key = httpCurl('https://api.weixin.qq.com/sns/jscode2session', $param, 'GET');
$session_key = json_decode($http_key,true);
//print_r(http_build_query($param));
if (!empty($session_key['session_key'])) {
$appid = $param['appid'];
$encrypteData = urldecode($get['encrypteData']);
$iv = str_replace(' ','+',$get['iv']);
function decryptData( $appid , $sessionKey, $encryptedData, $iv ){
$OK = 0;
$IllegalAesKey = -41001;
$IllegalIv = -41002;
$IllegalBuffer = -41003;
$DecodeBase64Error = -41004;
if (strlen($sessionKey) != 24) {
return $IllegalAesKey;
}
$aesKey=base64_decode($sessionKey);
if (strlen($iv) != 24) {
return $IllegalIv;
}
$aesIV=base64_decode($iv);
$aesCipher=base64_decode($encryptedData);
$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
$dataObj=json_decode( $result );
if( $dataObj == NULL )
{
return $IllegalBuffer;
}
if( $dataObj->watermark->appid != $appid )
{
return $DecodeBase64Error;
}
$data = json_decode($result,true);
return $data;
}
$errCode = decryptData($appid, $session_key['session_key'], $encrypteData, $iv);
//把appid写入到数据库中
$data['appid'] = $errCode['openId'];
$data['nicheng'] = $errCode['nickName'];
$data['publishtime'] = time();
$data['sex'] = $errCode['gender'];
if (false == Db::name('message_user')->where(['appid' => $data['appid']])->find()) {
Db::name('message_user')->insert($data);
$value = Db::name('message_user')->where(['appid' => $data['appid']])->field('appid,nicheng,publishtime,sex')->select();
}else{
$value = Db::name('message_user')->where(['appid' => $data['appid']])->field('appid,nicheng,publishtime,sex')->select();
}
$array = array_merge_recursive($errCode, $value);
return json($array);
}else{
echo '获取session_key失败!';
}
// return json(['status' =>1]);
}
3.结果