先看图解
(qq和微信都一样啦)
数据库设计
用户基础表(users)
用户验证关联表(user_auth_rel)
本地用户表(user_local_auth)
第三方用户表(user_third_auth)
第三方登陆主要是基于OAuth2.0协议来实现
1、首先我们需要以开发者的身份向第三方登陆平台申请接入应用,申请成功后,我会获得一个applD和一个secrectlD.
2、当我们的网站需接入第三方登陆时,会引导用户跳转到第三方的登陆授权页面,此时把之前申请的applD和secrectID带给登陆授权页面。
3、用户登陆成功后即得到授权,第三方会返回一个临时的code给我们的网站。
4、我们的网站接受到code后,再次向我们的第三方发起请求,并携带接收的code,从第三方获取access token.
5、第三方处理请求后,会返回一个access token给我们的网站,我们的网站获取到access token后就可以调用第三方提供的接口了,比如获取用户信息等。最后把该用户信息存入到我们站点的数据库,并把信息保存到session中,实现用户的第三方登陆。
顺带这微信授权登录
需要在微信中先获取code
wx.login({
timeout: 2000,
success: (result) => {
let code=result.code
// console.log(code);
// return
wx.request({
url: 'http://www.lzk5.7.com/index.php/api/admin_login', //仅为示例,并非真实的接口地址
data: {
code:code
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
let openid=res.data.openid;
wx.setStorageSync('openid',openid)
let openid0=wx.getStorageSync('openid')
console.log(openid0)
}
})
},
})
后台获取
// 小程序登录
public function wxlogin(Request $request) {
// 此2个值是小程序后台提供
$appid = '###############';
$secret = '###############';
// 小程序传过来的
$code = $request->get('code');
// 请求地址
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
$url = sprintf($url, $appid, $secret, $code);
// 申请请求客户端 verify 不检查证书ssl
$client = new Client(['timeout' => 5, 'verify' => false]);
$response = $client->get($url);
$json = (string)$response->getBody();
// json转为数组
$arr = json_decode($json, true);
// 写入到数据表中
try {
Renting::create(['openid' => $arr['openid']]);
} catch (\Exception $exception) {
}
return $json;
}
文档链接:
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html