admin管理员组文章数量:1558098
由于微信网页开发,需要获取用户信息,所以就需要网页授权,但是在微信公众平台公众号只能设置一个回调域名,现在
只有一个公众号,但是我多个业务不同的域名,并都需要拿到用户信息,这时一个回调域名肯定是不能解决问题的,因为公众号设置的回调域名必须要与项目域名一致,不然就会报redirect_uri域名错误。
实现思路:
中转域名地址(http://www.zhongzhuan),其他要授权的域名先去请求中转地址,并会把获取的code
,state
原封不动的返回到原来的地址,这样就可以用返回的code
去获取access_token
,从而通过access_token
获取用户信息
1、我们把微信授权的回调域名设置成中转域名地址(http://www.zhongzhuan)
2、把调起微信授权代码放到(http://www.zhongzhuan/index.php)
<?php
const APPID="";
class Wx_auth{
//准备scope为snsapi_userInfo网页授权页面,获取code
public static function authorize($params){
$responseType=$params['response_type'];//返回类型,请填写code
$scope=$params['scope'];//应用授权作用域
$state=$params['state'];//重定向后会带上state参数 自定义
$redirect_url='http://www.zhongzhuan/index.php';//这里的域名就是公众号设置的域名
$redirect_url = urlencode($redirect_url);
$get_userInfo_url = 'https://open.weixin.qq/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_uri=$_COOKIE['redirect_uri'];
header('Location:'.$redirect_uri.'?code='.$code."&state=".$state);die;
}
}
if(!isset($_GET['code'])){
//最开始授权回调地址
if(isset($params['redirect_uri'])){
setcookie('redirect_uri',urldecode($params['redirect_uri']));
}
Wx_auth::authorize($_GET);
}else{
Wx_auth::redirect($_GET['code'],$_GET['state']);
}
3、另外要授权的域名项目(http://www.a),这是我们先去跳转到中转地址,由中转地址调起授权页面,用户点击授权登录,获取code
,state
原封不动的返回到(http://www.a/index.php),然后拿到code去获取用户信息
$appid='';
$appsecret='';
//1.准备scope为snsapi_userInfo网页授权页面
$redirect_url='http://www.a/index.php';
$redirecturl = urlencode($redirect_url);
//参数
$params=[
'redirect_uri'=>$redirecturl,
'response_type'=>'code',
'scope'=>"snsapi_userinfo",
'state'=>"fff"
];
$param_str=urldecode(http_build_query($params));;
//中转地址,获取code
$get_code_url = 'http://www.zhongzhuan?'.$param_str.'#wechat_redirect';
//2.用户手动同意授权,同意之后,获取code
$code = $_GET['code'];
if( !isset($code) ){
header('Location:'.$get_code_url);die;
}
//3.通过code换取网页授权access_token
$get_access_token_url = 'https://api.weixin.qq/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/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);
亲测有效!真正的解决了授权域名回调只能填写一个的问题!
实现思路来源:https://wwwblogs/lyzg/p/6159617.html
版权声明:本文标题:微信公众号网页授权登录多域名的解决 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1727388732a1112483.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论