const CODE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
const OPENID_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
// 获取用户openid 为避免重复请求接口获取后应做存储
function getOpenId() {
if (isset($_SESSION['openid'])) {
return $_SESSION['openid'];
} else {
// 1、用户访问一个地址 先获取到code
if(!isset($_GET['code'])) {
// 构建回调地址为当前地址
$redUrl = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url = self::CODE_URL . "appid=" .self::APPID ."&redirect_uri={$redUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//响应跳转请求
header("location:{$url}");exit;
} else {
// 2、根据code获取到openid
// 调用接口获取openid
$openidUrl = self::OPENID_URL . "appid=" . self::APPID . "&secret=".self::SECRET . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
$data = file_get_contents($openidUrl);
$arr = json_decode($data, true);
$_SESSION['openid'] = $arr['openid'];
return $_SESSION['openid'];
}
}
}
06-30
4602
11-20
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交