微信公众号使用tp5.1+Easywechat 实现网页授权
实现逻辑
- 使用中间件做限制,限制未授权用户自动跳转到授权,并保存业务地址
- 授权成功,执行授权回调,保存用户登录状态
- 跳转到第一步授权地址
代码实例
中间件
<?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
中获取中间件中保存的业务地址,重定向到业务地址,我这里就不做展示了。