由於微信網頁開發,需要獲取用戶信息,所以就需要網頁授權,但是在微信公衆平臺公衆號只能設置一個回調域名,現在
只有一個公衆號,但是我多個業務不同的域名,並都需要拿到用戶信息,這時一個回調域名肯定是不能解決問題的,因爲公衆號設置的回調域名必須要與項目域名一致,不然就會報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),這是我們先去跳轉到中轉地址,由中轉地址調起授權頁面,用戶點擊授權登錄,獲取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"
];
$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);
親測有效!真正的解決了授權域名回調只能填寫一個的問題!