You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

59 lines
1.9 KiB

<?php
// 配置参数
$app_id = 'wx79343915f99167e6';
$app_secret = 'f2f72c5e0ac29c2373bfaf22cf059c02';
$redirect_uri = 'http://192.168.50.21/mobile/testauth.php'; // 授权后跳转的回调地址
// 处理授权请求
if (isset($_GET['auth'])) {
// 获取授权 code
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $app_id . '&redirect_uri=' . urlencode($redirect_uri) . '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
header('Location: ' . $url);
exit;
}
// 获取 access_token 和 openid
if (isset($_GET['code'])) {
$code = $_GET['code'];
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $app_id . '&secret=' . $app_secret . '&code=' . $code . '&grant_type=authorization_code';
$response = file_get_contents($url);
$data = json_decode($response, true);
if (!$data || !isset($data['access_token']) || !isset($data['openid'])) {
// 授权失败
echo '授权失败,请重试';
exit;
}
// 获取用户信息
$access_token = $data['access_token'];
$openid = $data['openid'];
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
$response = file_get_contents($url);
$userinfo = json_decode($response, true);
if (!$userinfo || !isset($userinfo['openid'])) {
// 获取用户信息失败
echo '获取用户信息失败,请重试';
exit;
}
// 用户授权成功,这里可以将用户信息保存到数据库中,或者进行其他操作
var_dump($userinfo);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试页面</title>
</head>
<body>
<button onclick="auth()">授权</button>
<script>
function auth() {
window.location.href = '?auth=1';
}
</script>
</body>
</html>