Test Failed
Push — master ( bdd8d4...c21701 )
by Carlos
04:52 queued 02:19
created

AccessToken::autoRefresh()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 0
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
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
 * @see      https://github.com/overtrue
19
 * @see      http://overtrue.me
20
 */
21
22
namespace EasyWeChat\Core;
23
24
use Doctrine\Common\Cache\Cache;
25
use Doctrine\Common\Cache\FilesystemCache;
26
use EasyWeChat\Core\Exceptions\HttpException;
27
28
/**
29
 * Class AccessToken.
30
 */
31
class AccessToken
32
{
33
    /**
34
     * App ID.
35
     *
36
     * @var string
37
     */
38
    protected $appId;
39
40
    /**
41
     * App secret.
42
     *
43
     * @var string
44
     */
45
    protected $secret;
46
47
    /**
48
     * Cache.
49
     *
50
     * @var Cache
51
     */
52
    protected $cache;
53
54
    /**
55
     * Cache Key.
56
     *
57
     * @var string
58
     */
59
    protected $cacheKey;
60
61
    /**
62
     * Http instance.
63
     *
64
     * @var Http
65
     */
66
    protected $http;
67
68
    /**
69
     * Query name.
70
     *
71
     * @var string
72
     */
73
    protected $queryName = 'access_token';
74
75
    /**
76
     * Response Json key name.
77
     *
78
     * @var string
79
     */
80
    protected $tokenJsonKey = 'access_token';
81
82
    /**
83
     * Cache key prefix.
84
     *
85
     * @var string
86
     */
87
    protected $prefix = 'easywechat.common.access_token.';
88
89
    // API
90
    const API_TOKEN_GET = 'https://api.weixin.qq.com/cgi-bin/token';
91
92
    /**
93
     * Constructor.
94
     *
95
     * @param string                       $appId
96
     * @param string                       $secret
97
     * @param \Doctrine\Common\Cache\Cache $cache
98
     */
99 61
    public function __construct($appId, $secret, Cache $cache = null)
100
    {
101 61
        $this->appId = $appId;
102 61
        $this->secret = $secret;
103 61
        $this->cache = $cache;
104 61
    }
105
106
    /**
107
     * Get token from WeChat API.
108
     *
109
     * @param bool $forceRefresh
110
     *
111
     * @return string
112
     */
113 5
    public function getToken($forceRefresh = false)
114
    {
115 5
        $cacheKey = $this->getCacheKey();
116 5
        $cached = $this->getCache()->fetch($cacheKey);
117
118 5
        if ($forceRefresh || empty($cached)) {
119 2
            $token = $this->getTokenFromServer();
120
121
            // XXX: T_T... 7200 - 1500
122 2
            $this->getCache()->save($cacheKey, $token[$this->tokenJsonKey], $token['expires_in'] - 1500);
123
124 2
            return $token[$this->tokenJsonKey];
125
        }
126
127 4
        return $cached;
128
    }
129
130
    /**
131
     * 设置自定义 token.
132
     *
133
     * @param string $token
134
     * @param int    $expires
135
     *
136
     * @return $this
137
     */
138 2
    public function setToken($token, $expires = 7200)
139
    {
140 2
        $this->getCache()->save($this->getCacheKey(), $token, $expires - 1500);
141
142 2
        return $this;
143
    }
144
145
    /**
146
     * Return the app id.
147
     *
148
     * @return string
149
     */
150 20
    public function getAppId()
151
    {
152 20
        return $this->appId;
153
    }
154
155
    /**
156
     * Return the secret.
157
     *
158
     * @return string
159
     */
160 2
    public function getSecret()
161
    {
162 2
        return $this->secret;
163
    }
164
165
    /**
166
     * Set cache instance.
167
     *
168
     * @param \Doctrine\Common\Cache\Cache $cache
169
     *
170
     * @return AccessToken
171
     */
172 2
    public function setCache(Cache $cache)
173
    {
174 2
        $this->cache = $cache;
175
176 2
        return $this;
177
    }
178
179
    /**
180
     * Return the cache manager.
181
     *
182
     * @return \Doctrine\Common\Cache\Cache
183
     */
184 5
    public function getCache()
185
    {
186 5
        return $this->cache ?: $this->cache = new FilesystemCache(sys_get_temp_dir());
187
    }
188
189
    /**
190
     * Set the query name.
191
     *
192
     * @param string $queryName
193
     *
194
     * @return $this
195
     */
196 1
    public function setQueryName($queryName)
197
    {
198 1
        $this->queryName = $queryName;
199
200 1
        return $this;
201
    }
202
203
    /**
204
     * Return the query name.
205
     *
206
     * @return string
207
     */
208 1
    public function getQueryName()
209
    {
210 1
        return $this->queryName;
211
    }
212
213
    /**
214
     * Return the API request queries.
215
     *
216
     * @return array
217
     */
218 1
    public function getQueryFields()
219
    {
220 1
        return [$this->queryName => $this->getToken()];
221
    }
222
223
    /**
224
     * Get the access token from WeChat server.
225
     *
226
     * @throws \EasyWeChat\Core\Exceptions\HttpException
227
     *
228
     * @return string
229
     */
230 2 View Code Duplication
    public function getTokenFromServer()
231
    {
232
        $params = [
233 2
            'appid' => $this->appId,
234 2
            'secret' => $this->secret,
235 2
            'grant_type' => 'client_credential',
236 2
        ];
237
238 2
        $http = $this->getHttp();
239
240 2
        $token = $http->parseJSON($http->get(self::API_TOKEN_GET, $params));
241
242 2
        if (empty($token[$this->tokenJsonKey])) {
243 1
            throw new HttpException('Request AccessToken fail. response: '.json_encode($token, JSON_UNESCAPED_UNICODE));
244
        }
245
246 2
        return $token;
247
    }
248
249
    /**
250
     * Return the http instance.
251
     *
252
     * @return \EasyWeChat\Core\Http
253
     */
254 2
    public function getHttp()
255
    {
256 2
        return $this->http ?: $this->http = new Http();
257
    }
258
259
    /**
260
     * Set the http instance.
261
     *
262
     * @param \EasyWeChat\Core\Http $http
263
     *
264
     * @return $this
265
     */
266 2
    public function setHttp(Http $http)
267
    {
268 2
        $this->http = $http;
269
270 2
        return $this;
271
    }
272
273
    /**
274
     * Set the access token prefix.
275
     *
276
     * @param string $prefix
277
     *
278
     * @return $this
279
     */
280
    public function setPrefix($prefix)
281
    {
282
        $this->prefix = $prefix;
283
284
        return $this;
285
    }
286
287
    /**
288
     * Set access token cache key.
289
     *
290
     * @param string $cacheKey
291
     *
292
     * @return $this
293
     */
294
    public function setCacheKey($cacheKey)
295
    {
296
        $this->cacheKey = $cacheKey;
297
298
        return $this;
299
    }
300
301
    /**
302
     * Get access token cache key.
303
     *
304
     * @return string $this->cacheKey
305
     */
306 5
    public function getCacheKey()
307
    {
308 5
        if (is_null($this->cacheKey)) {
309 5
            return $this->prefix.$this->appId;
310
        }
311
312
        return $this->cacheKey;
313
    }
314
}
315