Completed
Push — master ( 931b65...d2ebaa )
by Carlos
03:47
created

Authorization::getApi()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
ccs 0
cts 2
cp 0
crap 2
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
 * Authorization.php.
14
 *
15
 * Part of Overtrue\WeChat.
16
 *
17
 * For the full copyright and license information, please view the LICENSE
18
 * file that was distributed with this source code.
19
 *
20
 * @author    lixiao <[email protected]>
21
 * @author    mingyoung <[email protected]>
22
 * @copyright 2016
23
 *
24
 * @see      https://github.com/overtrue
25
 * @see      http://overtrue.me
26
 */
27
28
namespace EasyWeChat\OpenPlatform;
29
30
use Doctrine\Common\Cache\Cache;
31
use EasyWeChat\Core\Exception;
32
use EasyWeChat\OpenPlatform\Api\BaseApi;
33
use EasyWeChat\Support\Collection;
34
35
class Authorization
36
{
37
    const CACHE_KEY_ACCESS_TOKEN = 'easywechat.open_platform.authorizer_access_token';
38
    const CACHE_KEY_REFRESH_TOKEN = 'easywechat.open_platform.authorizer_refresh_token';
39
40
    /**
41
     * Cache.
42
     *
43
     * @var \Doctrine\Common\Cache\Cache
44
     */
45
    protected $cache;
46
47
    /**
48
     * Base API.
49
     *
50
     * @var \EasyWeChat\OpenPlatform\Api\BaseApi
51
     */
52
    private $api;
53
54
    /**
55
     * Open Platform App Id, aka, Component App Id.
56
     *
57
     * @var string
58
     */
59
    private $appId;
60
61
    /**
62
     * Authorizer App Id.
63
     *
64
     * @var string
65
     */
66
    private $authorizerAppId;
67
68
    /**
69
     * Auth code.
70
     *
71
     * @var string
72
     */
73
    private $authCode;
74
75
    /**
76
     * Authorization Constructor.
77
     *
78
     * Users need not concern the details.
79
     *
80
     * @param \EasyWeChat\OpenPlatform\Api\BaseApi $api
81
     * @param string                               $appId
82
     * @param \Doctrine\Common\Cache\Cache         $cache
83
     */
84 13
    public function __construct(BaseApi $api, $appId, Cache $cache)
85
    {
86 13
        $this->api = $api;
87 13
        $this->appId = $appId;
88 13
        $this->cache = $cache;
89 13
    }
90
91
    /**
92
     * Gets the base api.
93
     *
94
     * @return \EasyWeChat\OpenPlatform\Api\BaseApi
95
     */
96
    public function getApi()
97
    {
98
        return $this->api;
99
    }
100
101
    /**
102
     * Sets the authorizer app id.
103
     *
104
     * @param string $authorizerAppId
105
     *
106
     * @return $this
107
     */
108 11
    public function setAuthorizerAppId($authorizerAppId)
109
    {
110 11
        $this->authorizerAppId = $authorizerAppId;
111
112 11
        return $this;
113
    }
114
115
    /**
116
     * Gets the authorizer app id, or throws if not found.
117
     *
118
     * @return string
119
     *
120
     * @throws \EasyWeChat\Core\Exception
121
     */
122 9
    public function getAuthorizerAppId()
123
    {
124 9
        if (!$this->authorizerAppId) {
125
            throw new Exception(
126
                'Authorizer App Id is not present, you may not make the authorization yet.'
127
            );
128
        }
129
130 9
        return $this->authorizerAppId;
131
    }
132
133
    /**
134
     * Sets the auth code.
135
     *
136
     * @param $code
137
     */
138
    public function setAuthCode($code)
139
    {
140
        $this->authCode = $code;
141
    }
142
143
    /**
144
     * Gets the auth code.
145
     *
146
     * @return string
147
     */
148 4
    public function getAuthCode()
149
    {
150 4
        return $this->authCode;
151
    }
152
153
    /**
154
     * Sets the auth info from the message of the auth event sent by WeChat.
155
     *
156
     * @param \EasyWeChat\Support\Collection $message
157
     */
158
    public function setFromAuthMessage(Collection $message)
159
    {
160
        if ($authorizerAppId = $message->get('AuthorizerAppid')) {
161
            $this->setAuthorizerAppId($authorizerAppId);
162
        }
163
        if ($authorizationCode = $message->get('AuthorizationCode')) {
164
            $this->setAuthCode($authorizationCode);
165
        }
166
    }
167
168
    /**
169
     * Handles authorization: calls the API, saves the tokens.
170
     *
171
     * @return Collection
172
     */
173 2
    public function handleAuthorization()
174
    {
175 2
        $info = $this->getAuthorizationInfo();
176
177 2
        $appId = $info['authorization_info']['authorizer_appid'];
178 2
        $this->setAuthorizerAppId($appId);
179
180 2
        $this->setAuthorizerAccessToken($info['authorization_info']['authorizer_access_token']);
181 2
        $this->setAuthorizerRefreshToken($info['authorization_info']['authorizer_refresh_token']);
182
183 2
        $authorizerInfo = $this->getAuthorizerInfo();
184
        // Duplicated info.
185 2
        $authorizerInfo->forget('authorization_info');
186 2
        $info->merge($authorizerInfo->all());
187
188 2
        return $info;
189
    }
190
191
    /**
192
     * Gets the authorization information.
193
     * Like authorizer app id, access token, refresh token, function scope, etc.
194
     *
195
     * @return \EasyWeChat\Support\Collection
196
     */
197 4
    public function getAuthorizationInfo()
198
    {
199 4
        return $this->api->getAuthorizationInfo($this->getAuthCode());
200
    }
201
202
    /**
203
     * Gets the authorizer information.
204
     * Like authorizer name, logo, business, etc.
205
     *
206
     * @return \EasyWeChat\Support\Collection
207
     */
208 4
    public function getAuthorizerInfo()
209
    {
210 4
        return $this->api->getAuthorizerInfo($this->getAuthorizerAppId());
211
    }
212
213
    /**
214
     * Saves the authorizer access token in cache.
215
     *
216
     * @param string $token
217
     *
218
     * @return bool TRUE if the entry was successfully stored in the cache, FALSE otherwise
219
     */
220 4
    public function setAuthorizerAccessToken($token, $expires = 7200)
221
    {
222 4
        return $this->cache->save($this->getAuthorizerAccessTokenKey(), $token, $expires);
223
    }
224
225
    /**
226
     * Gets the authorizer access token.
227
     *
228
     * @return string
229
     */
230 4
    public function getAuthorizerAccessToken()
231
    {
232 4
        return $this->cache->fetch($this->getAuthorizerAccessTokenKey());
233
    }
234
235
    /**
236
     * Saves the authorizer refresh token in cache.
237
     *
238
     * @param string $refreshToken
239
     *
240
     * @return bool TRUE if the entry was successfully stored in the cache, FALSE otherwise
241
     */
242 5
    public function setAuthorizerRefreshToken($refreshToken)
243
    {
244 5
        return $this->cache->save($this->getAuthorizerRefreshTokenKey(), $refreshToken);
245
    }
246
247
    /**
248
     * Gets the authorizer refresh token.
249
     *
250
     * @return string
251
     *
252
     * @throws Exception when refresh token is not present
253
     */
254 4
    public function getAuthorizerRefreshToken()
255
    {
256 4
        if ($token = $this->cache->fetch($this->getAuthorizerRefreshTokenKey())) {
257 4
            return $token;
258
        }
259
260
        throw new Exception(
261
            'Authorizer Refresh Token is not present, you may not make the authorization yet.'
262
        );
263
    }
264
265
    /**
266
     * Removes the authorizer access token from cache.
267
     *
268
     * @return bool TRUE if the cache entry was successfully deleted, FALSE otherwise.
269
     *              Deleting a non-existing entry is considered successful
270
     */
271
    public function removeAuthorizerAccessToken()
272
    {
273
        return $this->cache->delete($this->getAuthorizerAccessTokenKey());
274
    }
275
276
    /**
277
     * Removes the authorizer refresh token from cache.
278
     *
279
     * @return bool TRUE if the cache entry was successfully deleted, FALSE otherwise.
280
     *              Deleting a non-existing entry is considered successful
281
     */
282
    public function removeAuthorizerRefreshToken()
283
    {
284
        return $this->cache->delete($this->getAuthorizerRefreshTokenKey());
285
    }
286
287
    /**
288
     * Gets the authorizer access token cache key.
289
     *
290
     * @return string
291
     */
292 4
    public function getAuthorizerAccessTokenKey()
293
    {
294 4
        return self::CACHE_KEY_ACCESS_TOKEN.$this->appId.$this->getAuthorizerAppId();
295
    }
296
297
    /**
298
     * Gets the authorizer refresh token cache key.
299
     *
300
     * @return string
301
     */
302 5
    public function getAuthorizerRefreshTokenKey()
303
    {
304 5
        return self::CACHE_KEY_REFRESH_TOKEN.$this->appId.$this->getAuthorizerAppId();
305
    }
306
}
307