在 PHP 中实现微信公众号授权登录,可以按照以下步骤:
- 在微信公众平台创建应用或者在开放平台注册成为开发者;
- 根据文档获取 appid 和 appsecret;
- 构造授权 URL,带上 redirect_uri、appid、scope、state 参数(如果需要的话);
- 用户打开授权 URL,同意后会重定向到回调地址(即 redirect_uri);
- 在回调地址页面中,获取授权 code;
- 使用授权 code 换取 access_token 和 openid;
- 将 access_token 和 openid 保存在服务器端,用于后续访问微信 API;
- 如果需要,可以使用 access_token 来获取用户信息。
以下是 PHP 代码示例:
// 1. 构造授权 URL
$redirect_uri = urlencode("http://example.com/callback.php");
$scope = "snsapi_userinfo";
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state=STATE#wechat_redirect";
// 2. 用户打开授权 URL 同意后会重定向到回调地址
// 在回调地址中获取授权 code
$code = $_GET["code"];
// 3. 使用授权 code 换取 access_token 和 openid
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
$res = file_get_contents($url);
$res = json_decode($res, true);
$access_token = $res["access_token"];
$openid = $res["openid"];
// 4. 如果需要,可以使用 access_token 来获取用户信息
$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
$res = file_get_contents($url);
$res = json_decode($res, true);
$nickname = $res["nickname"];
$avatar = $res["headimgurl"];
以上代码仅供参考,实际开发中还需要考虑异常情况的处理。