微信公众号网页授权登录多域名的解决

由于微信网页开发,需要获取用户信息,所以就需要网页授权,但是在微信公众平台公众号只能设置一个回调域名,现在
只有一个公众号,但是我多个业务不同的域名,并都需要拿到用户信息,这时一个回调域名肯定是不能解决问题的,因为公众号设置的回调域名必须要与项目域名一致,不然就会报redirect_uri域名错误。

实现思路
中转域名地址(http://www.zhongzhuan.com),其他要授权的域名先去请求中转地址,并会把获取的code,state原封不动的返回到原来的地址,这样就可以用返回的code去获取access_token,从而通过access_token获取用户信息
1、我们把微信授权的回调域名设置成中转域名地址(http://www.zhongzhuan.com
2、把调起微信授权代码放到(http://www.zhongzhuan.com/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.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_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.com),这是我们先去跳转到中转地址,由中转地址调起授权页面,用户点击授权登录,获取codestate原封不动的返回到(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"
];
$param_str=urldecode(http_build_query($params));;
//中转地址,获取code
$get_code_url = 'http://www.zhongzhuan.com?'.$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.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);

亲测有效!真正的解决了授权域名回调只能填写一个的问题!

实现思路来源:https://www.cnblogs.com/lyzg/p/6159617.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章