公众号开发过程中可能会遇到多个系统同时需要做网页授权,这些系统访问域名又各不相同,这就存在网页授权域名限制的问题。解决办法是,将网页授权第一步放在同一个网址,例如http://domain/oauth2.php?appid=APPID&redirect_uri=REDIRECT_URI&scope=snsapi_userinfo
以下是oauth2.php文件示例:
<?php
function ToUrlParams($urlObj)
{
$buff = "";
foreach ($urlObj as $k => $v)
{
if($k != "sign"){
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
return $buff;
}
function CreateOauthUrlForCode($redirectUrl,$appId,$scope)
{
$urlObj["appid"] = $appId;
$urlObj["redirect_uri"] = urlencode($redirectUrl);
$urlObj["response_type"] = "code";
$urlObj["scope"] = $scope;
$urlObj["state"] = "STATE"."#wechat_redirect";
$bizString = ToUrlParams($urlObj);
return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
}
if (!isset($_GET['code'])){
if(!isset($_GET['redirect_uri']) || !isset($_GET['appid'])){
echo '参数信息不全,请求示例:http://domain/oauth2.php?appid=APPID&redirect_uri=REDIRECT_URI&scope=snsapi_userinfo';
echo '可选参数scope,参考值:snsapi_base或snsapi_userinfo';
exit;
}
$appid = $_GET['appid'];
$scope = isset($_GET['scope']) ? $_GET['scope'] : 'snsapi_base';
$redirectUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if(strpos($redirectUrl,'?') !== false){
$redirectUrl .= "&redirect_uri=" . urlencode($_GET['redirect_uri']);
} else {
$redirectUrl .= "?redirect_uri=" . urlencode($_GET['redirect_uri']);
}
$url = CreateOauthUrlForCode($redirectUrl,$appid,$scope);
Header("Location: $url");
exit;
} else {
//获取授权码
$code = $_GET['code'];
$redirectUrl = $_GET['redirect_uri'];
if(strpos($redirectUrl,'?') !== false){
$redirectUrl .= "&code=" . urlencode($code);
} else {
$redirectUrl .= "?code=" . urlencode($code);
}
Header("Location: $redirectUrl");
exit;
}
?>
获取授权码后跳转到目标系统,目标系统可通过code获取用户信息,如此便避开了授权域名限制。
当然也可以采用另一种方案,就是获取用户信息后再跳转到目标系统。