forked from thenbsp/wechat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AccessToken.php
103 lines (85 loc) · 2.22 KB
/
AccessToken.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
<?php
namespace Thenbsp\Wechat;
use Thenbsp\Wechat\Wechat;
use Thenbsp\Wechat\Util\Http;
use Thenbsp\Wechat\Util\Cache;
class AccessToken
{
/**
* AccessToken 接口地址
*/
const ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/cgi-bin/token';
/**
* 公众号对象
*/
protected $wechat;
/**
* 缓存对象
*/
protected $cache;
/**
* 构造方法
*/
public function __construct(Wechat $wechat, Cache $cache)
{
$this->wechat = $wechat;
$this->cache = $cache;
}
/**
* 获取 Wechat 对象
*/
public function getWechat()
{
return $this->wechat;
}
/**
* 获取 Cache 对象
*/
public function getCache()
{
return $this->cache;
}
/**
* 获取 AccessToken
*/
public function getAccessToken()
{
$key = $this->_getCacheName();
if( $value = $this->cache->get($key) ) {
if( array_key_exists('access_token', $value) &&
array_key_exists('expires_in', $value) ) {
return $value['access_token'];
}
}
$value = $this->_getAccessToken();
// set cache
$this->cache->set($key, $value, $value['expires_in']);
return $value['access_token'];
}
/**
* 获取 AccessToken(从 API 获取)
*/
protected function _getAccessToken()
{
$request = Http::get(self::ACCESS_TOKEN_URL, array(
'query' => array(
'grant_type' => 'client_credential',
'appid' => $this->wechat['appid'],
'secret' => $this->wechat['appsecret']
)
));
$response = $request->json();
if( array_key_exists('access_token', $response) &&
array_key_exists('expires_in', $response) ) {
return $response;
}
throw new \Exception($response['errcode'].': '.$response['errmsg']);
}
/**
* 获取缓存名称
*/
protected function _getCacheName()
{
return $this->wechat['appid'].'_access_token';
}
}