php 写一个公众平台登录
时间: 2023-10-10 12:14:03 浏览: 30
要实现公众平台登录,你需要了解 OAuth2.0 协议。以下是一个简单的 PHP 示例代码,可供参考:
```php
<?php
// 公众平台的 appid 和 appsecret
$appid = "your_app_id";
$appsecret = "your_app_secret";
// 用户授权后回调 URL
$redirect_uri = "http://yourdomain.com/callback.php";
// 用户授权,获取 code
if (!isset($_GET["code"])) {
$url = "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: $url");
exit;
}
// 使用 code 换取 access_token 和 openid
$code = $_GET["code"];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
$response = file_get_contents($url);
$data = json_decode($response, true);
$access_token = $data["access_token"];
$openid = $data["openid"];
// 使用 access_token 和 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);
// 输出用户信息
echo "昵称:" . $userinfo["nickname"] . "<br>";
echo "性别:" . ($userinfo["sex"] == 1 ? "男" : ($userinfo["sex"] == 2 ? "女" : "未知")) . "<br>";
echo "城市:" . $userinfo["city"] . "<br>";
echo "头像:<img src='" . $userinfo["headimgurl"] . "'><br>";
?>
```
在上述代码中,首先需要编写一个链接,引导用户进入授权页面。当用户授权后,会重定向回你指定的回调 URL,并携带一个 code 参数。接下来,使用这个 code 参数向公众平台发起请求,获取 access_token 和 openid。最后,使用 access_token 和 openid 获取用户信息。