微信公众号网页授权中转功能-解决网页授权域名个数限制-通过已授权的域名进行中转
微信公众号网页授权中转功能
解决网页授权域名个数限制
通过已授权的域名进行中转
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
修改为自己的中转域名,这样可以解决个数限制问题
十年开发经验程序员,离职全心创业中,历时三年开发出的产品《唯一客服系统》
一款基于Golang+Vue开发的在线客服系统,软件著作权编号:2021SR1462600。一套可私有化部署的网站在线客服系统,编译后的二进制文件可直接使用无需搭开发环境,下载zip解压即可,仅依赖MySQL数据库,是一个开箱即用的全渠道在线客服系统,致力于帮助广大开发者/公司快速部署整合私有化客服功能。
开源地址:唯一客服(开源学习版)
官网地址:唯一客服官网