forked from Mastercard-Gateway/gateway-prestashop-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.php
730 lines (629 loc) · 23.5 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
<?php
/**
* Copyright (c) On Tap Networks Limited.
*/
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 mixed $value
* @return string
*/
public static function numeric($value)
{
return number_format($value, 2, '.', '');
}
/**
* @param $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
*/
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/50/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/50/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(sprintf('3DS-'));
$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 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/50/merchant/{merchantId}/session
*
* @param array $order
* @param array $interaction
* @param array $customer
* @param array $billing
* @return array
* @throws Exception
* @throws GatewayResponseException
*/
public function createCheckoutSession(
$order = array(),
$interaction = array(),
$customer = array(),
$billing = array()
) {
$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' => $billing,
'interaction' => $interaction,
'customer' => $customer,
)));
$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 array $theeDSecure
* @param array $session
* @param array $customer
* @param array $billing
* @return mixed|ResponseInterface
* @throws Exception
*/
public function authorize(
$orderId,
$order,
$theeDSecure = null,
$session = array(),
$customer = array(),
$billing = array()
) {
$txnId = '1';
$uri = $this->apiUrl . 'order/' . $orderId . '/transaction/' . $txnId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'AUTHORIZE',
'3DSecure' => $theeDSecure,
'partnerSolutionId' => $this->getSolutionId(),
'order' => array_merge($order, array(
'notificationUrl' => $this->webhookUrl
)),
'billing' => $billing,
'customer' => $customer,
'sourceOfFunds' => array(
'type' => 'CARD'
),
'session' => $session,
)));
$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 array $theeDSecure
* @param array $session
* @param array $customer
* @param array $billing
* @return mixed|ResponseInterface
* @throws Exception
*/
public function pay(
$orderId,
$order = array(),
$theeDSecure = null,
$session = array(),
$customer = array(),
$billing = array()
) {
$txnId = '1';
$uri = $this->apiUrl . 'order/' . $orderId . '/transaction/' . $txnId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'PAY',
'3DSecure' => $theeDSecure,
'partnerSolutionId' => $this->getSolutionId(),
'order' => array_merge($order, array(
'notificationUrl' => $this->webhookUrl
)),
'billing' => $billing,
'customer' => $customer,
'sourceOfFunds' => array(
'type' => 'CARD'
),
'session' => $session,
)));
$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/50/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/50/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/50/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 = 'void-' . $txnId;
$uri = $this->apiUrl . 'order/' . $orderId . '/transaction/' . $newTxnId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'VOID',
'partnerSolutionId' => $this->getSolutionId(),
'transaction' => array(
'targetTransactionId' => $txnId
)
)));
$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/50/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}
*
* @param string $orderId
* @param string $txnId
* @param $amount
* @param $currency
* @return mixed|ResponseInterface
* @throws Exception
*/
public function captureTxn($orderId, $txnId, $amount, $currency)
{
$newTxnId = 'capture-' . $txnId;
$uri = $this->apiUrl . 'order/' . $orderId . '/transaction/' . $newTxnId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'CAPTURE',
'partnerSolutionId' => $this->getSolutionId(),
'transaction' => array(
'amount' => $amount,
'currency' => $currency
),
'order' => array(
'notificationUrl' => $this->webhookUrl
)
)));
$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/50/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}
*
* @param $orderId
* @param $txnId
* @param $amount
* @param $currency
* @return mixed|ResponseInterface
* @throws Exception
*/
public function refund($orderId, $txnId, $amount, $currency)
{
$newTxnId = 'refund-' . $txnId;
$uri = $this->apiUrl . 'order/' . $orderId . '/transaction/' . $newTxnId;
$request = $this->messageFactory->createRequest('PUT', $uri, array(), json_encode(array(
'apiOperation' => 'REFUND',
'partnerSolutionId' => $this->getSolutionId(),
'transaction' => array(
'amount' => $amount,
'currency' => $currency
),
'order' => array(
'notificationUrl' => $this->webhookUrl
)
)));
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
$this->validateTxnResponse($response);
return $response;
}
/**
* Request to retrieve the options available for processing a payment, for example, the credit cards and currencies.
* https://mtf.gateway.mastercard.com/api/rest/version/51/merchant/{merchantId}/paymentOptionsInquiry
*/
public function paymentOptionsInquiry()
{
$uri = $this->apiUrl . 'paymentOptionsInquiry';
$request = $this->messageFactory->createRequest('GET', $uri);
$response = $this->client->sendRequest($request);
$response = json_decode($response->getBody(), true);
return $response;
}
}