-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathClient.php
86 lines (71 loc) · 2.38 KB
/
Client.php
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 ChinaDivisions;
use ChinaDivisions\Exceptions\ResponseException;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\RequestInterface;
use Spatie\ArrayToXml\ArrayToXml;
class Client
{
protected $gateway = 'https://shidclink.cainiao.com/gateway/link.do';
/**
* 签名器
*
* @var Signature
*/
protected $signer;
/**
* 请求器
*
* @var ClientInterface
*/
protected $httpClient;
public function __construct(Signature $signer = null, ClientInterface $httpClient = null)
{
$this->httpClient = $httpClient ?? new HttpClient();
$this->signer = $signer ?? new Signature();
}
/**
* 构建请求
*
* @param string $msgType
* @param string $logisticProviderId
* @param string|array $logisticsInterface
* @param string $salt
*
* @return RequestInterface
*/
public function build($msgType, $logisticProviderId, $logisticsInterface, $salt)
{
if (is_array($logisticsInterface)) {
$logisticsInterface = ArrayToXml::convert($logisticsInterface, 'request', true);
}
$dataDigest = $this->signer->make($logisticsInterface, $salt);
$body = http_build_query([
'msg_type' => $msgType,
'logistic_provider_id' => $logisticProviderId,
'logistics_interface' => $logisticsInterface,
'data_digest' => $dataDigest,
]);
return new Request('POST', $this->gateway, ['Content-Type' => 'application/x-www-form-urlencoded'], $body);
}
public function send(RequestInterface $request)
{
$response = $this->httpClient->send($request);
$content = $response->getBody()->getContents();
if ($content == '') {
throw new BadResponseException('Response content is empty.', $request, $response);
}
$result = json_decode($content, true);
if ($result === null) {
throw new BadResponseException('Bad response format.', $request, $response);
}
$success = $result['success'];
if ($success != 'true') {
throw new ResponseException($result['errorMsg'], intval($result['errorCode']));
}
return $result;
}
}