微信公众号网页授权中转功能-解决网页授权域名个数限制-通过已授权的域名进行中转...

微信公众号网页授权中转功能

解决网页授权域名个数限制

通过已授权的域名进行中转

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
修改为自己的中转域名,这样可以解决个数限制问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值