Hris.php
7.75 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
<?php
/**
* Hris.php
* HRIS 系统接口服务
* @author Deepseath
* @version $Id$
*/
namespace deepseath\hris;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
class Hris
{
/**
* 缓存池
* @var \Symfony\Component\Cache\Adapter\FilesystemAdapter
*/
protected $_cache = null;
/**
* HRIS 系统原始 token
* @var string
*/
protected $_originToken = '';
/**
* token 过期时间,单位:秒
* @var int
*/
protected $_tokenExpire = 7200;
/**
* HRIS 接口服务根 URL
* @var string
*/
protected $_baseUrl = '';
/**
* 库版本号
* @var string
*/
protected $_libVersion = '1.0';
/**
* HTTP 请求对象
* @var \Yurun\Util\HttpRequest
*/
protected $_http = null;
/**
* 调试模式
* @var boolean
*/
protected $_debug = false;
/**
* 配置信息
* @var array
*/
public $config = [];
/**
* 单点实例
* @param array $options
* @return \deepseath\hris\Hris
*/
public static function &instance(array $options)
{
static $instance = null;
if (empty($instance)) {
$instance = new self($options);
}
return $instance;
}
private function __construct(array $options = [])
{
$this->_cache = new FilesystemAdapter('hris', 86400, null);
if (function_exists('config')) {
$config = config('hris');
if (empty($options)) {
$options = $config;
} else {
$options = array_merge($config, $options);
}
unset($config);
}
$this->config = $options;
if (empty($options['originToken'])) {
throw new \Exception('原始 TOKEN 未定义', 9001);
}
if (!empty($options['baseUrl'])) {
$this->_baseUrl = $options['baseUrl'];
}
if (isset($options['debug'])) {
$this->_debug = $options['debug'];
}
if (!isset($this->config['mapping_expire'])) {
$this->config['mapping_expire'] = 86400 * 7;
}
$this->_originToken= $options['originToken'];
$this->_http = \Yurun\Util\HttpRequest::newSession();
}
/**
* 缓存对象
* @return \Symfony\Component\Cache\Adapter\FilesystemAdapter
*/
public function cache()
{
return $this->_cache;
}
/**
* 获取 token 信息
* @param $force bool 是否强制获取更新 token
* @return array
* <pre>
* + access_token String Y 令牌
* + token_type String Y 令牌类型
* + expires_in String Y token有效时间,时间单位秒
* + scope String Y 授权作用域
* </pre>
*/
public function getTokenInfo(bool $force = false) : array
{
$token = $this->_cache->getItem('token');
if ($token->isHit() && $force === false) {
return $token->get();
}
// 初始化 token 信息
$newTokenInfo = [];
// 构造 token 获取接口地址
$url = $this->_baseUrl . 'tokenFlush';
$params = [
'token' => $this->_originToken
];
// 请求接口
$headers = [
'Authorization' => $this->_originToken,
'Content-Type' => 'application/json;charset=utf-8'
];
$this->_http->headers($headers);
$this->log($url, 'Get Token');
$this->log($params, 'Request');
$this->log($headers, 'Header');
$response = $this->_http->post($url, $params, 'json');
$newTokenInfo = $response->json(true);
$this->log($newTokenInfo, 'Result');
if (empty($newTokenInfo) || !isset($newTokenInfo['code'])) {
throw new \Exception('request hris token error' . var_export($newTokenInfo, true) . '|' . $url . var_export($params, true), 9001);
}
if ($newTokenInfo['code'] != 200) {
throw new \Exception('HRIS TOKEN GET ERROR:' . $newTokenInfo['msg'] . ':' . $newTokenInfo['code']);
}
$newTokenInfo['_datetime'] = date('Y-m-d H:i:s');
// 将本次获取的 token 值写入到缓存
$token->set($newTokenInfo);
if (isset($newTokenInfo['expires_in'])) {
$expire = $newTokenInfo['expires_in'];
} else {
$expire = $this->_tokenExpire;
}
$token->expiresAfter($expire - 10);
$this->log($token->get(), 'Save Token');
$this->_cache->save($token);
return $newTokenInfo;
}
/**
* 接口 API POST
* @param string $path 接口基于版本目录的路径
* @param array $data 请求的数据
* @param bool $flushToken 是否强制刷新 token
* @throws \Exception
* @return array
*/
public function apiRequest($method, $path, $data, $flushToken = false)
{
static $tryCount;
if ($tryCount === null || $flushToken === false) {
$tryCount = 1;
} else {
$tryCount++;
}
if ($tryCount > 3) {
throw new \Exception('hris SDK Error: Get token error, retry maximum number.');
}
$headers = [
'Content-Type' => 'application/json;charset=utf-8',
'Authorization' => $this->getTokenInfo($flushToken)['data']['token']
];
$this->_http->headers($headers);
$url = $this->_baseUrl . $path;
$method = strtolower($method);
$this->log($url, 'Url');
$this->log($method, 'Method');
$this->log($headers, 'Header');
$this->log($data, 'Request');
if ($method == 'post') {
$dataString = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$response = $this->_http->post($url, $dataString, 'json');
} elseif ($method == 'get') {
$response = $this->_http->get($url, $data);
}
$body = $response->body();
$this->log($response->getStatusCode(), 'StatusCode');
$this->log($body, 'Body');
$result = $response->json(true);
$this->log($result, 'Result');
if (!isset($result['code']) || $result['code'] != 200) {
if (isset($result['code']) && ($result['code'] == '3001')) {
// token 无效,尝试重新刷新 token
$this->log($tryCount, 'Try count');
return $this->apiRequest($method, $path, $data, true);
}
if (isset($result['msg']) && isset($result['code'])) {
throw new \Exception(json_encode([
'url' => $url,
'title' => 'hris SDK request error',
'msg' => $result['msg'],
'code' => $result['code'],
'request' => $data,
'result' => $result,
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $result['code']);
} else {
throw new \Exception(json_encode([
'url' => $url,
'title' => 'hris SDK response error',
'msg' => $result,
'result' => $result,
'response' => $body,
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 90001);
}
}
return isset($result['data']) ? $result['data'] : ($result['msg'] ?? []);
}
/**
* 打印调试日志
* @param mixed $info
*/
public function log($info, $title = '', $level = 'hris')
{
if ($this->_debug) {
$info = is_scalar($info) ? $info : json_encode($info, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$title = $title ? "[{$title}]" : '';
\think\facade\Log::write($title . $info, 'hris');
}
}
}