微信公眾號使用tp5.1+Easywechat 實現網頁授權


實現邏輯

  1. 使用中間件做限制,限制未授權用戶自動跳轉到授權,並保存業務地址
  2. 授權成功,執行授權回調,保存用戶登錄狀態
  3. 跳轉到第一步授權地址

代碼實例

中間件

<?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中獲取中間件中保存的業務地址,重定向到業務地址,我這里就不做展示了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM