forked from thenbsp/wechat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccessToken.php
More file actions
115 lines (93 loc) · 2.63 KB
/
AccessToken.php
File metadata and controls
115 lines (93 loc) · 2.63 KB
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
110
111
112
113
114
115
<?php
namespace Thenbsp\Wechat\OAuth;
use Thenbsp\Wechat\Bridge\Http;
use Doctrine\Common\Collections\ArrayCollection;
class AccessToken extends ArrayCollection
{
/**
* 刷新 access_token
*/
const REFRESH = 'https://api.weixin.qq.com/sns/oauth2/refresh_token';
/**
* 检测 access_token 是否有效
*/
const IS_VALID = 'https://api.weixin.qq.com/sns/auth';
/**
* 网页授权获取用户信息
*/
const USERINFO = 'https://api.weixin.qq.com/sns/userinfo';
/**
* 用户 access_token 和公众号是一一对应的
*/
protected $appid;
/**
* 构造方法
*/
public function __construct($appid, array $options)
{
$this->appid = $appid;
parent::__construct($options);
}
/**
* 公众号 appid
*/
public function getAppid()
{
return $this->appid;
}
/**
* 获取用户信息
*/
public function getUser($lang = 'zh_CN')
{
if( !$this->isValid() ) {
$this->refresh();
}
$query = array(
'access_token' => $this['access_token'],
'openid' => $this['openid'],
'lang' => $lang
);
$response = Http::request('GET', static::USERINFO)
->withQuery($query)
->send();
if( $response['errcode'] != 0 ) {
throw new \Exception($response['errmsg'], $response['errcode']);
}
return $response;
}
/**
* 刷新用户 access_token
*/
public function refresh()
{
$query = array(
'appid' => $this->appid,
'grant_type' => 'refresh_token',
'refresh_token' => $this['refresh_token']
);
$response = Http::request('GET', static::REFRESH)
->withQuery($query)
->send();
if( $response['errcode'] != 0 ) {
throw new \Exception($response['errmsg'], $response['errcode']);
}
// update new access_token from ArrayCollection
parent::__construct($response->toArray());
return $this;
}
/**
* 检测用户 access_token 是否有效
*/
public function isValid()
{
$query = array(
'access_token' => $this['access_token'],
'openid' => $this['openid']
);
$response = Http::request('GET', static::IS_VALID)
->withQuery($query)
->send();
return ($response['errmsg'] === 'ok');
}
}