<?php
$retrunUrl = $_GET['returnUrl'];
$parkId = $_GET['parkId'];
//此处请求java接口获取appid,secret,或直接取值
$appid = 'appid';
$appsecret = 'appsecret';
//通过code获得openid
if (!isset($_GET['code'])){
//触发微信返回code码
//此处若使用了https负载均衡,则可以直接固定值:https
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://": "http://";
$baseUrl = urlencode($protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$urlObj["appid"] = $appid;
$urlObj["redirect_uri"] = $baseUrl;
$urlObj["response_type"] = "code";
$urlObj["scope"] = "snsapi_base"; //snsapi_base、snsapi_userinfo
$urlObj["state"] = "STATE" . "#wechat_redirect";
$bizString = ToUrlParams($urlObj);
$codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
// echo $codeUrl;
echo json_encode(
array(
"status"=>"200",
"massage"=>"OK",
"data"=>$codeUrl
)
);
exit();
} else {
//获取code码,以获取openid
$code = $_GET['code'];
$openid = getUserOpenid($appid, $appsecret, $code);
if(!strstr(urldecode($retrunUrl), '?')){
$newUrl = urldecode($retrunUrl)."?openid=".$openid;
}else{
$newUrl = urldecode($retrunUrl)."&openid=".$openid;
}
// echo $newUrl;
Header("Location: $newUrl");
exit();
}
/**
*
*
* @param string $code 微信跳转回来带上的code
*
* @return openid
*/
function getUserOpenid($appid, $appsecret, $code)
{
$urlObj["appid"] = $appid;
$urlObj["secret"] = $appsecret;
$urlObj["code"] = $code;
$urlObj["grant_type"] = "authorization_code";
$bizString = ToUrlParams($urlObj);
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?" . $bizString;
$res = httpRequest($url);
//取出openid
$data = json_decode($res);
$openid = $data->openid;
return $openid;
}
/**
*
* 拼接签名字符串
* @param array $urlObj
*
* @return 返回已经拼接好的字符串
*/
function ToUrlParams($urlObj)
{
$buff = "";
foreach ($urlObj as $k => $v) {
if ($k != "sign") {
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
return $buff;
}
/**
* 构造获取http请求
* @param string $url 请求接口的url,需要url编码
* @param string $data 请求时传递的数据,GET时为null
* @param string $cookies 是否需要缓存状态
* @return 返回请求接口返回的数据
*/
function httpRequest($url, $data = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
?>