forked from tijsverkoyen/bpost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbpost.php
2773 lines (2428 loc) · 62.2 KB
/
bpost.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
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* bPost class
*
* This source file can be used to communicate with the bPost Shipping Manager API
*
* The class is documented in the file itself. If you find any bugs help me out and report them. Reporting can be done by sending an email to php-bpost-bugs[at]verkoyen[dot]eu.
* If you report a bug, make sure you give me enough information (include your code).
*
* Changelog since 1.0.0
* - added a class to handle the form.
*
* License
* Copyright (c), Tijs Verkoyen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
*
* This software is provided by the author "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the author be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
*
* @author Tijs Verkoyen <[email protected]>
* @version 1.0.1
* @copyright Copyright (c), Tijs Verkoyen. All rights reserved.
* @license BSD License
*/
class bPost
{
// internal constant to enable/disable debugging
const DEBUG = false;
// URL for the api
const API_URL = 'https://api.bpost.be/services/shm';
// current version
const VERSION = '1.0.1';
/**
* The account id
*
* @var string
*/
private $accountId;
/**
* A cURL instance
*
* @var resource
*/
private $curl;
/**
* The passPhrase
*
* @var string
*/
private $passPhrase;
/**
* The port to use.
*
* @var int
*/
private $port;
/**
* The timeout
*
* @var int
*/
private $timeOut = 10;
/**
* The user agent
*
* @var string
*/
private $userAgent;
// class methods
/**
* Create bPost instance
*
* @param string $accountId
* @param string $passPhrase
*/
public function __construct($accountId, $passPhrase)
{
$this->accountId = (string) $accountId;
$this->passPhrase = (string) $passPhrase;
}
/**
* Destructor
*/
public function __destruct()
{
// is the connection open?
if($this->curl !== null)
{
// close connection
curl_close($this->curl);
// reset
$this->curl = null;
}
}
/**
* Callback-method for elements in the return-array
*
* @param mixed $input The value.
* @param string $key string The key.
* @param DOMDocument $xml Some data.
*/
private static function arrayToXML(&$input, $key, $xml)
{
// wierd stuff
if(in_array($key, array('orderLine', 'internationalLabelInfo')))
{
foreach($input as $row)
{
$element = new DOMElement($key);
$xml->appendChild($element);
// loop properties
foreach($row as $name => $value)
{
if(is_bool($value)) $value = ($value) ? 'true' : 'false';
$node = new DOMElement($name, $value);
$element->appendChild($node);
}
}
return;
}
// skip attributes
if($key == '@attributes') return;
// create element
$element = new DOMElement($key);
// append
$xml->appendChild($element);
// no value? just stop here
if($input === null) return;
// is it an array and are there attributes
if(is_array($input) && isset($input['@attributes']))
{
// loop attributes
foreach((array) $input['@attributes'] as $name => $value) $element->setAttribute($name, $value);
// reset value
if(count($input) == 2 && isset($input['value'])) $input = $input['value'];
// reset the input if it is a single value
elseif(count($input) == 1) return;
}
// the input isn't an array
if(!is_array($input))
{
// boolean
if(is_bool($input)) $element->appendChild(new DOMText(($input) ? 'true' : 'false'));
// is_numeric
elseif(is_numeric($input)) $element->appendChild(new DOMText($input));
// a string?
elseif(is_string($input))
{
// characters that require a cdata wrapper
$illegalCharacters = array('&', '<', '>', '"', '\'');
// default we dont wrap with cdata tags
$wrapCdata = false;
// find illegal characters in input string
foreach($illegalCharacters as $character)
{
if(stripos($input, $character) !== false)
{
// wrap input with cdata
$wrapCdata = true;
// no need to search further
break;
}
}
// check if value contains illegal chars, if so wrap in CDATA
if($wrapCdata) $element->appendChild(new DOMCdataSection($input));
// just regular element
else $element->appendChild(new DOMText($input));
}
// fallback
else
{
if(self::DEBUG)
{
echo 'Unknown type';
var_dump($input);
exit();
}
$element->appendChild(new DOMText($input));
}
}
// the value is an array
else
{
// init var
$isNonNumeric = false;
// loop all elements
foreach($input as $index => $value)
{
// non numeric string as key?
if(!is_numeric($index))
{
// reset var
$isNonNumeric = true;
// stop searching
break;
}
}
// is there are named keys they should be handles as elements
if($isNonNumeric) array_walk($input, array('bPost', 'arrayToXML'), $element);
// numeric elements means this a list of items
else
{
// handle the value as an element
foreach($input as $value)
{
if(is_array($value)) array_walk($value, array('bPost', 'arrayToXML'), $element);
}
}
}
}
/**
* Decode the response
*
* @param SimpleXMLElement $item The item to decode.
* @param array[optional] $return Just a placeholder.
* @param int[optional] $i A internal counter.
* @return mixed
*/
private static function decodeResponse($item, $return = null, $i = 0)
{
$arrayKeys = array('barcode', 'orderLine', 'additionalInsurance', 'infoDistributed', 'infoPugo');
$integerKeys = array('totalPrice');
if($item instanceof SimpleXMLElement)
{
foreach($item as $key => $value)
{
$attributes = (array) $value->attributes();
if(!empty($attributes) && isset($attributes['@attributes']))
{
$return[$key]['@attributes'] = $attributes['@attributes'];
}
// empty
if(isset($value['nil']) && (string) $value['nil'] === 'true') $return[$key] = null;
// empty
elseif(isset($value[0]) && (string) $value == '')
{
if(in_array($key, $arrayKeys))
{
$return[$key][] = self::decodeResponse($value);
}
else $return[$key] = self::decodeResponse($value, null, 1);
}
else
{
// arrays
if(in_array($key, $arrayKeys))
{
$return[$key][] = (string) $value;
}
// booleans
elseif((string) $value == 'true') $return[$key] = true;
elseif((string) $value == 'false') $return[$key] = false;
// integers
elseif(in_array($key, $integerKeys)) $return[$key] = (int) $value;
// fallback to string
else $return[$key] = (string) $value;
}
}
}
else throw new bPostException('Invalid item.');
return $return;
}
/**
* Make the call
*
* @param string $url The URL to call.
* @param array[optional] $data The data to pass.
* @param array[optional] $headers The headers to pass.
* @param string[optional] $method The HTTP-method to use.
* @param bool[optional] $expectXML Do we expect XML?
* @return mixed
*/
private function doCall($url, $data = null, $headers = array(), $method = 'GET', $expectXML = true)
{
// any data?
if($data !== null)
{
// init XML
$xml = new DOMDocument('1.0', 'utf-8');
// set some properties
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
// build data
array_walk($data, array(__CLASS__, 'arrayToXML'), $xml);
// store body
$body = $xml->saveXML();
}
else $body = null;
// build Authorization header
$headers[] = 'Authorization: Basic ' . $this->getAuthorizationHeader();
// set options
$options[CURLOPT_URL] = self::API_URL . '/' . $this->accountId . $url;
if($this->getPort() != 0) $options[CURLOPT_PORT] = $this->getPort();
$options[CURLOPT_USERAGENT] = $this->getUserAgent();
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = (int) $this->getTimeOut();
$options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
$options[CURLOPT_HTTPHEADER] = $headers;
// PUT
if($method == 'PUT')
{
$options[CURLOPT_CUSTOMREQUEST] = 'PUT';
if($body != null) $options[CURLOPT_POSTFIELDS] = $body;
}
if($method == 'POST')
{
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $body;
}
// init
$this->curl = curl_init();
// set options
curl_setopt_array($this->curl, $options);
// execute
$response = curl_exec($this->curl);
$headers = curl_getinfo($this->curl);
// fetch errors
$errorNumber = curl_errno($this->curl);
$errorMessage = curl_error($this->curl);
// error?
if($errorNumber != '')
{
// internal debugging enabled
if(self::DEBUG)
{
echo '<pre>';
var_dump(htmlentities($response));
var_dump($this);
echo '</pre>';
}
throw new bPostException($errorMessage, $errorNumber);
}
// valid HTTP-code
if(!in_array($headers['http_code'], array(0, 200)))
{
// internal debugging enabled
if(self::DEBUG)
{
echo '<pre>';
var_dump(htmlentities($body));
var_dump($response);
var_dump($headers);
var_dump($this);
echo '</pre>';
}
throw new bPostException('Invalid response.', $headers['http_code']);
}
// if we don't expect XML we can return the content here
if(!$expectXML) return $response;
// convert into XML
$xml = simplexml_load_string($response);
// validate
if($xml->getName() == 'businessException')
{
// internal debugging enabled
if(self::DEBUG)
{
echo '<pre>';
var_dump($response);
var_dump($headers);
var_dump($this);
echo '</pre>';
}
// message
$message = (string) $response->Message;
$code = (string) $response->Code;
// throw exception
throw new bPostException($message, $code);
}
// return the response
return $xml;
}
/**
* Get the account id
*
* @return string
*/
public function getAccountId()
{
return $this->accountId;
}
/**
* Generate the secret string for the Authorization header
*
* @return string
*/
private function getAuthorizationHeader()
{
return base64_encode($this->accountId . ':' . $this->passPhrase);
}
/**
* Get the passPhrase
*
* @return string
*/
public function getPassPhrase()
{
return $this->passPhrase;
}
/**
* Get the port
*
* @return int
*/
public function getPort()
{
return (int) $this->port;
}
/**
* Get the timeout that will be used
*
* @return int
*/
public function getTimeOut()
{
return (int) $this->timeOut;
}
/**
* Get the useragent that will be used.
* Our version will be prepended to yours.
* It will look like: "PHP bPost/<version> <your-user-agent>"
*
* @return string
*/
public function getUserAgent()
{
return (string) 'PHP bPost/' . self::VERSION . ' ' . $this->userAgent;
}
/**
* Set the timeout
* After this time the request will stop. You should handle any errors triggered by this.
*
* @param int $seconds The timeout in seconds.
*/
public function setTimeOut($seconds)
{
$this->timeOut = (int) $seconds;
}
/**
* Set the user-agent for you application
* It will be appended to ours, the result will look like: "PHP bPost/<version> <your-user-agent>"
*
* @param string $userAgent Your user-agent, it should look like <app-name>/<app-version>.
*/
public function setUserAgent($userAgent)
{
$this->userAgent = (string) $userAgent;
}
// webservice methods
// orders
/**
* Creates a new order. If an order with the same orderReference already exists
*
* @param bPostOrder $order
* @return bool
*/
public function createOrReplaceOrder(bPostOrder $order)
{
// build url
$url = '/orders';
// build data
$data['order']['@attributes']['xmlns'] = 'http://schema.post.be/shm/deepintegration/v2/';
$data['order']['value'] = $order->toXMLArray($this->accountId);
// build headers
$headers = array(
'Content-type: application/vnd.bpost.shm-order-v2+XML'
);
// make the call
return ($this->doCall($url, $data, $headers, 'POST', false) == '');
}
/**
* Fetch an order
*
* @param string $reference
* @return array
*/
public function fetchOrder($reference)
{
// build url
$url = '/orders/' . (string) $reference;
// make the call
$return = self::decodeResponse($this->doCall($url));
// for some reason the order-data is wrapped in an order tag sometimes.
if(isset($return['order']))
{
if(isset($return['barcode'])) $barcodes = $return['barcode'];
$return = $return['order'];
}
$order = new bPostOrder($return['orderReference']);
if(isset($barcodes)) $order->setBarcodes($barcodes);
if(isset($return['status'])) $order->setStatus($return['status']);
if(isset($return['costCenter'])) $order->setCostCenter($return['costCenter']);
// order lines
if(isset($return['orderLine']) && !empty($return['orderLine']))
{
foreach($return['orderLine'] as $row)
{
$order->addOrderLine($row['text'], $row['nbOfItems']);
}
}
// customer
if(isset($return['customer']))
{
// create customer
$customer = new bPostCustomer($return['customer']['firstName'], $return['customer']['lastName']);
if(isset($return['customer']['deliveryAddress']))
{
$address = new bPostAddress(
$return['customer']['deliveryAddress']['streetName'],
$return['customer']['deliveryAddress']['number'],
$return['customer']['deliveryAddress']['postalCode'],
$return['customer']['deliveryAddress']['locality'],
$return['customer']['deliveryAddress']['countryCode']
);
if(isset($return['customer']['deliveryAddress']['box']))
{
$address->setBox($return['customer']['deliveryAddress']['box']);
}
$customer->setDeliveryAddress($address);
}
if(isset($return['customer']['email'])) $customer->setEmail($return['customer']['email']);
if(isset($return['customer']['phoneNumber'])) $customer->setPhoneNumber($return['customer']['phoneNumber']);
$order->setCustomer($customer);
}
// delivery method
if(isset($return['deliveryMethod']))
{
// atHome?
if(isset($return['deliveryMethod']['atHome']))
{
$deliveryMethod = new bPostDeliveryMethodAtHome();
// options
if(isset($return['deliveryMethod']['atHome']['normal']['options']) && !empty($return['deliveryMethod']['atHome']['normal']['options']))
{
$options = array();
foreach($return['deliveryMethod']['atHome']['normal']['options'] as $key => $row)
{
$language = 'NL'; // @todo fix me
$emailAddress = null;
$mobilePhone = null;
$fixedPhone = null;
if(isset($row['emailAddress'])) $emailAddress = $row['emailAddress'];
if(isset($row['mobilePhone'])) $mobilePhone = $row['mobilePhone'];
if(isset($row['fixedPhone'])) $fixedPhone = $row['fixedPhone'];
if($emailAddress === null && $mobilePhone === null && $fixedPhone === null) continue;
$options[$key] = new bPostNotification($language, $emailAddress, $mobilePhone, $fixedPhone);
}
$deliveryMethod->setNormal($options);
}
$order->setDeliveryMethod($deliveryMethod);
}
// atShop
elseif(isset($return['deliveryMethod']['atShop']))
{
$deliveryMethod = new bPostDeliveryMethodAtShop();
$language = $return['deliveryMethod']['atShop']['infoPugo']['@attributes']['language'];
$emailAddress = null;
$mobilePhone = null;
$fixedPhone = null;
if(isset($return['deliveryMethod']['atShop']['infoPugo'][0]['emailAddress']))
{
$emailAddress = $return['deliveryMethod']['atShop']['infoPugo'][0]['emailAddress'];
}
if(isset($return['deliveryMethod']['atShop']['infoPugo'][0]['mobilePhone']))
{
$mobilePhone = $return['deliveryMethod']['atShop']['infoPugo'][0]['mobilePhone'];
}
if(isset($return['deliveryMethod']['atShop']['infoPugo'][0]['fixedPhone']))
{
$fixedPhone = $return['deliveryMethod']['atShop']['infoPugo'][0]['fixedPhone'];
}
$deliveryMethod->setInfoPugo(
$return['deliveryMethod']['atShop']['infoPugo'][0]['pugoId'],
$return['deliveryMethod']['atShop']['infoPugo'][0]['pugoName'],
new bPostNotification($language, $emailAddress, $mobilePhone, $fixedPhone)
);
if(isset($return['deliveryMethod']['atShop']['insurance']['additionalInsurance']['@attributes']['value']))
{
$deliveryMethod->setInsurance((int) $return['deliveryMethod']['atShop']['insurance']['additionalInsurance']['@attributes']['value']);
}
$language = $return['deliveryMethod']['atShop']['infoPugo']['@attributes']['language'];
$emailAddress = null;
$mobilePhone = null;
$fixedPhone = null;
$pugoId = null;
$pugoName = null;
if(isset($return['deliveryMethod']['atShop']['infoPugo'][0]['emailAddress']))
{
$emailAddress = $return['deliveryMethod']['atShop']['infoPugo'][0]['emailAddress'];
}
if(isset($return['deliveryMethod']['atShop']['infoPugo'][0]['mobilePhone']))
{
$mobilePhone = $return['deliveryMethod']['atShop']['infoPugo'][0]['mobilePhone'];
}
if(isset($return['deliveryMethod']['atShop']['infoPugo'][0]['fixedPhone']))
{
$fixedPhone = $return['deliveryMethod']['atShop']['infoPugo'][0]['fixedPhone'];
}
if(isset($return['deliveryMethod']['atShop']['infoPugo'][0]['pugoId']))
{
$pugoId = $return['deliveryMethod']['atShop']['infoPugo'][0]['pugoId'];
}
if(isset($return['deliveryMethod']['atShop']['infoPugo'][0]['pugoName']))
{
$pugoName = $return['deliveryMethod']['atShop']['infoPugo'][0]['pugoName'];
}
$deliveryMethod->setInfoPugo(
$pugoId, $pugoName,
new bPostNotification($language, $emailAddress, $mobilePhone, $fixedPhone)
);
$order->setDeliveryMethod($deliveryMethod);
}
// at24-7
elseif(isset($return['deliveryMethod']['at24-7']))
{
$deliveryMethod = new bPostDeliveryMethodAt247(
$return['deliveryMethod']['at24-7']['infoParcelsDepot']['parcelsDepotId']
);
if(isset($return['deliveryMethod']['at24-7']['memberId']))
{
$deliveryMethod->setMemberId($return['deliveryMethod']['at24-7']['memberId']);
}
if(isset($return['deliveryMethod']['at24-7']['signature']['signature']))
{
$deliveryMethod->setSignature();
}
if(isset($return['deliveryMethod']['at24-7']['signature']['signature']))
{
$deliveryMethod->setSignature(true);
}
if(isset($return['deliveryMethod']['at24-7']['insurance']['additionalInsurance']['@attributes']['value']))
{
$deliveryMethod->setInsurance((int) $return['deliveryMethod']['at24-7']['insurance']['additionalInsurance']['@attributes']['value']);
}
$order->setDeliveryMethod($deliveryMethod);
}
// intExpress?
elseif(isset($return['deliveryMethod']['intExpress']))
{
$deliveryMethod = new bPostDeliveryMethodIntBusiness();
if(isset($return['deliveryMethod']['intExpress']['insured']['additionalInsurance']['@attributes']['value']))
{
$deliveryMethod->setInsurance((int) $return['deliveryMethod']['intExpress']['insured']['additionalInsurance']['@attributes']['value']);
}
// options
if(isset($return['deliveryMethod']['intBusiness']['insured']['options']) && !empty($return['deliveryMethod']['intExpress']['insured']['options']))
{
$options = array();
foreach($return['deliveryMethod']['intExpress']['insured']['options'] as $key => $row)
{
$language = 'NL'; // @todo fix me
$emailAddress = null;
$mobilePhone = null;
$fixedPhone = null;
if(isset($row['emailAddress'])) $emailAddress = $row['emailAddress'];
if(isset($row['mobilePhone'])) $mobilePhone = $row['mobilePhone'];
if(isset($row['fixedPhone'])) $fixedPhone = $row['fixedPhone'];
if($emailAddress === null && $mobilePhone === null && $fixedPhone === null) continue;
$options[$key] = new bPostNotification($language, $emailAddress, $mobilePhone, $fixedPhone);
}
$deliveryMethod->setInsured($options);
}
$order->setDeliveryMethod($deliveryMethod);
}
// intBusiness?
elseif(isset($return['deliveryMethod']['intBusiness']))
{
$deliveryMethod = new bPostDeliveryMethodIntBusiness();
if(isset($return['deliveryMethod']['intBusiness']['insured']['additionalInsurance']['@attributes']['value']))
{
$deliveryMethod->setInsurance((int) $return['deliveryMethod']['intBusiness']['insured']['additionalInsurance']['@attributes']['value']);
}
// options
if(isset($return['deliveryMethod']['intBusiness']['insured']['options']) && !empty($return['deliveryMethod']['intBusiness']['insured']['options']))
{
$options = array();
foreach($return['deliveryMethod']['intBusiness']['insured']['options'] as $key => $row)
{
$language = 'NL'; // @todo fix me
$emailAddress = null;
$mobilePhone = null;
$fixedPhone = null;
if(isset($row['emailAddress'])) $emailAddress = $row['emailAddress'];
if(isset($row['mobilePhone'])) $mobilePhone = $row['mobilePhone'];
if(isset($row['fixedPhone'])) $fixedPhone = $row['fixedPhone'];
if($emailAddress === null && $mobilePhone === null && $fixedPhone === null) continue;
$options[$key] = new bPostNotification($language, $emailAddress, $mobilePhone, $fixedPhone);
}
$deliveryMethod->setInsured($options);
}
$order->setDeliveryMethod($deliveryMethod);
}
}
// total price
if(isset($return['totalPrice'])) $order->setTotal($return['totalPrice']);
return $order;
}
/**
* Modify the status for an order.
*
* @param string $reference The reference for an order
* @param string $status The new status, allowed values are: OPEN, PENDING, CANCELLED, COMPLETED or ON-HOLD
* @return bool
*/
public function modifyOrderStatus($reference, $status)
{
$allowedStatuses = array('OPEN', 'PENDING', 'CANCELLED', 'COMPLETED', 'ON-HOLD');
$status = mb_strtoupper((string) $status);
// validate
if(!in_array($status, $allowedStatuses))
{
throw new bPostException(
'Invalid status (' . $status . '), allowed values are: ' .
implode(', ', $allowedStatuses) . '.'
);
}
// build url
$url = '/orders/status';
// build data
$data['orderStatusMap']['@attributes']['xmlns'] = 'http://schema.post.be/shm/deepintegration/v2/';
$data['orderStatusMap']['entry']['orderReference'] = (string) $reference;
$data['orderStatusMap']['entry']['status'] = $status;
// build headers
$headers = array(
'X-HTTP-Method-Override: PATCH',
'Content-type: application/vnd.bpost.shm-order-status-v2+XML'
);
// make the call
return ($this->doCall($url, $data, $headers, 'PUT', false) == '');
}
// labels
/**
* Create a national label
*
* @param string $reference Order reference: unique ID used in your web shop to assign to an order.
* @param int $amount Amount of labels.
* @param bool[optional] $withRetour Should the return labeks be included?
* @param bool[optional] $returnLabels Should the labels be included?
* @param string[optional] $labelFormat Format of the labels, possible values are: A_4, A_5.
* @return array
*/
public function createNationalLabel($reference, $amount, $withRetour = null, $returnLabels = null, $labelFormat = null)
{
$allowedLabelFormats = array('A_4', 'A_5');
// validate
if($labelFormat !== null && !in_array($labelFormat, $allowedLabelFormats))
{
throw new bPostException(
'Invalid value for labelFormat (' . $labelFormat . '), allowed values are: ' .
implode(', ', $allowedLabelFormats) . '.'
);
}
// build url
$url = '/labels';
if($labelFormat !== null) $url .= '?labelFormat=' . $labelFormat;
// build data
$data['orderRefLabelAmountMap']['@attributes']['xmlns'] = 'http://schema.post.be/shm/deepintegration/v2/';
$data['orderRefLabelAmountMap']['entry']['orderReference'] = (string) $reference;
$data['orderRefLabelAmountMap']['entry']['labelAmount'] = (int) $amount;
if($withRetour !== null) $data['orderRefLabelAmountMap']['entry']['withRetour'] = (bool) $withRetour;
if($returnLabels !== null) $data['orderRefLabelAmountMap']['entry']['returnLabels'] = ($returnLabels) ? '1' : '0';
// build headers
$headers = array(
'Content-type: application/vnd.bpost.shm-nat-label-v2+XML'
);
// make the call
$return = self::decodeResponse($this->doCall($url, $data, $headers, 'POST'));
// validate
if(!isset($return['entry'])) throw new bPostException('Invalid response.');
// return
return $return['entry'];
}
/**
* Create an international label
*
* @param string $reference Order reference: unique ID used in your web shop to assign to an order.
* @param array $labelInfo For each label an object should be present
* @param bool[optional] $returnLabels Should the labels be included?
* @return array
*/
public function createInternationalLabel($reference, array $labelInfo, $returnLabels = null)
{
// build url
$url = '/labels';
// build data
$data['internationalLabelInfos']['@attributes']['xmlns'] = 'http://schema.post.be/shm/deepintegration/v2/';
foreach($labelInfo as $row)
{
if(!($row instanceof bPostInternationalLabelInfo))
{
throw new bPostException(
'Invalid value for labelInfo, should be an instance of bPostInternationalLabelInfo'
);
}
$data['internationalLabelInfos']['internationalLabelInfo'][] = $row->toXMLArray();
}
$data['internationalLabelInfos']['orderReference'] = (string) $reference;
if($returnLabels !== null) $data['internationalLabelInfos']['returnLabels'] = (bool) $returnLabels;
// build headers
$headers = array(
'Content-type: application/vnd.bpost.shm-int-label-v2+XML'
);
// make the call
$return = self::decodeResponse($this->doCall($url, $data, $headers, 'POST'));
// validate
if(!isset($return['entry'])) throw new bPostException('Invalid response.');
// return
return $return['entry'];
}
/**
* Create an order and the labels
*
* @param bPostOrder $order
* @param int $amount
* @return array
*/
public function createOrderAndNationalLabel(bPostOrder $order, $amount)
{
// build url
$url = '/orderAndLabels';
// build data
$data['orderWithLabelAmount']['@attributes']['xmlns'] = 'http://schema.post.be/shm/deepintegration/v2/';
$data['orderWithLabelAmount']['order'] = $order->toXMLArray($this->accountId);
$data['orderWithLabelAmount']['labelAmount'] = (int) $amount;
// build headers
$headers = array(
'Content-type: application/vnd.bpost.shm-orderAndNatLabels-v2+XML'
);
// make the call
$return = self::decodeResponse($this->doCall($url, $data, $headers, 'POST'));
// validate
if(!isset($return['entry'])) throw new bPostException('Invalid response.');
// return
return $return['entry'];
}