微信公眾號網頁授權中轉功能-解決網頁授權域名個數限制-透過已授權的域名進行中轉

唯一客服系统开发笔记發表於2024-08-28

微信公眾號網頁授權中轉功能

解決網頁授權域名個數限制

透過已授權的域名進行中轉

thinkphp8程式碼

route下

// 微信公眾號授權中轉
Route::get('connect/oauth2/authorize', 'WechatOfficial/GetConnectOauth2Authorize');
// 透過code換取網頁授權access_token
Route::get('sns/oauth2/access_token', 'WechatOfficial/GetSnsOauth2AccessToken');
// 拉取使用者資訊(需scope為 snsapi_userinfo)
Route::get('sns/userinfo', 'WechatOfficial/GetSnsUserinfo');

控制器下

<?php

namespace app\controller;

use app\BaseController;
use think\facade\Request;
use think\facade\Http;

class WechatOfficial extends BaseController
{
    public function GetConnectOauth2Authorize()
    {
        // 獲取查詢引數
        $appid = Request::param('appid','');
        $scope = Request::param('scope',"");
        $redirect_uri = Request::param('redirect_uri',"");
        $code = Request::param('code',"");

        // 判斷是否有code返回
        if (!empty($code)) {
            // 判斷redirect_uri是否包含查詢引數
            if (strpos($redirect_uri, '?') !== false) {
                return redirect($redirect_uri. '&code=' . $code);
            } else {
                return redirect($redirect_uri. '?code=' . $code);
            }
            return;
        }

        // 構建中間重定向URL
        $middleRedirect = urlencode(Request::url(true) . '/connect/oauth2/authorize?redirect_uri=' . urlencode($redirect_uri));
        // 構建微信授權URL
        $wechatUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$middleRedirect}&response_type=code&scope={$scope}&connect_redirect=1#wechat_redirect";

        // 重定向到微信授權頁面
        return redirect($wechatUrl);
    }
    public function GetSnsOauth2AccessToken()
    {
        $appid = Request::param('appid','');
        $secret = Request::param('secret',"");
        $code = Request::param('code',"");

        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code", ['verify' => false]);
        $respBody=$response->getBody();

        return json(json_decode((string)$respBody,true));
    }
    public function GetSnsUserinfo()
    {
        $access_token = Request::param('access_token','');
        $openid = Request::param('openid',"");

        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN", ['verify' => false]);
        $respBody=$response->getBody();

        return json(json_decode((string)$respBody,true));
    }
}

使用上,將原來呼叫官方域名

open.weixin.qq.com
修改為自己的中轉域名,這樣可以解決個數限制問題

相關文章