-
Notifications
You must be signed in to change notification settings - Fork 12
/
gateway.php
1059 lines (927 loc) · 33.2 KB
/
gateway.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
/**
* Copyright (c) 2019-2022 Mastercard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
use Http\Discovery\HttpClientDiscovery;
use Http\Message\MessageFactory\GuzzleMessageFactory;
use Http\Client\Common\Plugin\AuthenticationPlugin;
use Http\Message\Authentication\BasicAuth;
use Http\Client\Common\PluginClient;
use Http\Message\RequestMatcher\RequestMatcher;
use Http\Client\Common\HttpClientRouter;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Http\Client\Common\Plugin\ContentLengthPlugin;
use Http\Client\Common\Plugin\HeaderSetPlugin;
use Http\Client\Common\Plugin;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Http\Message\Formatter;
use Http\Message\Formatter\SimpleFormatter;
use Http\Client\Exception;
use Http\Client\Common\Exception\ClientErrorException;
use Http\Client\Common\Exception\ServerErrorException;
class ApiErrorPlugin implements Plugin
{
/**
* @inheritdoc
*/
public function handleRequest(\Psr\Http\Message\RequestInterface $request, callable $next, callable $first)
{
$promise = $next($request);
return $promise->then(function (ResponseInterface $response) use ($request) {
return $this->transformResponseToException($request, $response);
});
}
/**
* @param RequestInterface $request
* @param ResponseInterface $response
*
* @return ResponseInterface
*/
protected function transformResponseToException(RequestInterface $request, ResponseInterface $response)
{
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
$responseData = @json_decode($response->getBody(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ServerErrorException("Response not valid JSON", $request, $response);
}
$msg = '';
if (isset($responseData['error']['cause'])) {
$msg .= $responseData['error']['cause'].': ';
}
if (isset($responseData['error']['explanation'])) {
$msg .= $responseData['error']['explanation'];
}
throw new ClientErrorException($msg, $request, $response);
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
throw new ServerErrorException($response->getReasonPhrase(), $request, $response);
}
return $response;
}
}
class ApiLoggerPlugin implements Plugin
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var Formatter
*/
private $formatter;
/**
* @inheritdoc
*/
public function __construct(LoggerInterface $logger, Formatter $formatter = null)
{
$this->logger = $logger;
$this->formatter = $formatter ?: new SimpleFormatter();
}
/**
* @inheritdoc
*/
public function handleRequest(\Psr\Http\Message\RequestInterface $request, callable $next, callable $first)
{
$reqBody = @json_decode($request->getBody(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
$reqBody = $request->getBody();
}
$this->logger->info(sprintf('Emit request: "%s"', $this->formatter->formatRequest($request)),
['request' => $reqBody]);
return $next($request)->then(function (ResponseInterface $response) use ($request) {
$body = @json_decode($response->getBody(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
$body = $response->getBody();
}
$this->logger->info(
sprintf('Receive response: "%s" for request: "%s"', $this->formatter->formatResponse($response),
$this->formatter->formatRequest($request)),
[
'response' => $body,
]
);
return $response;
}, function (\Exception $exception) use ($request) {
if ($exception instanceof Exception\HttpException) {
$this->logger->error(
sprintf('Error: "%s" with response: "%s" when emitting request: "%s"', $exception->getMessage(),
$this->formatter->formatResponse($exception->getResponse()),
$this->formatter->formatRequest($request)),
[
'request' => $request,
'response' => $exception->getResponse(),
'exception' => $exception,
]
);
} else {
$this->logger->error(
sprintf('Error: "%s" when emitting request: "%s"', $exception->getMessage(),
$this->formatter->formatRequest($request)),
[
'request' => $request,
'exception' => $exception,
]
);
}
throw $exception;
});
}
}
class GatewayResponseException extends \Exception
{
}
class GatewayService
{
/**
* @var GuzzleMessageFactory
*/
protected $messageFactory;
/**
* @var string
*/
protected $apiUrl;
/**
* @var HttpClientRouter
*/
protected $client;
/**
* @var string|null
*/
protected $webhookUrl;
/**
* GatewayService constructor.
*
* @param string $baseUrl
* @param string $apiVersion
* @param string $merchantId
* @param string $password
* @param string $webhookUrl
*
* @throws \Exception
*/
public function __construct(
$baseUrl,
$apiVersion,
$merchantId,
$password,
$webhookUrl
) {
$this->webhookUrl = $webhookUrl;
$logger = new Logger('mastercard');
$logger->pushHandler(new StreamHandler(
_PS_ROOT_DIR_.'/var/logs/mastercard.log',
Configuration::get('mpgs_logging_level')
));
$this->messageFactory = new GuzzleMessageFactory();
$this->apiUrl = "https://{$baseUrl}/api/rest/version/{$apiVersion}/merchant/{$merchantId}/";
$username = 'merchant.'.$merchantId;
$client = new PluginClient(
HttpClientDiscovery::find(),
array(
new ContentLengthPlugin(),
new HeaderSetPlugin(['Content-Type' => 'application/json;charset=UTF-8']),
new AuthenticationPlugin(new BasicAuth($username, $password)),
new ApiErrorPlugin(),
new ApiLoggerPlugin($logger),
)
);
$requestMatcher = new RequestMatcher(null, $baseUrl);
$this->client = new HttpClientRouter();
$this->client->addClient(
$client,
$requestMatcher
);
}
/**
* Data format is: CART_X.X.X_DEV_X.X.X o e.g MAGENTO_2.0.2_CARTDEV_2.0.0
* where MAGENTO_2.0.2 represents Magento version 2.0.2 and CARTDEV_2.0.0
* represents extension developer CARTDEV and extension version 2.0.0
*
* @return string
*/
protected function getSolutionId()
{
return 'PRESTASHOP_'._PS_VERSION_.'_ONTAP_'.MPGS_VERSION;
}
/**
* @param $value
* @param int $limited
*
* @return bool|string|null
*/
public static function safe($value, $limited = 0)
{
if ($value === "") {
return null;
}
if ($limited > 0 && Tools::strlen($value) > $limited) {
return Tools::substr($value, 0, $limited);
}
return $value;
}
/**
* @param string $class
* @param string $property
* @param int $limited
*
* @return bool|string|null
*/
public static function safeProperty($class, $property, $limited = 0)
{
if (!property_exists($class, $property)) {
return null;
}
return static::safe($class->{$property}, $limited);
}
/**
* @param mixed $value
*
* @return string
*/
public static function numeric($value)
{
return number_format($value, 2, '.', '');
}
/**
* @param array $data
*
* @throws GatewayResponseException
*/
public function validateInitiateAuthenticationResponse($data)
{
if (!isset($data['result']) || $data['result'] !== 'SUCCESS') {
throw new GatewayResponseException('Missing or invalid session result.');
}
if (!isset($data['transaction']['id'])) {
throw new GatewayResponseException('Missing session or ID.');
}
}
/**
* @param array $data
*
* @throws GatewayResponseException
*/
public function validateAuthenticatePayerResponse($data)
{
$result = isset($data['result']) ? $data['result'] : '';
if ($result !== 'SUCCESS' && $result !== 'PROCEED' && $result !== 'PENDING') {
throw new GatewayResponseException('Missing or invalid session result.');
}
if (!isset($data['transaction']['id'])) {
throw new GatewayResponseException('Missing session or ID.');
}
}
/**
* @param array $data
*
* @throws GatewayResponseException
*/
public function validateCheckoutSessionResponse($data)
{
if (!isset($data['result']) || $data['result'] !== 'SUCCESS') {
throw new GatewayResponseException('Missing or invalid session result.');
}
if (!isset($data['session']) || !isset($data['session']['id'])) {
throw new GatewayResponseException('Missing session or ID.');
}
}
/**
* @param array $data
*
* @throws GatewayResponseException
*/
public function validateHostedSessionUpdateResponse($data)
{
if (!isset($data['session']) || $data['session']['updateStatus'] !== 'SUCCESS') {
throw new GatewayResponseException('Failed to update Hosted Session.');
}
}
/**
* @param array $data
*/
public function validateTxnResponse($data)
{
// @todo
}
/**
* @param array $data
*/
public function validateOrderResponse($data)
{
// @todo
}
/**
* @param array $data
*/
public function validateVoidResponse($data)
{
// @todo
}
/**
* @param $response
*
* @return bool
*/
public function isApproved($response)
{
$gatewayCode = $response['response']['gatewayCode'];
if (!in_array($gatewayCode, array('APPROVED', 'APPROVED_AUTO'))) {
return false;
}
return true;
}
/**
* Interprets the authentication response returned from the card Issuer's Access Control Server (ACS)
* after the cardholder completes the authentication process. The response indicates the success
* or otherwise of the authentication.
* The 3DS AuthId is required so that merchants can submit payloads multiple times
* without producing duplicates in the database.
* POST https://mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/3DSecureId/{3DSecureId}
*
* @param string $threeDSecureId
* @param string $paRes
*
* @return mixed|ResponseInterface
* @throws Exception
*/
public function process3dsResult($threeDSecureId, $paRes)
{
$uri = $this->apiUrl.'3DSecureId/'.$threeDSecureId;
$request = $this->messageFactory->createRequest('POST', $uri, array(), json_encode(array(
'apiOperation' => 'PROCESS_ACS_RESULT',
'3DSecure' => array('paRes' => $paRes),
)));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
return $response;
}
/**
* Request to check a cardholder's enrollment in the 3DSecure scheme.
* PUT https://mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/3DSecureId/{3DSecureId}
*
* @param array $data
* @param array $order
* @param array $session
*
* @return mixed|ResponseInterface
* @throws Exception
*/
public function check3dsEnrollment($data, $order, $session)
{
$threeDSecureId = uniqid('3DS-', true);
$uri = $this->apiUrl.'3DSecureId/'.$threeDSecureId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'CHECK_3DS_ENROLLMENT',
'3DSecure' => $data,
'order' => $order,
'session' => $session,
)));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
return $response;
}
/**
* Create initiate authentication
*
* @see https://test-gateway.mastercard.com/api/documentation/apiDocumentation/rest-json/version/latest/operation/Authentication%3a%20%20Initiate%20Authentication.html?locale=en_US
*
* @param string $orderId
* @param array $session
* @param array $order
*/
public function initiateAuthentication(
$orderId,
$session,
$order
) {
$txnId = uniqid($orderId.'-', true);
$uri = $this->apiUrl.'order/'.$orderId.'/transaction/'.$txnId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'INITIATE_AUTHENTICATION',
'authentication' => [
'acceptVersions' => '3DS1,3DS2',
'channel' => 'PAYER_BROWSER',
'purpose' => 'PAYMENT_TRANSACTION',
],
'session' => $session,
'order' => array_merge($order, array(
'reference' => $orderId,
)),
'transaction' => array(
'reference' => $txnId,
),
)));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateInitiateAuthenticationResponse($response);
return $response;
}
/**
* Authenticate Payer
*
* @see https://test-gateway.mastercard.com/api/documentation/apiDocumentation/rest-json/version/latest/operation/Authentication%3a%20%20Initiate%20Authentication.html?locale=en_US
*
* @param string $orderId
* @param array $session
* @param array $order
* @param array $device
* @param string $txnId
* @param string $responseUrl
* @param array $customer
* @param array $billing
* @param array $shipping
* @param array $shippingContact
*/
public function authenticatePayer(
$orderId,
$session,
$order,
$device,
$txnId,
$responseUrl,
$customer = array(),
$billing = array(),
$shipping = array(),
$shippingContact = array()
) {
$uri = $this->apiUrl.'order/'.$orderId.'/transaction/'.$txnId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'AUTHENTICATE_PAYER',
'authentication' => [
'redirectResponseUrl' => $responseUrl,
],
'device' => $device,
'session' => $session,
'order' => $order,
'billing' => array(
'address' => $billing,
),
'shipping' => array(
'address' => $shipping,
'contact' => $shippingContact,
),
'customer' => $customer,
)));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateAuthenticatePayerResponse($response);
return $response;
}
/**
* @param string $orderId
* @param string $sessionId
* @param array $order
* @param array $authentication
* @param array $transaction
*
* @return mixed
* @throws Exception
* @throws GatewayResponseException
*/
public function updateSession(
string $orderId,
string $sessionId,
$order,
$authentication = array(),
$transaction = array()
) {
$uri = $this->apiUrl.'session/'.$sessionId;
$requestData = array(
'partnerSolutionId' => $this->getSolutionId(),
'order' => array_merge($order, array(
'id' => $orderId,
)),
);
if (!empty($transaction)) {
$requestData['transaction'] = $transaction;
}
if (!empty($authentication)) {
$requestData['authentication'] = $authentication;
}
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode($requestData));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateHostedSessionUpdateResponse($response);
return $response;
}
/**
* Create Checkout Session
* Request to create a session identifier for the checkout interaction.
* The session identifier, when included in the Checkout.configure() function,
* allows you to return the payer to the merchant's website after completing the payment attempt.
* https://mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/session
*
* @param array $order
* @param array $interaction
* @param array $customer
* @param array $billing
* @param array $shipping
* @param array $shippingContact
*
* @return array
* @throws Exception
* @throws GatewayResponseException
*/
public function createCheckoutSession(
$order = array(),
$interaction = array(),
$customer = array(),
$billing = array(),
$shipping = array(),
$shippingContact = array()
) {
$orderId = $order['id'];
$txnId = $this->getUniqueTransactionId($orderId);
$uri = $this->apiUrl.'session';
$request = $this->messageFactory->createRequest('POST', $uri, array(), json_encode(array(
'apiOperation' => 'CREATE_CHECKOUT_SESSION',
'partnerSolutionId' => $this->getSolutionId(),
'order' => array_merge($order, array(
'notificationUrl' => $this->webhookUrl,
)),
'billing' => array(
'address' => $billing,
),
'shipping' => array(
'address' => $shipping,
'contact' => $shippingContact,
),
'interaction' => $interaction,
'customer' => $customer,
'transaction' => array(
'reference' => $txnId,
),
)));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateCheckoutSessionResponse($response);
return $response;
}
/**
* Request to obtain an authorization for a proposed funds transfer.
* An authorization is a response from a financial institution indicating that payment information
* is valid and funds are available in the payers account.
* https://mtf.gateway.mastercard.com/api/rest/version/50/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}
*
* @param string $orderId
* @param array $order
* @param string $threeDSecureId
* @param array $session
* @param array $customer
* @param array $billing
* @param array $shipping
* @param array $shippingContact
* @param array $authentication
* @param string $threeDSVersion
*
* @return mixed|ResponseInterface
* @throws Exception
*/
public function authorize(
$orderId,
$order,
$threeDSecureId = null,
$session = array(),
$customer = array(),
$billing = array(),
$shipping = array(),
$shippingContact = array(),
$authentication = array(),
$threeDSVersion = '1'
) {
$txnId = $this->getUniqueTransactionId($orderId);
$uri = $this->apiUrl.'order/'.$orderId.'/transaction/'.$txnId;
$body = array(
'apiOperation' => 'AUTHORIZE',
'partnerSolutionId' => $this->getSolutionId(),
'order' => array_merge($order, array(
'notificationUrl' => $this->webhookUrl,
'reference' => $orderId,
)),
'billing' => array(
'address' => $billing,
),
'shipping' => array(
'address' => $shipping,
'contact' => $shippingContact,
),
'customer' => $customer,
'sourceOfFunds' => array(
'type' => 'CARD',
),
'session' => $session,
'transaction' => array(
'reference' => $txnId,
),
);
if ($threeDSVersion == 1) {
$body['3DSecureId'] = $threeDSecureId;
} elseif ($threeDSVersion == 2) {
$body['authentication'] = $authentication;
}
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode($body));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateTxnResponse($response);
return $response;
}
/**
* A single transaction to authorise the payment and transfer funds from the payer's account to your account.
*
* For card payments, Pay is a mode where the Authorize and Capture operations are completed at the same time.
* Pay is the most common type of payment model used by merchants to accept card payments.
* The Pay model is used when the merchant is allowed to bill the cardholder's account immediately,
* for example when providing services or goods on the spot.
* PUT https://mtf.gateway.mastercard.com/api/rest/version/50/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}
*
* @param string $orderId
* @param array $order
* @param string $threeDSecureId
* @param array $session
* @param array $customer
* @param array $billing
* @param array $shipping
* @param array $shippingContact
* @param array $authentication
* @param string $threeDSVersion
*
* @return mixed|ResponseInterface
* @throws Exception
*/
public function pay(
$orderId,
$order = array(),
$threeDSecureId = null,
$session = array(),
$customer = array(),
$billing = array(),
$shipping = array(),
$shippingContact = array(),
$authentication = array(),
$threeDSVersion = '1'
) {
$txnId = $this->getUniqueTransactionId($orderId);
$uri = $this->apiUrl.'order/'.$orderId.'/transaction/'.$txnId;
$body = array(
'apiOperation' => 'PAY',
'partnerSolutionId' => $this->getSolutionId(),
'order' => array_merge($order, array(
'notificationUrl' => $this->webhookUrl,
'reference' => $orderId,
)),
'billing' => array(
'address' => $billing,
),
'shipping' => array(
'address' => $shipping,
'contact' => $shippingContact,
),
'customer' => $customer,
'sourceOfFunds' => array(
'type' => 'CARD',
),
'session' => $session,
'transaction' => array(
'reference' => $txnId,
),
);
if ($threeDSVersion == 1) {
$body['3DSecureId'] = $threeDSecureId;
} elseif ($threeDSVersion == 2) {
$body['authentication'] = $authentication;
}
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode($body));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateTxnResponse($response);
return $response;
}
/**
* Retrieve order
* Request to retrieve the details of an order and all transactions associated with this order.
* https://mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/order/{orderid}
*
* @param string $orderId
*
* @return array
* @throws \Http\Client\Exception
*/
public function retrieveOrder($orderId)
{
$uri = $this->apiUrl.'order/'.$orderId;
$request = $this->messageFactory->createRequest('GET', $uri);
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateOrderResponse($response);
return $response;
}
/**
* Helper method to find the authorisation transaction
*
* @param string $orderId
* @param array $response
*
* @return null|array
* @throws Exception
*/
public function getAuthorizationTransaction($orderId, $response = array())
{
if (empty($response)) {
$response = $this->retrieveOrder($orderId);
}
// @todo: Find only the first one
foreach ($response['transaction'] as $txn) {
if ($txn['transaction']['type'] === 'AUTHORIZATION' && $txn['result'] == 'SUCCESS') {
return $txn;
}
}
return null;
}
/**
* Helper method to find the capture/pay transaction
*
* @param string $orderId
* @param array $response
*
* @return null|array
* @throws Exception
*/
public function getCaptureTransaction($orderId, $response = array())
{
if (empty($response)) {
$response = $this->retrieveOrder($orderId);
}
// @todo: Find only the first one
foreach ($response['transaction'] as $txn) {
if (($txn['transaction']['type'] === 'CAPTURE' || $txn['transaction']['type'] === 'PAYMENT') && $txn['result'] == 'SUCCESS') {
return $txn;
}
}
return null;
}
/**
* Request to retrieve the details of a transaction. For example you can retrieve the details of an authorization that you previously executed.
* https://mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}
*
* @param string $orderId
* @param string $txnId
*
* @return array
* @throws Exception
*/
public function retrieveTransaction($orderId, $txnId)
{
$uri = $this->apiUrl.'order/'.$orderId.'/transaction/'.$txnId;
$request = $this->messageFactory->createRequest('GET', $uri);
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateTxnResponse($response);
return $response;
}
/**
* Request to void a previous transaction. A void will reverse a previous transaction.
* Typically voids will only be successful when processed not long after the original transaction.
* https://mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}
*
* @param string $orderId
* @param string $txnId
*
* @return mixed|\Psr\Http\Message\ResponseInterface
* @throws Exception
*/
public function voidTxn($orderId, $txnId)
{
$newTxnId = $this->getUniqueTransactionId($orderId);
$uri = $this->apiUrl.'order/'.$orderId.'/transaction/'.$newTxnId;
$requestData = array(
'apiOperation' => 'VOID',
'partnerSolutionId' => $this->getSolutionId(),
'transaction' => array(
'targetTransactionId' => $txnId,
'reference' => $newTxnId,
),
);
$requestJson = json_encode($requestData);
$request = $this->messageFactory->createRequest('PUT', $uri, array(), $requestJson);
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateVoidResponse($response);
return $response;
}
/**
* Request to capture funds previously reserved by an authorization.
* A Capture transaction triggers the movement of funds from the payer's account to the merchant's account.
* Typically, a Capture is linked to the authorization through the orderId - you provide the original orderId,
* a new transactionId, and the amount you wish to capture.
* You may provide other fields (such as shipping address) if you want to update their values; however,
* you must NOT provide sourceOfFunds.
* https://mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}
*
* @param string $orderId
* @param float $amount
* @param string $currency
*
* @return mixed|ResponseInterface
* @throws Exception
*/
public function captureTxn($orderId, $amount, $currency)
{
$txnId = $this->getUniqueTransactionId($orderId);
$uri = $this->apiUrl.'order/'.$orderId.'/transaction/'.$txnId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'CAPTURE',
'partnerSolutionId' => $this->getSolutionId(),
'transaction' => array(
'amount' => $amount,
'currency' => $currency,
'reference' => $txnId,
),
'order' => array(
'notificationUrl' => $this->webhookUrl,
'reference' => $orderId,
),
)));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateTxnResponse($response);
return $response;
}
/**
* Request to refund previously captured funds to the payer.
* Typically, a Refund is linked to the Capture or Pay through the orderId - you provide the original orderId,
* a new transactionId, and the amount you wish to refund. You may provide other fields if you want to update their values;
* however, you must NOT provide sourceOfFunds.
* In rare situations, you may want to refund the payer without associating the credit to a previous transaction (see Standalone Refund).
* In this case, you need to provide the sourceOfFunds and a new orderId.
* https://mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}
*
* @param string $orderId
* @param float $amount
* @param string $currency
*
* @return mixed|ResponseInterface