Completed
Push — master ( 3bbe72...a1f8d5 )
by Carlos
05:23 queued 02:38
created

AccessToken::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
/**
13
 * AccessToken.php.
14
 *
15
 * @author    overtrue <[email protected]>
16
 * @copyright 2015 overtrue <[email protected]>
17
 *
18
 * @link      https://github.com/overtrue
19
 * @link      http://overtrue.me
20
 */
21
namespace EasyWeChat\Core;
22
23
use Doctrine\Common\Cache\Cache;
24
use Doctrine\Common\Cache\FilesystemCache;
25
use EasyWeChat\Core\Exceptions\HttpException;
26
27
/**
28
 * Class AccessToken.
29
 */
30
class AccessToken
31
{
32
    /**
33
     * App ID.
34
     *
35
     * @var string
36
     */
37
    protected $appId;
38
39
    /**
40
     * App secret.
41
     *
42
     * @var string
43
     */
44
    protected $secret;
45
46
    /**
47
     * Cache.
48
     *
49
     * @var Cache
50
     */
51
    protected $cache;
52
53
    /**
54
     * Http instance.
55
     *
56
     * @var Http
57
     */
58
    protected $http;
59
60
    /**
61
     * Query name.
62
     *
63
     * @var string
64
     */
65
    protected $queryName = 'access_token';
66
67
    /**
68
     * Cache key prefix.
69
     *
70
     * @var string
71
     */
72
    protected $prefix = 'easywechat.common.access_token.';
73
74
    // API
75
    const API_TOKEN_GET = 'https://api.weixin.qq.com/cgi-bin/token';
76
77
    /**
78
     * Constructor.
79
     *
80
     * @param string                      $appId
81
     * @param string                      $secret
82
     * @param Doctrine\Common\Cache\Cache $cache
83
     */
84 12
    public function __construct($appId, $secret, Cache $cache = null)
85
    {
86 12
        $this->appId = $appId;
87 12
        $this->secret = $secret;
88 12
        $this->cache = $cache;
89 12
    }
90
91
    /**
92
     * Get token from WeChat API.
93
     *
94
     * @param bool $forceRefresh
95
     *
96
     * @return string
97
     */
98 3
    public function getToken($forceRefresh = false)
99
    {
100 3
        $cacheKey = $this->prefix.$this->appId;
101
102 3
        $cached = $this->getCache()->fetch($cacheKey);
103
104 3
        if ($forceRefresh || !$cached) {
105 2
            $token = $this->getTokenFromServer();
106
107
            // XXX: T_T... 7200 - 1500
108 2
            $this->getCache()->save($cacheKey, $token['access_token'], $token['expires_in'] - 1500);
109
110 2
            return $token['access_token'];
111
        }
112
113 2
        return $cached;
114
    }
115
116
    /**
117
     * Return the app id.
118
     *
119
     * @return string
120
     */
121 6
    public function getAppId()
122
    {
123 6
        return $this->appId;
124
    }
125
126
    /**
127
     * Return the secret.
128
     *
129
     * @return string
130
     */
131 1
    public function getSecret()
132
    {
133 1
        return $this->secret;
134
    }
135
136
    /**
137
     * Set cache instance.
138
     *
139
     * @param \Doctrine\Common\Cache\Cache $cache
140
     */
141 1
    public function setCache(Cache $cache)
142
    {
143 1
        $this->cache = $cache;
144
145 1
        return $this;
146
    }
147
148
    /**
149
     * Return the cache manager.
150
     *
151
     * @return \Doctrine\Common\Cache\Cache
152
     */
153 3
    public function getCache()
154
    {
155 3
        return $this->cache ?: $this->cache = new FilesystemCache(sys_get_temp_dir());
156
    }
157
158
    /**
159
     * Set the query name.
160
     *
161
     * @param string $queryName
162
     *
163
     * @return $this
164
     */
165 1
    public function setQueryName($queryName)
166
    {
167 1
        $this->queryName = $queryName;
168
169 1
        return $this;
170
    }
171
172
    /**
173
     * Return the query name.
174
     *
175
     * @return string
176
     */
177 1
    public function getQueryName()
178
    {
179 1
        return $this->queryName;
180
    }
181
182
    /**
183
     * Return the API request queries.
184
     *
185
     * @return array
186
     */
187 1
    public function getQueryFields()
188
    {
189 1
        return [$this->queryName => $this->getToken()];
190
    }
191
192
    /**
193
     * Get the access token from WeChat server.
194
     *
195
     * @return array|bool
196
     */
197 2
    public function getTokenFromServer()
198
    {
199
        $params = [
200 2
            'appid' => $this->appId,
201 2
            'secret' => $this->secret,
202 2
            'grant_type' => 'client_credential',
203 2
        ];
204
205 2
        $http = $this->getHttp();
206
207 2
        $token = $http->parseJSON($http->get(self::API_TOKEN_GET, $params));
208
209 2
        if (empty($token['access_token'])) {
210 1
            throw new HttpException('Request AccessToken fail. response: '.json_encode($token, JSON_UNESCAPED_UNICODE));
211
        }
212
213 2
        return $token;
214
    }
215
216
    /**
217
     * Return the http instance.
218
     *
219
     * @return \EasyWeChat\Core\Http
220
     */
221 2
    public function getHttp()
222
    {
223 2
        return $this->http ?: $this->http = new Http();
224
    }
225
226
    /**
227
     * Set the http instance.
228
     *
229
     * @param \EasyWeChat\Core\Http $http
230
     *
231
     * @return $this
232
     */
233 2
    public function setHttp(Http $http)
234
    {
235 2
        $this->http = $http;
236
237 2
        return $this;
238
    }
239
}
240