-
-
Save edk24/e8c368ea548a4d209876ded94828a8f3 to your computer and use it in GitHub Desktop.
微信公众号授权登录处理类库
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace library\wechat; | |
use RuntimeException; | |
class Login { | |
protected $appid; | |
protected $appsenret; | |
public function __construct(string $appid, string $appsenret) | |
{ | |
$this->appid = $appid; | |
$this->appsenret = $appsenret; | |
} | |
/** | |
* 生成授权登录地址 | |
* | |
* @param string $scope 授权类型: snsapi_base 静默 | snsapi_userinfo 完全 | |
* @param string $redirect_uri 重定向地址 | |
* @return string | |
* @link https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html | |
*/ | |
public function buildAuthorizeUrl(string $scope = 'snsapi_userinfo', string $redirect_uri): string | |
{ | |
$redirect_uri = urlencode($redirect_uri); | |
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE#wechat_redirect"; | |
$url = sprintf($url, $this->appid, $redirect_uri, $scope); | |
return $url; | |
} | |
/** | |
* code换access_token | |
* | |
* @param string $code | |
* @return array 返回 array($access_token, $openid) | |
* @link https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html | |
*/ | |
public function code2accessToken(string $code): array | |
{ | |
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; | |
$url = sprintf($url, $this->appid, $this->appsenret, $code); | |
$response = json_decode(file_get_contents($url), true); | |
if (!isset($response['access_token'])) { | |
throw new RuntimeException('微信授权失败: ' . json_encode($response)); | |
} | |
return [$response['access_token'], $response['openid']]; | |
} | |
/** | |
* 获取用户信息 | |
* | |
* @param string $access_token | |
* @param string $openid | |
* @return array | |
* @link https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html | |
*/ | |
public function getUserInfo($access_token, $openid): array | |
{ | |
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"; | |
$url = sprintf($url, $access_token, $openid); | |
$response = json_decode(file_get_contents($url), true); | |
if (!isset($response['openid'])) { | |
throw new RuntimeException('微信获取用户信息失败: ' . json_encode($response)); | |
} | |
return $response; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用方法
接口部分
接口
前端部分