微信公众号网页授权中转功能
解决网页授权域名个数限制
通过已授权的域名进行中转
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');
控制器下
<?phpnamespace 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
修改为自己的中转域名,这样可以解决个数限制问题