Client.php
2.3 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
<?php
namespace Lackoxygen\Customs;
use GuzzleHttp\Client as GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
use Lackoxygen\Customs\Contract\RequestInterface;
use Lackoxygen\Customs\Exception\Exception;
use Psr\Http\Message\ResponseInterface;
class Client
{
/**
* @var GuzzleHttp
*/
protected $guzzleHttp;
/**
* @var RequestInterface
*/
protected $request;
/**
* Client constructor.
*/
protected function __construct(RequestInterface $request)
{
$clientConfig = (array)config('customs.client');
$this->guzzleHttp = new GuzzleHttp($clientConfig);
$this->request = $request;
}
/**
* @return ResponseInterface
* @throws GuzzleException
*/
protected function send(): ResponseInterface
{
return $this->guzzleHttp->request($this->request->getMethod(), $this->request->getPath(), $this->getOptions());
}
/**
* @return array
*/
protected function getOptions(): array
{
$requestArray = ['payExInfoStr' => $this->request->toJson(JSON_UNESCAPED_UNICODE)];
$options = [];
if ($this->request->getMethod() === "GET") {
$options[RequestOptions::QUERY] = $requestArray;
} elseif ($this->request->getContentType() === 'application/x-www-form-urlencoded') {
$options[RequestOptions::FORM_PARAMS] = $requestArray;
$options[RequestOptions::HEADERS] = ['Content-Type' => 'application/x-www-form-urlencoded'];
} elseif (strpos($this->request->getContentType(), 'application/json') !== false) {
$options[RequestOptions::JSON] = $requestArray;
$options[RequestOptions::HEADERS] = ['Content-Type' => 'application/json'];
}
return $options;
}
/**
* @param RequestInterface $request
*
* @return string
* @throws Exception
*/
public static function request(RequestInterface $request): string
{
$client = new static($request);
try {
$response = $client->send();
} catch (\Throwable $e) {
throw new Exception($e);
}
$content = $response->getBody()->getContents();
$response->getBody()->rewind();
return $content;
}
}