首先创建一个项目,把这些代码都清空,我们自己写!
首先index.wxml,写一个button用于发起登录
index.wxml
然后写index.js
通过wx.login()来获取code
如果成功获取,那么返回code
然后调用wx.request()向服务端发起一个请求,即向登录api接口发送code
换取openid和session_key
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
},
//授权登录
onGotUserInfo(e) {
// console.log(e)
},
//登录获取code
bindGetUserInfo(e) {
var that = this;
that.setData({
kais: false,
userimg: e.detail.userInfo.avatarUrl,
username: e.detail.userInfo.nickName,
});
wx.login({
success: function (res) {
wx.getUserInfo({ //得到rawData, signatrue, encryptData
success: function (data) {
var rawData = data.rawData;
var signature = data.signature;
var encryptedData = data.encryptedData;
var iv = data.iv;
wx.request({
url: '/api/user/login',
data: {
"code": res.code,
"rawData": rawData,
"signature": signature,
'iv': iv,
'encryptedData': encryptedData
},
method: 'POST',
success: function (info) {
console.log(info);
that.setData({
token: info.data,
kais: false,
});
//存储登录信息
if (wx.getStorageSync('key') == '') {
wx.setStorage({
key: 'key',
data: info.data,
});
};
}
})
}
})
},
})
},
})
app.js,这个清空,留下这样就行了
//app.js
App({
})
写到这小程序端酒写完了,现在开始写服务端了
vget($url); // 一个使用curl实现的get方法请求
$arr = json_decode($arr, true);
$openid = $arr['openid'];
$session_key = $arr['session_key'];
// 数据签名校验
$signature = input('signature');
$rawData = input('rawData');
$signature2 = sha1($rawData . $session_key);
if ($signature != $signature2) {
return json(['code' => 500, 'msg' => '数据签名验证失败!']);
}
Vendor("PHP.wxBizDataCrypt"); //加载解密文件,在官方有下载(下载后放到vender目录去)
$encryptedData = input('encryptedData');
$iv = input('iv');
$pc = new \WXBizDataCrypt($APPID, $session_key);
$errCode = $pc->decryptData($encryptedData, $iv, $data); //其中$data包含用户的所有数据
$data = json_decode($data,true);
if ($errCode == 0) {
$user_id = md5($data['openId']);
//缓存七天
//Cache::set("$user_id",$data['openId'],60*60*24*7);
$userInfo = [
'open_id' => $data['openId'],
'nickName' => $data['nickName'],
'avatarUrl' => $data['avatarUrl'],
'gender' => $data['gender'],
'country' => $data['language'],
'province' => $data['province'],
'city' => $data['city'],
'create_time'=> date('Y-m-d H:i:s'),
'update_time'=> date('Y-m-d H:i:s'),
];
$uid = Db::name('wx_user')->field('id')->where('open_id',$data['openId'])->find()['id'];
//判断用户是否已经授权登录(没有则注册)
if(empty($uid)){
$uid = Db::name('wx_user')->insertGetId($userInfo);
}
//存储7天作为登录时的验证(token),其中键是md5加密后的openId,值是数据库中用户的id
Cache::set("$user_id",$uid,60*60*24*7);
dump($data);
echo $user_id;
die;//打印解密所得的用户信息
} else {
echo $errCode;//打印失败信息
}
}
public function vget($url){
$info=curl_init();
curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
curl_setopt($info,CURLOPT_HEADER,0);
curl_setopt($info,CURLOPT_NOBODY,0);
curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($info,CURLOPT_URL,$url);
$output= curl_exec($info);
curl_close($info);
return $output;
}
}
后台可以通过openID和session_key解密打印用户的所有信息
最后服务端会返回token,小程序本地保存下来,下次需要用到用户相关的接口时记得携带就可以了