|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the mingyoung/dingtalk. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) 张铭阳 <[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
|
|
|
namespace EasyDingTalk\Kernel; |
|
13
|
|
|
|
|
14
|
|
|
use EasyDingTalk\Kernel\Exceptions\InvalidCredentialsException; |
|
15
|
|
|
use EasyDingTalk\Kernel\Http\Client; |
|
16
|
|
|
use function EasyDingTalk\tap; |
|
17
|
|
|
use Overtrue\Http\Traits\ResponseCastable; |
|
18
|
|
|
|
|
19
|
|
|
class AccessToken |
|
20
|
|
|
{ |
|
21
|
|
|
use Concerns\InteractsWithCache, ResponseCastable; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var \EasyDingTalk\Application |
|
25
|
|
|
*/ |
|
26
|
|
|
protected $app; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* AccessToken constructor. |
|
30
|
|
|
* |
|
31
|
|
|
* @param \EasyDingTalk\Application |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __construct($app) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->app = $app; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* 获取钉钉 AccessToken |
|
40
|
|
|
* |
|
41
|
|
|
* @return array |
|
42
|
|
|
* |
|
43
|
|
|
* @throws \Psr\SimpleCache\InvalidArgumentException |
|
44
|
|
|
*/ |
|
45
|
|
|
public function get() |
|
46
|
|
|
{ |
|
47
|
|
|
if ($value = $this->getCache()->get($this->cacheFor())) { |
|
48
|
|
|
return $value; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
return $this->refresh(); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* 获取 AccessToken |
|
56
|
|
|
* |
|
57
|
|
|
* @return string |
|
58
|
|
|
* |
|
59
|
|
|
* @throws \Psr\SimpleCache\InvalidArgumentException |
|
60
|
|
|
*/ |
|
61
|
|
|
public function getToken() |
|
62
|
|
|
{ |
|
63
|
|
|
return $this->get()['access_token']; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* 刷新钉钉 AccessToken |
|
68
|
|
|
* |
|
69
|
|
|
* @return array |
|
70
|
|
|
*/ |
|
71
|
|
|
public function refresh() |
|
72
|
|
|
{ |
|
73
|
|
|
$response = (new Client($this->app))->requestRaw('gettoken', 'GET', ['query' => [ |
|
74
|
|
|
'appkey' => $this->app['config']->get('app_key'), |
|
75
|
|
|
'appsecret' => $this->app['config']->get('app_secret'), |
|
76
|
|
|
]]); |
|
77
|
|
|
|
|
78
|
|
|
return tap($this->castResponseToType($response, 'array'), function ($value) { |
|
|
|
|
|
|
79
|
|
|
if (0 !== $value['errcode']) { |
|
80
|
|
|
throw new InvalidCredentialsException(json_encode($value)); |
|
81
|
|
|
} |
|
82
|
|
|
$this->getCache()->set($this->cacheFor(), $value, $value['expires_in']); |
|
83
|
|
|
}); |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
/** |
|
87
|
|
|
* 缓存 Key |
|
88
|
|
|
* |
|
89
|
|
|
* @return string |
|
90
|
|
|
*/ |
|
91
|
|
|
protected function cacheFor() |
|
92
|
|
|
{ |
|
93
|
|
|
return sprintf('access_token.%s', $this->app['config']->get('app_key')); |
|
94
|
|
|
} |
|
95
|
|
|
} |
|
96
|
|
|
|