AuthorizerAccessToken.php
2.6 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
<?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <i@overtrue.me>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* AuthorizerAccessToken.php.
*
* Part of Overtrue\WeChat.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author lixiao <leonlx126@gmail.com>
* @copyright 2016
*
* @see https://github.com/overtrue
* @see http://overtrue.me
*/
namespace EasyWeChat\OpenPlatform;
// Don't change the alias name please. I met the issue "name already in use"
// when used in Laravel project, not sure what is causing it, this is quick
// solution.
use EasyWeChat\Core\AccessToken as BaseAccessToken;
/**
* Class AuthorizerAccessToken.
*
* AuthorizerAccessToken is responsible for the access token of the authorizer,
* the complexity is that this access token also requires the refresh token
* of the authorizer which is acquired by the open platform authorizer process.
*
* This completely overrides the original AccessToken.
*/
class AuthorizerAccessToken extends BaseAccessToken
{
/**
* @var \EasyWeChat\OpenPlatform\Authorizer
*/
protected $authorizer;
/**
* AuthorizerAccessToken constructor.
*
* @param string $appId
* @param \EasyWeChat\OpenPlatform\Authorizer $authorizer
*/
public function __construct($appId, Authorizer $authorizer)
{
parent::__construct($appId, null);
$this->authorizer = $authorizer;
}
/**
* Get token from WeChat API.
*
* @param bool $forceRefresh
*
* @return string
*/
public function getToken($forceRefresh = false)
{
$cached = $this->authorizer->getAccessToken();
if ($forceRefresh || empty($cached)) {
return $this->renewAccessToken();
}
return $cached;
}
/**
* Refresh authorizer access token.
*
* @return string
*/
protected function renewAccessToken()
{
$token = $this->authorizer->getApi()
->getAuthorizerToken(
$this->authorizer->getAppId(),
$this->authorizer->getRefreshToken()
);
$this->authorizer->setAccessToken($token['authorizer_access_token'], $token['expires_in'] - 1500);
return $token['authorizer_access_token'];
}
/**
* Return the AuthorizerAppId.
*
* @return string
*/
public function getAppId()
{
return $this->authorizer->getAppId();
}
}