Skip to content

Commit 6fae2a8

Browse files
committed
chore(control): 重构获取百度 access token 方法
1 parent c75fd1c commit 6fae2a8

File tree

2 files changed

+31
-68
lines changed

2 files changed

+31
-68
lines changed

laravel/app/Http/Controllers/Bus/AutoController.php

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -77,19 +77,11 @@ public function qiniuCallback(Request $request)
7777
*/
7878
public function baiduOCR($img, $imgUrl)
7979
{
80-
// 1. 获取 Access Token
81-
$config = [
82-
'url' => 'https://aip.baidubce.com/oauth/2.0/token',
83-
// 'params' => [
84-
// 'grant_type' => 'client_credentials',
85-
// 'client_id' => 'Va5yQRHlA4Fq5eR3LT0vuXV4',
86-
// 'client_secret' => '0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2'
87-
// ]
88-
];
89-
$accessToken = AccessToken::getInstance($config)->getToken();
80+
// 1. 获取 BaiDu Access Token
81+
$accessToken = AccessToken::getInstance()->getBaiDuToken();
9082

9183
if (empty($accessToken)) {
92-
Log::error('######### GET baiduOCR ERROR !!!'); //error_log($e->getMessage());
84+
Log::error('######### GET baiduOCR $accessToken ERROR !!!'); //error_log($e->getMessage());
9385
return '';
9486
}
9587

laravel/app/Http/Repository/AccessToken.php

Lines changed: 28 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,13 @@
1010

1111

1212
use Curl\Http;
13-
use Illuminate\Support\Facades\Storage;
13+
use Illuminate\Support\Facades\Cache;
1414

1515
class AccessToken
1616
{
17+
/**
18+
* @var int 默认缓存 30 天
19+
*/
1720
protected $expiresIn = 2592000;
1821

1922
/**
@@ -28,26 +31,11 @@ class AccessToken
2831
*/
2932
protected $header = [];
3033

31-
/**
32-
* @var string|array 模拟表单提交的数据,发送 JSON 数据必须定义为 String
33-
* 如:{"username":"admin","password":"123456"}
34-
*/
35-
protected $params = 'api=11959004&grant_type=client_credentials&client_id=yxGSiFRIbfdl7WwGGXIGlmnR&client_secret=nE2rXH6ScEUg8MifDPbTzCrD5SHoC4vh';
36-
37-
private $fileName = '';
38-
39-
private $url;
4034
private static $instance;
4135

4236
/**
4337
* TokenUtil constructor.
4438
* @param array $config
45-
*
46-
* $config = [
47-
* 'url' => "https://api.yii2.wang/v1/authorize",
48-
* 'expiresIn' => '86400', // 24H
49-
* 'params' => ['username' => '13776036576', 'password' => '123456'],
50-
* ];
5139
*/
5240
private function __construct($config)
5341
{
@@ -70,22 +58,30 @@ public static function getInstance($config = [])
7058
* @param bool $bool 是否强制刷新缓存 token
7159
* @return bool|string
7260
*/
73-
public function getToken($bool = false)
61+
public function getBaiDuToken($bool = false)
7462
{
75-
try {
76-
$data = Storage::get('token.txt');
77-
} catch (\Exception $e) {
78-
return $this->buildAccessToken();
79-
}
80-
$store = json_decode($data, true);
81-
// 1. 强制获取,文件不存在,文件过期 =》 刷新 Token
82-
if ($bool || empty($store['create_at']) || time() - $store['create_at'] > $this->expiresIn) {
83-
// HTTP 请求获取 token 并写入文件缓存
84-
return $this->buildAccessToken();
85-
}
86-
87-
// 2. 在有效期内,直接读取返回
88-
return $store['access_token'];
63+
$bool && Cache::forget('baidu_access_token');
64+
65+
return Cache::remember('baidu_access_token', $this->expiresIn, function() {
66+
$url = env('BAIDU_token_url') ?? 'https://aip.baidubce.com/oauth/2.0/token';
67+
$curl = new Http();
68+
$params = [
69+
'api' => env('BAIDU_api'),
70+
'grant_type' => env('BAIDU_grant_type'),
71+
'client_id' => env('BAIDU_client_id'),
72+
'client_secret' => env('BAIDU_client_secret'),
73+
];
74+
75+
$httpResult = $curl->request($url, $params, 'post', 5, $this->header);
76+
77+
// 2. 写入缓存
78+
if (!empty($httpResult['content'])) {
79+
$content = json_decode($httpResult['content'], true);
80+
return $content['access_token'] ?? '';
81+
} else {
82+
return '';
83+
}
84+
});
8985
}
9086

9187
/**
@@ -98,37 +94,12 @@ public function setInterval()
9894
$interval = $this->expiresIn;//每隔一定时间运行
9995
do {
10096
try {
101-
$this->buildAccessToken();
97+
$this->getBaiDuToken();
10298
} catch (\Exception $e) {
10399
echo $e->getMessage();
104100
}
105101
sleep($interval); // 等待时间,进行下一次操作。
106102
} while (true);
107103
}
108104

109-
/**
110-
* 获取 access_token 并保存到 token.txt 文件中
111-
* @return string|bool 返回 access_token
112-
*/
113-
private function buildAccessToken()
114-
{
115-
if (empty($this->url)) {
116-
return false;
117-
}
118-
119-
$curl = new Http();
120-
$httpResult = $curl->request($this->url, $this->params, 'post', 6, $this->header);
121-
122-
// 2. 写入文件缓存
123-
if (!empty($httpResult['content'])) {
124-
$content = json_decode($httpResult['content'], true);
125-
$response = array_merge($content, ['create_at' => time()]);
126-
$json = json_encode($response, JSON_UNESCAPED_UNICODE);
127-
128-
// 2018-10-11 使用 Laravel Storage 存储数据
129-
return Storage::disk('local')->put('token.txt', $json) ? $content['access_token'] : false;
130-
} else {
131-
return false;
132-
}
133-
}
134105
}

0 commit comments

Comments
 (0)