Session.php
1.9 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
<?php
namespace Lackoxygen\TiktokOpen\Wap;
use Lackoxygen\TiktokOpen\Base\Cache;
use Lackoxygen\TiktokOpen\Base\Exception\AnswerException;
use Lackoxygen\TiktokOpen\Base\Exception\Exception;
use Lackoxygen\TiktokOpen\Base\ServiceManager;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
/**
* @property string $accessToken
* @property int $issueTime
* @property int $expiresIn
*/
class Session extends ServiceManager
{
/**
* @var string $name
*/
protected string $name = 'wap.session';
/**
* @throws Exception
*/
private function generateToken()
{
$response = $this->app['wap.oauth']->clientToken();
try {
$this->storeResponse($response);
} catch (AnswerException $e) {
throw new Exception(
sprintf('Token creation exception, %s', $e->getMessage())
);
}
}
/**
* @throws AnswerException
*/
private function storeResponse(array $response): void
{
$data = Arr::get($response, 'data', []);
if (0 !== Arr::get($data, 'error_code')) {
throw new AnswerException(Arr::get($response, 'message'));
}
$expiresIn = (int)Arr::get($data, 'expires_in');
$payload = [
'access_token' => $data['access_token'],
'issue_time' => time(),
'expires_in' => $expiresIn,
];
Cache::put(
$this->name,
$payload,
$expiresIn - 30
);
}
protected function get(string $key)
{
if (!Cache::has($this->name)) {
$this->generateToken();
}
$payload = Cache::get($this->name);
return Arr::get($payload, $key, '');
}
public function __get($name)
{
$key = Str::snake($name);
return $this->get($key);
}
public function forget(): bool
{
return Cache::forget($this->name);
}
}