微信公众号网页授权多域名解决方案
发表于:2023-09-09 17:06:58浏览:245次
需求:
由于微信网页开发,需要获取用户信息,所以就需要网页授权,但是在微信公众平台回调域名有数量限制,现在只有一个公众号,但是我有多个业务不同的域名,并都需要拿到用户信息,这时有限的回调域名肯定是不能解决问题的,因为公众号设置的回调域名必须要与项目域名一致,不然就会报redirect_uri域名错误
实现思路:
中转域名地址( http://www.zhongzhuan.com ),其他要授权的域名先去请求中转地址,并会把获取的code,state原封不动的返回到原来的地址,这样就可以用返回的code去获取access_token,从而通过access_token获取用户信息
① 我们把微信授权的回调域名设置成中转域名地址(http://www.zhongzhuan.com)
② 把调起微信授权代码放到 (http://www.zhongzhuan.com/index.php)
<?php
const APPID="";
class Wx_auth{
//准备scope为snsapi_userInfo网页授权页面,获取code
public static function authorize($params){
//返回类型,请填写code
$responseType = $params['response_type'];
//应用授权作用域
$scope = $params['scope'];
//重定向后会带上state参数,自定义
$state = $params['state'];
//这里的域名就是公众号设置的域名
$redirect_url = 'http://www.zhognzhuan.com/index.php';
$redirect_url = urlencode($redirect_url);
$get_userInfo_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?
appid='.APPID.'&redirect_uri='.$redirect_url.'&response_type='.
$responseType.'&scope='.$scope.'&state='.$state.'#wechat_redirect';
header('Location:'.$get_userInfo_url);
die;
}
//把回调结果返回最开始的授权业务
public static function redirect($code,$state){
$redirect_url = $_COOKIE['redirect_uri'];
header('Location:'.$redirect_url.'?code='.$code.'&state='.$state);
die;
}
}
if(!isset($_GET['code']){
//最开始授权回调地址
if(isset($params['redirect_uri'])){
setcookie('redirect_uri',urldecode($params['redirect_uri']));
}
Wxauth::authorize($_GET);
}else{
Wxauth::redirect($_GET['code'],$_GET['state']);
}
>
③ 另外要授权的域名项目( http://www.a.com ),这时我们先去跳转到中转地址,由中转地址调起授权页面,用户点击授权登录,获取code,state后原封不动的返回到(http://www.a.com/index.php),然后拿到code去获取用户信息
$appid='';
$appsecret='';
//1.准备scope为snsapi_userInfo网页授权页面
$redirect_url = 'http://www.a.com/index.php'
$redirecturl = urlencode($redirect_url);
//参数
$params = [
'redirect_uri' => $redirecturl,
'response_type' => 'code',
'scope' => 'snsapi_userinfo',
'state' => 'fff'
];
$params_str = http_build_query($params);
//中转地址,获取code
$get_code_url = 'http://www.zhognzhuan.com?'.$param_str.'#wechat_redirect';
//2.用户手动同意授权,同意之后,获取code
$code = $_GET['cdoe'];
if(!isset($code)){
header('Location:'.$get_code_url);
die;
}
//3.通过code换取网页授权access_token
$get_access_token_url= 'https://api.weixin.qq.com/sns/oauth2/access_token?
appid='.$appid.'&secret='.$appsecret.'$code='.$code.'&grant_type=authorization_code';
$result = json_decode(file_get_contents($get_access_token_url));
//4.通过access_token和openid拉取用户信息
$get_user_info_url='https://api.weixin.qq.com/sns/userinfo?access_token='.
$result->access_token.'&openid='.$result->openid.'&lang=zh_CN';
$userInfo = file_get_contents($get_user_info_url);
$userInfo = json_decode($userInfo,true);
print_r($userInfo);
栏目分类全部>