BaseClient.php
12.7 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
<?php
namespace PgServiceSdk\Kernel;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\ClientInterface;
use PgServiceSdk\Kernel\Http\Response;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\RequestException;
use PgServiceSdk\Kernel\Support\Collection;
use PgServiceSdk\Kernel\Traits\HasHttpRequest;
use PgServiceSdk\Kernel\Library\Apim\ApimSign;
use GuzzleHttp\Psr7\Response as GuzzleResponse;
use PgServiceSdk\Kernel\Exceptions\ValidationException;
use PgServiceSdk\Kernel\Exceptions\BadRequestException;
use PgServiceSdk\Kernel\Exceptions\AuthorizationException;
use PgServiceSdk\Kernel\Exceptions\InvalidConfigException;
use PgServiceSdk\Kernel\Exceptions\ServiceInvalidException;
use PgServiceSdk\Kernel\Exceptions\ResourceNotFoundException;
/**
* Class BaseClient
* @package PgServiceSdk\Kernel
*/
class BaseClient
{
use HasHttpRequest {
request as performRequest;
}
/**
* Pimple 容器
*
* @var ServiceContainer
*/
protected $app;
/**
* option 选项中 baseUri,子类可覆盖
*
* @var string
*/
protected $baseUri;
/**
* 是否处理 JSON 请求的空数组逻辑
*
* @var bool
*/
protected $handleEmptyArray = true;
/**
* BaseClient constructor.
* @param ServiceContainer $app
*/
public function __construct(ServiceContainer $app)
{
$this->app = $app;
}
/**
* 发送 GET 请求
*
* @param string $url
* @param array $query
*
* @return array|object|Collection|\Psr\Http\Message\ResponseInterface|string
*
* @throws AuthorizationException
* @throws InvalidConfigException
* @throws ResourceNotFoundException
* @throws ServiceInvalidException
* @throws ValidationException
*/
public function httpGet($url, array $query = [])
{
return $this->request($url, 'GET', ['query' => $query]);
}
/**
* 发送表单数据(application/x-www-form-urlencoded)
*
* @param string $url
* @param array $data
*
* @return array|object|Collection|\Psr\Http\Message\ResponseInterface|string
*
* @throws AuthorizationException
* @throws InvalidConfigException
* @throws ResourceNotFoundException
* @throws ServiceInvalidException
* @throws ValidationException
*/
public function httpPost($url, array $data = [])
{
return $this->request($url, 'POST', ['form_params' => $data]);
}
/**
* 发送 POST JSON 请求
*
* @param string $url
* @param array $data
* @param array $query
*
* @return array|object|Collection|\Psr\Http\Message\ResponseInterface|string
*
* @throws AuthorizationException
* @throws InvalidConfigException
* @throws ResourceNotFoundException
* @throws ServiceInvalidException
* @throws ValidationException
*/
public function httpPostJson($url, array $data = [], array $query = [])
{
if ($this->handleEmptyArray) {
$data = $this->handleJsonEmptyArray($data);
}
return $this->request($url, 'POST', ['query' => $query, 'json' => $data]);
}
/**
* 发送 PUT JSON 请求
*
* @param string $url
* @param array $data
* @param array $query
*
* @return array|object|Collection|\Psr\Http\Message\ResponseInterface|string
*
* @throws AuthorizationException
* @throws InvalidConfigException
* @throws ResourceNotFoundException
* @throws ServiceInvalidException
* @throws ValidationException
*/
public function httpPutJson($url, array $data = [], array $query = [])
{
if ($this->handleEmptyArray) {
$data = $this->handleJsonEmptyArray($data);
}
return $this->request($url, 'PUT', ['query' => $query, 'json' => $data]);
}
/**
* 发送 PATCH JSON 请求
*
* @param string $url
* @param array $data
* @param array $query
*
* @return array|object|Collection|\Psr\Http\Message\ResponseInterface|string
*
* @throws AuthorizationException
* @throws InvalidConfigException
* @throws ResourceNotFoundException
* @throws ServiceInvalidException
* @throws ValidationException
*/
public function httpPatchJson($url, array $data = [], array $query = [])
{
if ($this->handleEmptyArray) {
$data = $this->handleJsonEmptyArray($data);
}
return $this->request($url, 'PATCH', ['query' => $query, 'json' => $data]);
}
/**
* 发送表单上传附件
*
* @param string $url
* @param array $files
* @param array $form
* @param array $query
*
* @return array|object|Collection|\Psr\Http\Message\ResponseInterface|string
*
* @throws AuthorizationException
* @throws InvalidConfigException
* @throws ResourceNotFoundException
* @throws ServiceInvalidException
* @throws ValidationException
*/
public function httpUpload($url, array $files = [], array $form = [], array $query = [])
{
$multipart = [];
foreach ($files as $name => $file) {
$multipart [] = [
'name' => $name,
'contents' => $file,
];
}
foreach ($form as $name => $contents) {
$multipart[] = compact('name', 'contents');
}
return $this->request($url, 'POST', compact('multipart', 'query'));
}
/**
* 发送请求
*
* @param string $url
* @param string $method
* @param array $options
* @param bool $returnRaw
*
* @return \Psr\Http\Message\ResponseInterface|\PgServiceSdk\Kernel\Support\Collection|array|object|string
*
* @throws AuthorizationException
* @throws InvalidConfigException
* @throws ResourceNotFoundException
* @throws ServiceInvalidException
* @throws ValidationException
*/
public function request($url, $method = 'POST', array $options = [], $returnRaw = false)
{
if (empty($this->middlewares)) {
$this->registerMiddleware();
}
try {
$response = $this->performRequest($url, $method, $options);
} catch (ClientException $e) {
$response = $e->getResponse();
$code = $response->getStatusCode();
$contents = $response->getBody()->getContents();
$content = json_decode($contents);
$message = property_exists($content, 'message') ? $content->message : '';
switch ($code) {
case 404:
throw new ResourceNotFoundException($message, 404);
case 400:
case 422:
throw new ValidationException($message, 400);
break;
case 401:
throw new AuthorizationException($message, 401);
default:
throw new ServiceInvalidException($message ? $message : 'Service Invalid', 500);
}
} catch (ServerException $e) {
$response = $e->getResponse();
$contents = $response->getBody()->getContents();
$content = json_decode($contents);
$message = property_exists($content, 'message') ? $content->message : 'Service Invalid';
throw new ServiceInvalidException($message, 500);
} catch (RequestException $e) {
// 在发送网络错误(连接超时、DNS错误等)时
throw new BadRequestException($e->getMessage(), 400);
}
if ($returnRaw) {
return $response;
}
$responseType = $this->app->config->get('response_type');
$result = $this->costResponseToType($response, $responseType);
return $result;
}
/**
* 自定义请求,响应对象
*
* @param string $url
* @param string $method
* @param array $options
*
* @return \GuzzleHttp\Psr7\Response
*
* @throws AuthorizationException
* @throws InvalidConfigException
* @throws ResourceNotFoundException
* @throws ServiceInvalidException
* @throws ValidationException
*/
public function requestRaw($url, $method = 'POST', array $options = [])
{
return Response::buildFromPsrResponse($this->request($url, $method, $options, true));
}
/**
* 重写获取客户端,通过 Pimple 容器获取
*
* @return \GuzzleHttp\Client
*/
public function getClient()
{
if (!($this->httpClient instanceof ClientInterface)) {
$this->httpClient = $this->app['http_client'] ?: new Client();
}
return $this->httpClient;
}
/**
* 处理空的数据
*
* @param array $data
*
* @return array|object
*/
protected function handleJsonEmptyArray(array $data)
{
count($data) == 0 && $data = (object)$data;
return $data;
}
/**
* 注册中间件
*/
protected function registerMiddleware()
{
$this->pushMiddleware($this->appVerificationMiddleware(), 'appVerification');
$this->pushMiddleware($this->retryMiddleware(), 'retry');
}
/**
* 重试中间件
*
* @return callable
*/
protected function retryMiddleware()
{
return Middleware::retry(function ($retries,
Request $request,
GuzzleResponse $response = null,
RequestException $exception = null) {
if ($retries <= $this->app->config->get('http.retries', 1) && $response) {
return true;
}
return false;
}, function () {
return abs($this->app->config->get('http.retry_delay', 500));
});
}
/**
* appVerificationHandler
*
* @return \Closure
*/
private function appVerificationMiddleware()
{
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
$request = $this->appVerificationHandler($request);
return $handler($request, $options);
};
};
}
/**
* appVerification 中间件具体实现
*
* @param RequestInterface $request
*
* @return RequestInterface
*
* @throws InvalidConfigException
*/
protected function appVerificationHandler(RequestInterface $request)
{
$key = $this->app->config->get('apim.uc.subscription_key', '');
$nonceStr = $this->app->config->get('apim.uc.nonce_str', md5(rand()));
$secret = $this->app->config->get('apim.secret', '');
$apiKey = $this->app->config->get('apim.api_key', '');
$timeStamp = date('Y-m-d H:i:s');
$queryArray = \GuzzleHttp\Psr7\parse_query($request->getUri()->getQuery());
if ($key == '' || $secret == '' || $nonceStr == '' || $apiKey == '') {
throw new InvalidConfigException('Config key "apim.uc.*" and "apim.secret" and "apim.api_key" not be empty ');
}
if (!isset($queryArray['sign'])) {
if ($request->getMethod() == 'GET') {
$sign = ApimSign::getQuerySign($secret, $apiKey, $nonceStr, $timeStamp, $queryArray);
} else {
$body = $request->getBody()->getContents();
if (in_array('application/json', $request->getHeader('Content-Type'))) {
$sign = ApimSign::postBodySign($secret, $apiKey, $nonceStr, $timeStamp, json_decode($body, true), $queryArray);
}
if (in_array('application/x-www-form-urlencoded', $request->getHeader('Content-Type'))) {
parse_str($body, $bodyArray);
$sign = ApimSign::postBodySign($secret, $apiKey, $nonceStr, $timeStamp, $bodyArray, $queryArray);
}
//TODO 其他请求方式应抛出异常
}
$request = $request->withUri(
$request->getUri()->withQuery(
\GuzzleHttp\Psr7\build_query(array_merge($queryArray, [
'api_key' => $apiKey,
'nonce_str' => $nonceStr,
'timestamp' => $timeStamp,
'sign' => $sign
])
)
)
);
}
// 设置请求头
if (!$request->hasHeader('Ocp-Apim-Subscription-Key')) {
$request = $request->withHeader('Ocp-Apim-Subscription-Key', $key);
}
return $request;
}
}