fasatadmin 第三方插件还是非常好用的!唯一不足就是说明不详细,先说下我的需求吧,以便和我需求差不多的小伙伴可以看下去! 使用微信公众号进行登录,前后端分离后端提供接口 前端访问!然后并且注册用户!同时需要记录 上级id 并且在注册的时候填写上级id 到用户表中!
先说流程,也是我浪费时间最多的地方,前后端分离的概念! 其实微信公众号 的登录特别简单,你先用 在微信端 (注意一定是微信端,或者微信开发者工具,这块坑最多)访问一个微信的授权登录网址,然后再这个网址中会包含你需要让微信返回给你的回调网址! 然后你在这个网址里面会自动给你返回一个code 这个code 你拿着去 换取 openid 即可!然后拿到了 openid 以后 剩下的事情就自行解决吧!
先看我修改的一段代码! 由于fasatadmin 提供的第三方登录的 回调网址是写好的!不符合我自己id的业务逻辑 所以 我自己 重新模仿这 他的 获取网址方法 getAuthorizeUrl 改写了一个 getUrl 方法 具体代码如下
public function getUrl($url)
{
$state = md5(uniqid(rand(), true));
Session::set('state', $state);
$queryarr = array(
"appid" => $this->config['app_id'],
"redirect_uri" => $url,
"response_type" => "code",
"scope" => $this->config['scope'],
"state" => $state,
);
if ($this->isWeb) {
//PC端应用scope固定值
$queryarr['scope'] = "snsapi_login";
}
$url = $this->getAuthCodeUrl . '?' . http_build_query($queryarr) . '#wechat_redirect';
return $url;
}
其实很简单 基本也没改写什么东西 就是把 redirect_uri 这个参数的 $url 给 变成自定义的了!
这么做的目的就是为了可以 让自己的业务逻辑可以继续而不改动太多插件中的东西!
<?php
namespace app\api\controller;
use app\common\controller\Api;
use addons\third\library\Application;
use addons\third\library\Service;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Session;
use fast\Http;
use fast\Random;
class Wechat extends Api
{
protected $noNeedLogin = ['login', 'callback'];
protected $noNeedRight = ['*'];
protected $app = null;
protected $options = [];
protected $layout = 'default';
protected $platform = 'wechat';
public function _initialize()
{
parent::_initialize();
$this->config = get_addon_config('third');
$this->app = new Application($this->config);
}
//第一步自定义回调地址 访问插件中自定义写的 getUrl方法 获取url 并访问
public function login()
{
$id = input('id', 1); //测试时候先写1
if (empty($id)) $this->error('参数错误');
$info = Db::name('record')->where('id', $id)->find();
if (empty($info)) $this->error('参数错误');
Session::set('user_id', $info['user_id']);
$url = url('api/wechat/callback',['id'=>$info['user_id']], false,true);
$redirectUrl = $this->app->{$this->platform}->getUrl($url);
header("Location:" . $redirectUrl);
}
//第二步 回调信息 获取用户信息 如果没有就注册
public function callback()
{
$code = $this->request->param("code");
if (empty($code)){
$this->error('没有获取到回调code登录失败');
}
$id = $this->request->param('id');
if (empty($id)) $this->error('参数错误');
$result = $this->app->{$this->platform}->getUserInfo(['code' => $code]);
if (empty($result)) $this->error('没有获取到用户信息');
$result['user_id'] = $id;
$user = \app\common\model\User::where('openid2', $result['openid'])->find();
if ($user) {
$login = $this->auth->direct($user->id);
return $this->auth->getToken();
}else{
$extend = array_filter(['tid' =>$id, 'group_id'=>2 , 'openid2'=> $result['openid']]);
$result = $this->auth->register('A'.Random::numeric(), Random::alnum(), '', '', $extend);
return $this->auth->getToken();
}
}
}
上面就是完整的登录注册逻辑了! 大概意识就是 我通过 url 自定义了一个 回调连接!然后 我在 我的回调里面 加入了我需要加入进去的id 并且以 回调的形式发往 微信,等微信同意我的授权了以后 就在返回的访问的时候又原封不动的吧我提交给 微信的参数有给我带回来了! 这样我就可以通过回调里面的 $this->request->param 方法 把我需要的id 在拿回来! 然后就可以 顺利的进行注册了!