實現邏輯
- 使用中間件做限制,限制未授權用戶自動跳轉到授權,並保存業務地址
- 授權成功,執行授權回調,保存用戶登錄狀態
- 跳轉到第一步授權地址
代碼實例
中間件
<?php
namespace app\http\middleware;
use EasyWeChat\Factory;
class CheckOnlineWxAuth
{
public function handle($request, \Closure $next)
{
if (!session('member'))
{
//配置信息最好寫在配置文件中
$config = [
'app_id' => 'wx******',
'secret' => '************',
// 指定 API 調用返回結果的類型:array(default)/collection/object/raw/自定義類名
'response_type' => 'array',
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => '/oauth_callback',
],
];
session('target_url',$request->url());
$app = Factory::officialAccount($config);
$oauth = $app->oauth;
$oauth->redirect()->send();
}
return $next($request);
}
}
授權回調
<?php
namespace app\online\controller;
use EasyWeChat\Factory;
use think\Controller;
class Wechat extends Controller
{
public function callback()
{
$config = [
'app_id' => 'wx*******',
'secret' => 'facb5696fd22cf1424bd0bb448e5a8d3',
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => '/online/oauth_callback',
],
];
$app = Factory::officialAccount($config);
//獲取授權的用戶
$user = $app->oauth->user();
return json($user);
}
}
返回結果
在回調中保存用戶登錄狀態,並從 session
中獲取中間件中保存的業務地址,重定向到業務地址,我這里就不做展示了。