2023-12-26 714
<?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 get_userinfo($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'];
// var_dump($access_token_json);
//拉取用户信息(需scope为 snsapi_userinfo) 如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
$res = https_request($url);
return json_decode($res, true);
}
// 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;
}
$json_arr = get_userinfo($code);
// 用户头像、昵称
$nickname = $json_arr['nickname'];
$headimgurl = $json_arr['headimgurl'];
?>
<!-- 用户信息展示 -->
<h1><?= $nickname ?></h1>
<div><img src="<?= $headimgurl ?>" style="width:200px;"></div>