Completed
Push — master ( 017947...8f5b55 )
by frey
13s
created

AuthorizerAccessToken::refreshToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace EntWeChat\Suite;
4
5
// Don't change the alias name please. I met the issue "name already in use"
6
// when used in Laravel project, not sure what is causing it, this is quick
7
// solution.
8
use EntWeChat\Core\AccessToken as BaseAccessToken;
9
10
/**
11
 * Class AuthorizerAccessToken.
12
 *
13
 * AuthorizerAccessToken is responsible for the access token of the authorizer,
14
 * the complexity is that this access token also requires the refresh token
15
 * of the authorizer which is acquired by the open platform authorization
16
 * process.
17
 *
18
 * This completely overrides the original AccessToken.
19
 */
20
class AuthorizerAccessToken extends BaseAccessToken
21
{
22
    /**
23
     * @var \EntWeChat\Suite\Authorization
24
     */
25
    protected $authorization;
26
27
    /**
28
     * AuthorizerAccessToken constructor.
29
     *
30
     * @param string                         $corpId
31
     * @param \EntWeChat\Suite\Authorization $authorization
32
     */
33
    public function __construct($corpId, Authorization $authorization)
34
    {
35
        parent::__construct($corpId, null);
36
37
        $this->authorization = $authorization;
38
    }
39
40
    /**
41
     * Get token from WeChat API.
42
     *
43
     * @param bool $forceRefresh
44
     *
45
     * @return string
46
     */
47
    public function getToken($forceRefresh = false)
48
    {
49
        $cached = $this->authorization->getAuthorizerAccessToken();
50
51
        if ($forceRefresh || empty($cached)) {
52
            return $this->refreshToken();
53
        }
54
55
        return $cached;
56
    }
57
58
    /**
59
     * Refresh authorizer access token.
60
     *
61
     * @return string
62
     */
63
    protected function refreshToken()
64
    {
65
        $token = $this->authorization->getApi()
66
                                     ->getAuthorizerToken(
67
                                         $this->authorization->getAuthorizerCorpId(),
68
                                         $this->authorization->getAuthorizerPermanentCode()
69
                                     );
70
71
        $this->authorization->setAuthorizerAccessToken($token['access_token'], $token['expires_in'] - 1500);
72
73
        return $token['access_token'];
74
    }
75
76
    /**
77
     * Return the AuthorizerCorpId.
78
     *
79
     * @return string
80
     */
81
    public function getCorpId()
82
    {
83
        return $this->authorization->getAuthorizerCorpId();
84
    }
85
}
86