小程序登录
参考:https://www.cnblogs.com/liangzia/p/9957626.html(主要)
https://www.cnblogs.com/zxf100/p/11849878.html
前言
提示:微信小程序登录大概逻辑及实现
例如:前后端分离项目
一、大概逻辑
小程序端准备若干参数传至后端,后端生成token返回(后端是https接口)
二、实现步骤
1.小程序前端实现
直接上代码
<button
open-type="getUserInfo"
bindgetuserinfo="onGetUserInfo"
class="userinfo-avatar"
style="background-image: url({{avatarUrl}})"
size="default"
></button>
onGetUserInfo: function(e) {
if (!this.data.logged && e.detail.userInfo) {
console.log(e)
this.setData({
logged: true,
avatarUrl: e.detail.userInfo.avatarUrl,
userInfo: e.detail.userInfo
})
wx.login({
success:function(res){
console.log(res);
wx.request({
// url: 'http://127.0.0.1:12001/api/frontend/user/checkIdentity',
url: 'https://www.baidu.net/api/frontend/user/checkIdentity',
method: 'POST',
header: { 'content-type': 'application/x-www-form-urlencoded' },
data: {
encryptedData: e.detail.encryptedData,
signature: e.detail.signature,
rawData: e.detail.rawData,
iv: e.detail.iv,
code:res.code
},
success: function (res_user) {
console.log(11111)
console.log(res_user)
if (res_user.data.status == 0) {
var data = JSON.parse(res_user.data.msg) //json转对象
//授权成功返回的数据,根据自己需求操作
console.log(data)
}
}, fail: function () {
console.log('ajax失败了')
}
})
}
})
}
},
2.引入微信验证库(坑多)
首先到官方链接:搜索“点击下载”,然后剪切这几个文件到项目文件夹,引入,且得使用include_once app_path() . "/Library/Wechat/wxBizDataCrypt.php";
这种方式,不知道为啥要用这么古老得方法,而且里面得代码写的真是~
3.接口实现
具体逻辑思路看代码
public function checkIdentity($request)
{
$encryptedData = $request->encryptedData ?? '';
$iv = $request->iv ?? '';
$signature = $request->signature ?? '';
$rawData = $request->rawData ?? '';
$code = $request->code ?? '';
// 获取sessionKey和openId后面要用
list($sessionKey, $openId) = WeChatUtil::getSessionKeyOpenId($code);
// 验证
$signature2 = sha1($rawData . $sessionKey);
if ($signature != $signature2) {
throw FrontendException::error(200011);
}
/**
* 根据open_id找
* 如果没有就继续执行下去,解密得到info
* 新增进去
*/
$user = self::getSingleByOpenId($openId);
if(empty($user)){
$wxBizDataCrypt = new \WXBizDataCrypt(env('XCX_APP_ID'), $sessionKey);
$errorCode = $wxBizDataCrypt->decryptData($encryptedData, $iv, $data);
if(empty($errorCode)){
$data = json_decode($data,true);
$user = new Users();
$user->username = $data['nickName'];
$user->open_id = $data['openId'];
$user->country = $data['country'];
$user->save();
}
}
$params = [
'username' => $user->username,
'password' => '123456'
];
return ($token = Auth::guard('api')->attempt($params))
? ['token' => 'bearer ' . $token]
: ['error' => '获取token失败'];
// throw FrontendException::error(200012);
}
总结
提示:自己写了简单的前端页面对接的,感觉比H5的微信登录简单些🧐