forked from xjflyttp/yii2-oauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWeixinAuth.php
109 lines (95 loc) · 2.91 KB
/
WeixinAuth.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace xj\oauth;
use yii\authclient\OAuth2;
use yii\authclient\OAuthToken;
/**
* Weixin OAuth
* @author xjflyttp <[email protected]>
* @see https://open.weixin.qq.com/cgi-bin/showdocument?action=doc&id=open1419316505&t=0.1933593254077447
*/
class WeixinAuth extends OAuth2 implements IAuth
{
public $authUrl = 'https://open.weixin.qq.com/connect/qrconnect';
public $tokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
public $apiBaseUrl = 'https://api.weixin.qq.com';
public $scope = 'snsapi_login';
/**
* Composes user authorization URL.
* @param array $params additional auth GET params.
* @return string authorization URL.
*/
public function buildAuthUrl(array $params = [])
{
$defaultParams = [
'appid' => $this->clientId,
'redirect_uri' => $this->getReturnUrl(),
'response_type' => 'code',
];
if (!empty($this->scope)) {
$defaultParams['scope'] = $this->scope;
}
return $this->composeUrl($this->authUrl, array_merge($defaultParams, $params));
}
/**
* Fetches access token from authorization code.
* @param string $authCode authorization code, usually comes at $_GET['code'].
* @param array $params additional request params.
* @return OAuthToken access token.
*/
public function fetchAccessToken($authCode, array $params = [])
{
$defaultParams = [
'appid' => $this->clientId,
'secret' => $this->clientSecret,
'code' => $authCode,
'grant_type' => 'authorization_code',
];
$response = $this->sendRequest('POST', $this->tokenUrl, array_merge($defaultParams, $params));
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
/**
* @inheritdoc
*/
protected function apiInternal($accessToken, $url, $method, array $params, array $headers)
{
$params['access_token'] = $accessToken->getToken();
$params['openid'] = $this->getOpenid();
return $this->sendRequest($method, $url, $params, $headers);
}
/**
*
* @return []
* @see https://open.weixin.qq.com/cgi-bin/showdocument?action=doc&id=open1419316518&t=0.14920092844688204
*/
protected function initUserAttributes()
{
return $this->api('sns/userinfo');
}
/**
* get UserInfo
* @return []
* @see http://open.weibo.com/wiki/2/users/show
*/
public function getUserInfo()
{
return $this->getUserAttributes();
}
/**
* @return string
*/
public function getOpenid()
{
$attributes = $this->getUserAttributes();
return $attributes['openid'];
}
protected function defaultName()
{
return 'Weixin';
}
protected function defaultTitle()
{
return 'Weixin';
}
}