2023-12-26 681
<?php
$code = $_GET["code"];
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ($code == '') {
oauth1($url);
}
function oauth1($url)
{
$appid = "****公众号appid";
// 用户同意授权,获取code
$redirect_uri = urlencode($url);
// 关于特殊场景下的静默授权
// 上面已经提到,对于以snsapi_base为scope的网页授权,就静默授权的,用户无感知;
// 对于已关注公众号的用户,如果用户从公众号的会话或者自定义菜单进入本公众号的网页授权页,即使是scope为snsapi_userinfo,也是静默授权,用户无感知
// header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
}
// 判断是否关注公众号
function is_subscribe($openid)
{
// 基础支持中的access_token(与通过code换取网页授权access_token不同)
$access_token = get_access_token();
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
$res = https_request($url);
$res_array = json_decode($res, true);
return $res_array;
}
// 基础支持中的access_token(与通过code换取网页授权access_token不同)
function get_access_token()
{
$appid = "****公众号appid";
$appsecret = "****公众号appsecret";
// 获取access_token
$access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
$access_token_json = https_request($access_token_url);
$access_token_array = json_decode($access_token_json, true);
$access_token = $access_token_array['access_token'];
return $access_token;
}
function get_openid($code)
{
$appid = "****公众号appid";
$appsecret = "****公众号appsecret";
// 通过code换取网页授权access_token、openid
$access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
$access_token_json = https_request($access_token_url);
$access_token_array = json_decode($access_token_json, true);
// $access_token = $access_token_array['access_token'];
$openid = $access_token_array['openid'];
return $openid;
}
// curl请求
function https_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
$openid = get_openid($code);
$gzh_arr = is_subscribe($openid);
if ($gzh_arr['subscribe'] == 1) {
echo "已关注";
} else {
echo "未关注";
}