-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathTracking.php
266 lines (220 loc) · 10.2 KB
/
Tracking.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
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
<?php
namespace LapayGroup\RussianPost\Providers;
use LapayGroup\RussianPost\Exceptions\StatusValidationException;
use LapayGroup\RussianPost\Exceptions\TrackingException;
use LapayGroup\RussianPost\StatusList;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
class Tracking implements LoggerAwareInterface
{
use LoggerAwareTrait;
private $wsdl = 'https://tracking.pochta.ru';
const NAMESPACE_HISTORY = 'http://russianpost.org/operationhistory';
const NAMESPACE_DATA = 'http://russianpost.org/operationhistory/data';
const NAMESPACE_DATA1 = 'http://www.russianpost.org/RTM/DataExchangeESPP/Data';
private $login = '';
private $password = '';
private $service = '';
private $timeout = 60;
/** @var \SoapClient */
public $client = false;
/**
* Tracking constructor.
*
* @param $service
* @param $config
* @param int $timeout
* @throws \SoapFault
*/
function __construct($service, $config, $timeout = 60)
{
$this->createClient($service);
$this->login = $config['auth']['tracking']['login'];
$this->password = $config['auth']['tracking']['password'];
$this->service = $service;
$this->timeout = $timeout;
}
/**
* @param $service
* @throws \SoapFault
*/
private function createClient($service)
{
$this->service = $service;
if($service != 'pack') {
$wsdl = $this->wsdl . '/tracking-web-static/rtm34_wsdl.xml';
$soapVersion = SOAP_1_2;
} else {
$wsdl = $this->wsdl . '/tracking-web-static/fc_wsdl.xml';
$soapVersion = SOAP_1_1;
}
$this->client = new \SoapClient($wsdl, array(
'trace' => 1,
'soap_version' => $soapVersion,
'use' => SOAP_LITERAL,
'style' => SOAP_DOCUMENT,
'connection_timeout'=>$this->timeout
)
);
}
/**
* Получение подробной информации обо всех операциях, совершенных над отправлением
* @param $rpo - ШК отправления
* @param string $lang - Язык названия операций (RUS, ENG)
* @return \stdClass[]
* @throws \SoapFault
*/
public function getOperationsByRpo($rpo, $lang = 'RUS')
{
// Если пакетный клиент, меняем на штучный
if ($this->service == 'pack') {
$this->createClient('single');
}
$requestParams = new \SoapVar([
new \SoapVar([
new \SoapVar($rpo, XSD_STRING, null, null, 'Barcode', self::NAMESPACE_DATA),
new \SoapVar(0, XSD_INT, null, null, 'MessageType', self::NAMESPACE_DATA),
new \SoapVar($lang, XSD_STRING, null, null, 'Language', self::NAMESPACE_DATA),
], SOAP_ENC_OBJECT, null, null, 'OperationHistoryRequest', self::NAMESPACE_DATA),
new \SoapVar([
new \SoapVar($this->login, XSD_STRING, null, null, 'login', self::NAMESPACE_DATA),
new \SoapVar($this->password, XSD_STRING, null, null, 'password', self::NAMESPACE_DATA),
], SOAP_ENC_OBJECT, null, null, 'AuthorizationHeader', self::NAMESPACE_DATA),
], SOAP_ENC_OBJECT);
$response = $this->client->getOperationHistory($requestParams);
if ($this->logger) {
$this->logger->info("Russian Post Tracking API request: \n\r".$this->client->__getLastRequest());
$this->logger->info("Russian Post Tracking API response: \n\r".$this->client->__getLastResponse());
}
$result = $response->OperationHistoryData;
if (!isset($result->historyRecord)) return [];
if (!is_array($result->historyRecord))
$result->historyRecord = [$result->historyRecord];
return !empty($result->historyRecord) ? $result->historyRecord : [];
}
/**
* Получение информации об операциях с наложенным платежом, который связан с почтовым отправлением.
* @param $rpo - ШК отправления
* @param string $lang - Язык названия операций (RUS, ENG)
* @return \stdClass
* @throws \SoapFault
*/
public function getNpayInfo($rpo, $lang = 'RUS')
{
// Если пакетный клиент, меняем на штучный
if ($this->service == 'pack') {
$this->createClient('single');
}
$requestParams = new \SoapVar([
new \SoapVar([
new \SoapVar($this->login, XSD_STRING, null, null, 'login', self::NAMESPACE_DATA),
new \SoapVar($this->password, XSD_STRING, null, null, 'password', self::NAMESPACE_DATA),
], SOAP_ENC_OBJECT, null, null, 'AuthorizationHeader', self::NAMESPACE_DATA),
new \SoapVar(
'<ns2:PostalOrderEventsForMailInput Barcode="'.$rpo.'" Language="'.$lang.'" />'
, XSD_ANYXML, null, null, 'PostalOrderEventsForMailInput', self::NAMESPACE_DATA1),
], SOAP_ENC_OBJECT);
$response = $this->client->PostalOrderEventsForMail($requestParams);
if ($this->logger) {
$this->logger->info("Russian Post Tracking API request: \n\r".$this->client->__getLastRequest());
$this->logger->info("Russian Post Tracking API response: \n\r".$this->client->__getLastResponse());
}
$result = $response->PostalOrderEventsForMaiOutput;
if (!empty($result->PostalOrderEvent) && !is_array($result->PostalOrderEvent))
$result->PostalOrderEvent = [$result->PostalOrderEvent];
return !empty($result->PostalOrderEvent) ? $result->PostalOrderEvent : [];
}
/**
* Создание запроса на получение информации о операциях с переданными отправлениями
* @param $rpoList - массиш ШК отправлений
* @param string $lang - Язык названия операций (RUS, ENG)
* @return array
* @throws \SoapFault
*/
public function getTickets($rpoList, $lang = 'RUS')
{
// Если штучный клиент, меняем на пакетный
if ($this->service == 'single') {
$this->createClient('pack');
}
// Бьем по 500, если больше, то ловис HTTP Exception так как слишком большой размер ответа от ПРФ
$rpoPack = array_chunk($rpoList, 500);
$requestParams = new \stdClass();
$requestParams->login = $this->login;
$requestParams->password = $this->password;
$requestParams->language = $lang;
$requestParams->request = new \stdClass();
$result['tickets'] = $result['not_create'] = [];
foreach ($rpoPack as $rpoList) {
$requestParams->Item = [];
foreach ($rpoList as $rpo) {
$item = new \stdClass();
$item->Barcode = $rpo;
$requestParams->request->Item[] = $item;
}
$response = $this->client->getTicket($requestParams);
if ($this->logger) {
$this->logger->info("Russian Post Tracking API request: \n\r".$this->client->__getLastRequest());
$this->logger->info("Russian Post Tracking API response: \n\r".$this->client->__getLastResponse());
}
if (!empty($response) && !empty($response->value)) {
$result['tickets'][] = $response->value;
} else {
$result['not_create'] = array_merge($result['not_create'], $rpoList);
}
}
return $result;
}
/**
* Получение подробной информации обо всех операциях, совершенных над переданными отправлениями в тикете
* @param $ticket
* @return array|\stdClass
* @throws TrackingException
* @throws \SoapFault
*/
public function getOperationsByTicket($ticket)
{
// Если штучный клиент, меняем на пакетный
if ($this->service == 'single') {
$this->createClient('pack');
}
$statusList = new StatusList();
$requestParams = new \stdClass();
$requestParams->login = $this->login;
$requestParams->password = $this->password;
$requestParams->ticket = $ticket;
$response = $this->client->getResponseByTicket($requestParams);
if ($this->logger) {
$this->logger->info("Russian Post Tracking API request: \n\r".$this->client->__getLastRequest());
$this->logger->info("Russian Post Tracking API response: \n\r".$this->client->__getLastResponse());
}
if (!empty($response->error) || empty($response->value))
throw new TrackingException('Ответ по тикету '.$ticket.' еще не готов.');
/** @var \stdClass $result */
$result = !is_array($response->value->Item) ? [$response->value->Item] : $response->value->Item;
// Проставляем название подстатуса из справочника
foreach ($result as $key => &$item) {
if (empty($item->Operation)) continue;
$rpo = (string)$item->Barcode;
if (!is_array($item->Operation)) {
$item = [$item->Operation];
} else {
$item = $item->Operation;
}
foreach ($item as &$operation) {
try {
$statusInfo = $statusList->getInfo($operation->OperTypeID, $operation->OperCtgID);
$operation->OperCtgName = $statusInfo['substatusName'];
$operation->isFinal = $statusInfo['isFinal'];
}
catch (StatusValidationException $e) {
$operation->OperCtgName = $e->getMessage();
$operation->isFinal = false;
}
}
$result[$rpo] = $item;
unset($result[$key]);
}
return $result;
}
}