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.

70 lines
3.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace LaneWeChat\Core;
// WeChatOAuth类用于处理微信OAuth认证流程。
class WeChatOAuth{
// getCode静态方法用于生成用户授权的URL并重定向用户到微信授权页面。
public static function getCode($redirect_uri, $state=1, $scope='snsapi_base'){
// 如果redirect_uri以'/'开头,则去掉它。
if($redirect_uri[0] == '/'){
$redirect_uri = substr($redirect_uri, 1);
}
// 从配置中获取appid。
$appid = WECHAT_APPID;
// 将redirect_uri添加到WECHAT_URL后进行URL编码。
$redirect_uri = WECHAT_URL . $redirect_uri;
$redirect_uri = urlencode($redirect_uri);
// 设置response_type为code表示期望的响应类型是授权码。
$response_type = 'code';
// 构造微信授权URL。
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=' . $response_type . '&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
// 发送HTTP重定向响应到微信授权URL。
header('Location: ' . $url, true, 301);
}
// getAccessTokenAndOpenId静态方法用于通过授权码获取access_token和openid。
public static function getAccessTokenAndOpenId($code){
// 设置grant_type为authorization_code表示使用授权码换取access_token。
$grant_type = 'authorization_code';
// 构造获取access_token的URL。
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . WECHAT_APPID . '&secret=' . WECHAT_APPSECRET . '&code=' . $code . '&grant_type=' . $grant_type;
// 调用Curl类的方法发送请求并获取结果。
return Curl::callWebServer($url);
}
// refreshToken静态方法用于刷新access_token。
public static function refreshToken($refreshToken){
// 构造刷新access_token的URL。
$queryUrl = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . WECHAT_APPID . '&grant_type=refresh_token&refresh_token=' . $refreshToken;
$queryAction = 'GET';
// 调用Curl类的方法发送请求并获取结果。
return Curl::callWebServer($queryUrl, '', $queryAction);
}
// getUserInfo静态方法用于获取用户信息。
public static function getUserInfo($accessToken, $openId, $lang='zh_CN'){
// 构造获取用户信息的URL。
$queryUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accessToken . '&openid=' . $openId . '&lang=' . $lang;
$queryAction = 'GET';
// 调用Curl类的方法发送请求并获取结果。
return Curl::callWebServer($queryUrl, '', $queryAction);
}
// checkAccessToken静态方法用于检查access_token是否有效。
public static function checkAccessToken($accessToken, $openId){
// 构造检查access_token的URL。
$queryUrl = 'https://api.weixin.qq.com/sns/auth?access_token=' . $accessToken . '&openid=' . $openId;
$queryAction = 'GET';
// 调用Curl类的方法发送请求并获取结果。
return Curl::callWebServer($queryUrl, '', $queryAction);
}
}