Browse Source

test

master
用户名 3 years ago
parent
commit
da9deb6c53
  1. 83
      mobile/blank.php

83
mobile/blank.php

@ -9,63 +9,38 @@ $appid = 'wx79343915f99167e6';
$appsecret = 'f2f72c5e0ac29c2373bfaf22cf059c02';
$redirect_uri = 'https://shop.heavenk.com/mobile/blank.php'; // 回调URL
// 构造授权链接
$auth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize'
. '?appid=' . urlencode($appid)
. '&redirect_uri=' . urlencode($redirect_uri)
. '&response_type=code'
. '&scope=snsapi_userinfo' // snsapi_base 只获取openid,snsapi_userinfo 获取用户信息
. '&state=STATE'; // wechat_redirect
// 如果用户已经授权,则重定向到回调URL,并获取用户的openid
if (isset($_GET['code'])) {
$code = $_GET['code'];
// 构造获取access_token的URL
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token'
. '?appid=' . urlencode($appid)
. '&secret=' . urlencode($appsecret)
. '&code=' . urlencode($code)
. '&grant_type=authorization_code';
// 发送HTTP请求获取access_token
// 创建一个cURL句柄
$ch = curl_init();
// 设置请求的URL和其他选项
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 发送HTTP GET请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if(curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch);
}
// 关闭cURL句柄
curl_close($ch);
// 输出响应
$response = json_decode($response);
// var_dump($response->openid);
var_dump($response);
$_SESSION['openid'] = $response->openid;
// return $response->openid;
// 获取授权 code
if (!isset($_GET['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;
}
// 跳回原来的页面
$redirect_url = $referer;
// var_dump($redirect_url);
// header("Location: $redirect_url");
// exit;
// 获取 access_token 和 openid
$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;
}
} else {
// 如果没有授权,则重定向到授权页面
header('Location: ' . $auth_url);
var_dump($referer);
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);
?>
Loading…
Cancel
Save