-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGateway.php
2944 lines (2576 loc) · 113 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 © 2015-present ParadoxLabs, Inc.
*
* 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.
*
* Need help? Try our knowledgebase and support system:
* @link https://support.paradoxlabs.com
*/
namespace ParadoxLabs\Authnetcim\Model;
use Magento\Payment\Gateway\Command\CommandException;
/**
* Authorize.Net CIM API Gateway - custom built for perfection.
*/
class Gateway extends \ParadoxLabs\TokenBase\Model\AbstractGateway
{
/**
* Authorize.Net registered solution ID
*
* @var string
*/
public const SOLUTION_ID = 'A1000133';
/**
* Authorize.Net transaction duplicate window
*
* @var int
*/
public const DUPLICATE_WINDOW = 30;
/**
* Transaction status codes indicating denial on review
*
* @var string[]
*/
public const DENY_STATUSES = [
'declined',
'expired',
'failedReview',
'generalError',
'returnedItem',
'voided',
];
public const AUTHORIZED_STATUSES = [
'authorizedPendingCapture',
'FDSAuthorizedPendingReview',
'FDSPendingReview',
'underReview',
];
/**
* @var string
*/
protected $code = 'authnetcim';
/**
* @var string
*/
protected $endpointLive = 'https://api2.authorize.net/xml/v1/request.api';
/**
* @var string
*/
protected $endpointTest = 'https://apitest.authorize.net/xml/v1/request.api';
/**
* $fields defines validation for each API parameter or input.
*
* key => [
* 'maxLength' => int,
* 'noSymbols' => true|false,
* 'charMask' => (allowed characters in regex form),
* 'enum' => [ values ]
* ]
*
* @var array
*/
protected $fields = [
'accountNumber' => ['maxLength' => 17, 'charMask' => 'X\d'],
'accountType' => ['enum' => ['checking', 'savings', 'businessChecking']],
'allowPartialAuth' => ['enum' => ['true', 'false']],
'amount' => [],
'approvalCode' => ['maxLength'],
'bankName' => ['maxLength' => 50],
'billToAddress' => ['maxLength' => 60, 'noSymbols' => true],
'billToCity' => ['maxLength' => 40, 'noSymbols' => true],
'billToCompany' => ['maxLength' => 50, 'noSymbols' => true],
'billToCountry' => ['maxLength' => 60, 'noSymbols' => true],
'billToFaxNumber' => ['maxLength' => 25, 'charMask' => '\d\(\)\-\.'],
'billToFirstName' => ['maxLength' => 50, 'noSymbols' => true],
'billToLastName' => ['maxLength' => 50, 'noSymbols' => true],
'billToPhoneNumber' => ['maxLength' => 25, 'charMask' => '\d\(\)\-\.'],
'billToState' => ['maxLength' => 40, 'noSymbols' => true],
'billToZip' => ['maxLength' => 20, 'noSymbols' => true],
'cardCode' => ['maxLength' => 4, 'charMask' => '\d'],
'cardNumber' => ['maxLength' => 16, 'charMask' => 'X\d'],
'centinelAuthIndicator' => ['maxLength' => 2, 'charMask' => '\d'],
'centinelAuthValue' => [],
'customerIp' => [],
'customerPaymentProfileId' => ['charMask' => '\d'],
'customerProfileId' => ['charMask' => '\d'],
'customerShippingAddressId' => ['charMask' => '\d'],
'customerType' => ['enum' => ['individual', 'business']],
'dataDescriptor' => ['noSymbols' => true],
'dataValue' => ['charMask' => 'a-zA-Z0-9+\/\\='],
'description' => ['maxLength' => 255],
'deviceType' => ['charMask' => '\d'],
'duplicateWindow' => ['charMask' => '\d'],
'dutyAmount' => [],
'dutyDescription' => ['maxLength' => 255],
'dutyName' => ['maxLength' => 31],
'echeckType' => ['enum' => ['CCD', 'PPD', 'TEL', 'WEB', 'ARC', 'BOC']],
'email' => ['maxLength' => 255],
'emailCustomer' => ['enum' => ['true', 'false']],
'expirationDate' => ['maxLength' => 7],
'hostedPaymentAddProfile' => ['enum' => [true, false]],
'hostedPaymentCancelText' => ['maxLength' => 31],
'hostedPaymentPayButtonText' => ['maxLength' => 31],
'hostedPaymentCardCodeRequired' => ['enum' => [true, false]],
'hostedPaymentShowCreditCard' => ['enum' => [true, false]],
'hostedPaymentShowBankAccount' => ['enum' => [true, false]],
'hostedPaymentShowMerchantName' => ['enum' => [true, false]],
'hostedPaymentValidateCaptcha' => ['enum' => [true, false]],
'hostedProfileSaveButtonText' => ['maxLength' => 32, 'noSymbols' => true],
'hostedProfilePageBorderVisible' => ['enum' => [true, false]],
'hostedProfileHeadingBgColor' => ['maxLength' => 7, 'charMask' => 'a-zA-Z0-9#'],
'hostedProfileIFrameCommunicatorUrl' => [],
'hostedProfilePaymentOptions' => ['enum' => ['showAll', 'showCreditCard', 'showBankAccount']],
'hostedProfileBillingAddressRequired' => ['enum' => [true, false]],
'hostedProfileCardCodeRequired' => ['enum' => [true, false]],
'hostedProfileBillingAddressOptions' => ['enum' => ['showBillingAddress', 'showNone']],
'hostedProfileManageOptions' => ['enum' => ['showAll', 'showPayment', 'showShipping']],
'includeIssuerInfo' => ['enum' => ['true', 'false']],
'invoiceNumber' => ['maxLength' => 20, 'noSymbols' => true],
'isFirstRecurringPayment' => ['enum' => ['true', 'false']],
'isFirstSubsequentAuth' => ['enum' => ['true', 'false']],
'isStoredCredentials' => ['enum' => ['true', 'false']],
'isSubsequentAuth' => ['enum' => ['true', 'false']],
'itemName' => ['maxLength' => 31, 'noSymbols' => true],
'loginId' => ['maxLength' => 20],
'marketType' => ['charMask' => '\d'],
'merchantCustomerId' => ['maxLength' => 20],
'nameOnAccount' => ['maxLength' => 22],
'profileType' => ['enum' => ['guest', 'regular']],
'purchaseOrderNumber' => ['maxLength' => 25, 'noSymbols' => true],
'recurringBilling' => ['enum' => ['true', 'false']],
'refId' => ['maxLength' => 20],
'routingNumber' => ['maxLength' => 9, 'charMask' => 'X\d'],
'shipAmount' => [],
'shipDescription' => ['maxLength' => 255],
'shipName' => ['maxLength' => 31],
'shipToAddress' => ['maxLength' => 60, 'noSymbols' => true],
'shipToCity' => ['maxLength' => 40, 'noSymbols' => true],
'shipToCompany' => ['maxLength' => 50, 'noSymbols' => true],
'shipToCountry' => ['maxLength' => 60, 'noSymbols' => true],
'shipToFaxNumber' => ['maxLength' => 25, 'charMask' => '\d\(\)\-\.'],
'shipToFirstName' => ['maxLength' => 50, 'noSymbols' => true],
'shipToLastName' => ['maxLength' => 50, 'noSymbols' => true],
'shipToPhoneNumber' => ['maxLength' => 25, 'charMask' => '\d\(\)\-\.'],
'shipToState' => ['maxLength' => 40, 'noSymbols' => true],
'shipToZip' => ['maxLength' => 20, 'noSymbols' => true],
'splitTenderId' => ['maxLength' => 6],
'subsequentAuthReason' => ['enum' => ['delayedCharge', 'noShow', 'resubmission', 'reauthorization']],
'taxAmount' => [],
'taxDescription' => ['maxLength' => 255],
'taxExempt' => ['enum' => ['true', 'false']],
'taxName' => ['maxLength' => 31],
'transactionKey' => ['maxLength' => 16, 'noSymbols' => true],
'transactionType' => [
'enum' => [
// Old types
'profileTransAuthCapture',
'profileTransAuthOnly',
'profileTransCaptureOnly',
'profileTransPriorAuthCapture',
'profileTransRefund',
'profileTransVoid',
// New types
'authCaptureTransaction',
'authOnlyTransaction',
'captureOnlyTransaction',
'priorAuthCaptureTransaction',
'refundTransaction',
'voidTransaction',
'updateHeldTransaction',
],
],
'transId' => ['charMask' => '\d'],
'unmaskExpirationDate' => ['enum' => ['true', 'false']],
'updateAction' => ['enum' => ['approve', 'decline']],
'userFields' => [],
'validationMode' => ['enum' => ['liveMode', 'testMode']],
];
/**
* @var array
*/
protected $txnTypeMap = [
'authCaptureTransaction' => 'auth_capture',
'authOnlyTransaction' => 'auth_only',
'captureOnlyTransaction' => 'capture_only',
'priorAuthCaptureTransaction' => 'prior_auth_capture',
'refundTransaction' => 'credit',
'voidTransaction' => 'void',
'updateHeldTransaction' => 'update_held_transaction',
];
/**
* @var \Magento\Framework\Module\Dir
*/
protected $moduleDir;
/**
* @var \Magento\Framework\Registry
*/
protected $registry;
/**
* Gateway constructor.
*
* @param \ParadoxLabs\TokenBase\Helper\Data $helper
* @param \ParadoxLabs\TokenBase\Model\Gateway\Xml $xml
* @param \ParadoxLabs\TokenBase\Model\Gateway\ResponseFactory $responseFactory
* @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
* @param \Magento\Framework\Module\Dir $moduleDir
* @param \Magento\Framework\Registry $registry
* @param array $data
* @param \Magento\Framework\HTTP\ClientInterfaceFactory|null $communicatorFactory
*/
public function __construct(
\ParadoxLabs\TokenBase\Helper\Data $helper,
\ParadoxLabs\TokenBase\Model\Gateway\Xml $xml,
\ParadoxLabs\TokenBase\Model\Gateway\ResponseFactory $responseFactory,
\Magento\Framework\HTTP\ZendClientFactory $httpClientFactory,
\Magento\Framework\Module\Dir $moduleDir,
\Magento\Framework\Registry $registry,
array $data = [],
\Magento\Framework\HTTP\ClientInterfaceFactory $communicatorFactory = null
) {
$this->moduleDir = $moduleDir;
$this->registry = $registry;
parent::__construct(
$helper,
$xml,
$responseFactory,
$httpClientFactory,
$data,
$communicatorFactory
);
}
/**
* Set the API credentials so they go through validation.
*
* @return $this
*/
public function clearParameters()
{
parent::clearParameters();
if (isset($this->defaults['login'], $this->defaults['password'])) {
$this->setParameter('loginId', $this->defaults['login']);
$this->setParameter('transactionKey', $this->defaults['password']);
}
return $this;
}
/**
* Send the given request to Authorize.Net and process the results.
*
* @param string $request
* @param array $params
* @return array|string
* @throws CommandException
* @throws CommandException
*/
protected function runTransaction($request, $params)
{
$auth = [
'@attributes' => [
'xmlns' => 'AnetApi/xml/v1/schema/AnetApiSchema.xsd',
],
'merchantAuthentication' => [
'name' => $this->getParameter('loginId'),
'transactionKey' => $this->getParameter('transactionKey'),
],
];
$xml = $this->arrayToXml($request, $auth + $params);
$this->lastRequest = $xml;
/** @var \Magento\Framework\HTTP\Client\Curl|\Magento\Framework\HTTP\Client\Socket $communicator */
$communicator = $this->communicatorFactory->create();
// If we are running a money transaction, we don't want to cut it off even if it takes too long.
// Override that 900 second timeout only if this is a non-critical transaction.
$communicator->setTimeout(900);
if (!in_array($request, ['createTransactionRequest', 'createCustomerProfileTransactionRequest'])) {
$communicator->setTimeout(15);
}
$communicator->setOption(\CURLOPT_SSL_VERIFYPEER, false);
$communicator->setOption(\CURLOPT_SSL_VERIFYHOST, 0);
if ($this->verifySsl === true) {
$certificatePath = $this->moduleDir->getDir('ParadoxLabs_Authnetcim') . '/authorizenet-cert.pem';
$communicator->setOption(\CURLOPT_SSL_VERIFYPEER, true);
$communicator->setOption(\CURLOPT_SSL_VERIFYHOST, 2);
$communicator->setOption(\CURLOPT_CAINFO, $certificatePath);
}
$communicator->addHeader('Content-Type', 'text/xml');
try {
$communicator->post($this->endpoint, $xml);
$this->lastResponse = $communicator->getBody();
if (!empty($this->lastResponse)) {
$this->log .= 'REQUEST: ' . $this->sanitizeLog($xml) . "\n";
$this->log .= 'RESPONSE: ' . $this->sanitizeLog($this->lastResponse) . "\n";
$this->lastResponse = $this->xmlToArray($this->lastResponse);
if ($this->testMode === true) {
$this->helper->log($this->code, $this->log, true);
}
/**
* Check for basic errors.
*/
$this->handleTransactionError();
} else {
$this->helper->log(
$this->code,
sprintf(
"Connection failed, empty response\nREQUEST: %s",
$this->sanitizeLog($xml)
)
);
throw new CommandException(
__('Authorize.Net CIM Gateway Connection failed')
);
}
} catch (\Exception $e) {
$this->helper->log(
$this->code,
sprintf(
"CURL Connection error: %s\nREQUEST: %s",
$e->getMessage(),
$this->sanitizeLog($xml)
)
);
throw new CommandException(
__(sprintf(
'Authorize.Net CIM Gateway Connection error: %s',
$e->getMessage()
))
);
}
return $this->lastResponse;
}
/**
* Mask certain values in the XML for secure logging purposes.
*
* @param string $string
* @return mixed
*/
protected function sanitizeLog($string)
{
$maskAll = ['cardCode'];
$maskFour = ['cardNumber', 'name', 'transactionKey', 'routingNumber', 'accountNumber'];
foreach ($maskAll as $val) {
$string = preg_replace('#' . $val . '>(.+?)</' . $val . '#', $val . '>XXX</' . $val, (string)$string);
}
foreach ($maskFour as $val) {
$start = strpos($string, '<' . $val . '>');
$end = strpos($string, '</' . $val . '>', $start);
$tagLen = strlen($val) + 2;
if ($start !== false && $end > ($start + $tagLen + 4)) {
$string = substr_replace($string, 'XXXX', $start + $tagLen, $end - 4 - ($start + $tagLen));
}
}
return $string;
}
/**
* Convert XML string to array. See \ParadoxLabs\TokenBase\Model\Gateway\Xml
*
* @param string $xml
* @return array
*/
protected function xmlToArray($xml)
{
// Strip bad namespace out before we try to parse it. ...
$xml = str_replace(' xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"', '', $xml);
return parent::xmlToArray($xml);
}
/**
* Turn transaction results and directResponse into a usable object.
*
* @param array $transactionResult
* @return \ParadoxLabs\TokenBase\Model\Gateway\Response
* @throws CommandException
* @throws CommandException
*/
protected function interpretTransaction($transactionResult)
{
/**
* Check for not-found error first. If that error makes it here, that means they attempted to use a stored card
* that could not be found (deleted, or account change, or such). Any way about it the card is no longer valid.
*/
if ($transactionResult['messages']['resultCode'] !== 'Ok') {
$errorCode = $transactionResult['messages']['message']['code'];
$errorText = $transactionResult['messages']['message']['text'];
if ($errorCode === 'E00040'
&& $errorText === 'Customer Profile ID or Customer Payment Profile ID not found.'
) {
if ($this->hasData('card')) {
/**
* We know the card is not valid, so hide and get rid of it. Except we're in the middle
* of a transaction... so any change will just be rolled back. Save it for a little later.
* @see \ParadoxLabs\TokenBase\Observer\CardLoadProcessDeleteQueueObserver::execute()
*/
$this->registry->unregister('queue_card_deletion');
$this->registry->register('queue_card_deletion', $this->getData('card'));
}
$this->helper->log(
$this->code,
sprintf("API error: %s: %s\n%s", $errorCode, $errorText, $this->log)
);
throw new CommandException(
__('Sorry, we were unable to find your payment record. '
. 'Please re-enter your payment info and try again.')
);
}
if ($errorCode === 'E00040' && $errorText === 'Customer Shipping Address ID not found.') {
/**
* Invalid shipping ID. We should retry, but that's hard to do with this architecture.
* In a transaction, no events, ...
*/
$this->helper->log(
$this->code,
sprintf("API error: %s: %s\n%s", $errorCode, $errorText, $this->log)
);
throw new CommandException(
__(sprintf('Authorize.Net CIM Gateway: %s Please contact support, or delete your '
. 'shipping address in My Account and try again.', $errorText))
);
}
}
/**
* Turn response into a consistent data object, as best we can
*/
if (isset($transactionResult['directResponse'])) {
$data = $this->getDataFromDirectResponse($transactionResult['directResponse']);
} elseif (isset($transactionResult['transactionResponse'])) {
$data = $this->getDataFromTransactionResponse($transactionResult['transactionResponse']);
} else {
$this->helper->log(
$this->code,
sprintf("Authorize.Net CIM Gateway: Transaction failed; no response.\n%s", $this->log)
);
throw new CommandException(
__('Authorize.Net CIM Gateway: Transaction failed; no response. '
. 'Please re-enter your payment info and try again.')
);
}
/** @var \ParadoxLabs\TokenBase\Model\Gateway\Response $response */
$response = $this->responseFactory->create();
$response->setData($data);
if ((int)$response->getResponseCode() === 4) {
$response->setIsFraud(true);
}
/**
* Response 54 is 'can't refund; txn has not settled.' 16 is 'cannot find txn' (expired).
* Allow those through; they're handled elsewhere.
*/
if (in_array((int)$response->getResponseReasonCode(), [16, 54], true)) {
return $response;
}
/**
* Fail if:
* Error result
* OR error/decline response code
* OR no transID on a charge txn
*/
if ($transactionResult['messages']['resultCode'] !== 'Ok'
|| (int)$response->getResponseCode() === 2
|| (int)$response->getResponseCode() === 3
|| (empty($response->getTransactionId()) && !in_array($response->getTransactionType(), ['credit', 'void']))
) {
$response->setIsError(true);
$this->helper->log(
$this->code,
sprintf(
"Transaction error: %s\n%s\n%s",
$response->getResponseReasonText(),
json_encode($response->getData()),
$this->log
)
);
if ($response->getTransactionId() === '0' && $response->getAuthCode() === '000000') {
throw new CommandException(
__('Transaction failed. Please disable test mode in Authorize.Net.')
);
}
throw new CommandException(
__('Authorize.Net CIM Gateway: Transaction failed. ' . $response->getResponseReasonText())
);
}
return $response;
}
/**
* Set billing address params from Address object
*
* @param \Magento\Customer\Api\Data\AddressInterface|\Magento\Sales\Api\Data\OrderAddressInterface $address
* @return $this
* @throws \Magento\Payment\Gateway\Command\CommandException
*/
public function setBillTo($address)
{
if ($address instanceof \Magento\Customer\Api\Data\AddressInterface) {
$region = $address->getRegion()->getRegionCode() ?: $address->getRegion()->getRegion();
} elseif ($address instanceof \Magento\Sales\Api\Data\OrderAddressInterface) {
$region = $address->getRegionCode() ?: $address->getRegion();
} else {
return $this;
}
$this->setParameter('billToFirstName', $address->getFirstname());
$this->setParameter('billToLastName', $address->getLastname());
$this->setParameter('billToCompany', $address->getCompany());
$this->setParameter('billToAddress', implode(', ', $address->getStreet() ?: []));
$this->setParameter('billToCity', $address->getCity());
$this->setParameter('billToState', $region);
$this->setParameter('billToZip', $address->getPostcode());
$this->setParameter('billToCountry', $address->getCountryId());
$this->setParameter('billToPhoneNumber', $address->getTelephone());
$this->setParameter('billToFaxNumber', $address->getFax());
return $this;
}
/**
* Set shipping address params from Address object
*
* @param \Magento\Customer\Api\Data\AddressInterface $address
* @return $this
*/
public function setShipTo(\Magento\Customer\Api\Data\AddressInterface $address)
{
$region = $address->getRegion()->getRegionCode() ?: $address->getRegion()->getRegion();
$this->setParameter('shipToFirstName', $address->getFirstname());
$this->setParameter('shipToLastName', $address->getLastname());
$this->setParameter('shipToCompany', $address->getCompany());
$this->setParameter('shipToAddress', implode(', ', $address->getStreet() ?: []));
$this->setParameter('shipToCity', $address->getCity());
$this->setParameter('shipToState', $region);
$this->setParameter('shipToZip', $address->getPostcode());
$this->setParameter('shipToCountry', $address->getCountryId());
return $this;
}
/**
* These should be implemented by the child gateway.
*
* @param \ParadoxLabs\TokenBase\Api\Data\CardInterface $card
* @return $this
*/
public function setCard(\ParadoxLabs\TokenBase\Api\Data\CardInterface $card)
{
$this->setParameter('email', $card->getCustomerEmail());
$this->setParameter('merchantCustomerId', $card->getCustomerId());
$this->setParameter('customerProfileId', $card->getProfileId());
$this->setParameter('customerPaymentProfileId', $card->getPaymentId());
$this->setParameter('customerIp', $card->getCustomerIp());
parent::setCard($card);
return $this;
}
/**
* Run an auth transaction for $amount with the given payment info
*
* @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount
* @return \ParadoxLabs\TokenBase\Model\Gateway\Response
*/
public function authorize(\Magento\Payment\Model\InfoInterface $payment, $amount)
{
/** @var \Magento\Sales\Model\Order\Payment $payment */
/**
* Short circuit if prior hosted transaction
*/
if (in_array($payment->getAdditionalInformation('transaction_status'), static::AUTHORIZED_STATUSES, true)
&& !empty($payment->getAdditionalInformation('transaction_id'))
&& $this->getHaveAuthorized() !== true) {
/** @var \ParadoxLabs\TokenBase\Model\Gateway\Response $response */
$response = $this->responseFactory->create();
$response->setData($payment->getAdditionalInformation());
if ((int)$response->getResponseCode() === 4) {
$response->setIsFraud(true);
}
return $response;
}
$this->setParameter('transactionType', 'authOnlyTransaction');
$this->setParameter('amount', $amount);
$this->setParameter('invoiceNumber', $payment->getOrder()->getIncrementId());
if ($this->getHaveAuthorized() !== true) {
if ($payment->getOrder()->getBaseTaxAmount()) {
$this->setParameter('taxAmount', $payment->getOrder()->getBaseTaxAmount());
}
if ($payment->getBaseShippingAmount()) {
$this->setParameter('shipAmount', $payment->getBaseShippingAmount());
}
} else {
$this->setParameter('subsequentAuthReason', 'reauthorization');
}
if ($payment->hasData('cc_cid') && !empty($payment->getData('cc_cid'))) {
$this->setParameter('cardCode', $payment->getData('cc_cid'));
}
if ($this->getCard()->getLastUse() === null
&& $payment->getMethodInstance() !== null
&& $payment->getMethodInstance()->getConfigData('validation_mode') !== 'liveMode') {
$this->setParameter('isFirstSubsequentAuth', 'true');
}
if ($this->helper->getIsFrontend()) {
$this->setParameter('isStoredCredentials', 'true');
} else {
$this->setParameter('isSubsequentAuth', 'true');
}
if ((int)$payment->getAdditionalInformation('is_subscription_generated') === 1) {
$this->setParameter('recurringBilling', 'true');
}
$result = $this->createTransaction();
return $this->interpretTransaction($result);
}
/**
* Run a capture transaction for $amount with the given payment info
*
* @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount
* @param string $transactionId
* @return \ParadoxLabs\TokenBase\Model\Gateway\Response
*/
public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount, $transactionId = null)
{
/** @var \Magento\Sales\Model\Order\Payment $payment */
/**
* Adjust transaction flow if there was a prior hosted transaction
*/
if (in_array($payment->getAdditionalInformation('transaction_status'), static::AUTHORIZED_STATUSES, true)
&& !empty($payment->getAdditionalInformation('transaction_id'))
&& $this->getHaveAuthorized() !== true) {
$transactionId = $payment->getAdditionalInformation('transaction_id');
$this->setHaveAuthorized(true);
}
if ($this->getHaveAuthorized()) {
$this->setParameter('transactionType', 'priorAuthCaptureTransaction');
if ($transactionId !== null) {
$this->setParameter('transId', $transactionId);
} else {
$this->setParameter('transId', $payment->getData('transaction_id'));
}
}
if ($this->getHaveAuthorized() === false || empty($this->getTransactionId())) {
$this->setParameter('transactionType', 'authCaptureTransaction');
if ($this->helper->getIsFrontend()) {
$this->setParameter('isStoredCredentials', 'true');
} else {
$this->setParameter('isSubsequentAuth', 'true');
}
if ((int)$payment->getAdditionalInformation('is_subscription_generated') === 1) {
$this->setParameter('recurringBilling', 'true');
}
}
$this->setParameter('amount', $amount);
$this->setParameter('invoiceNumber', $payment->getOrder()->getIncrementId());
$this->captureGetAmountInfo($payment);
if ($payment->hasData('cc_cid') && !empty($payment->getData('cc_cid'))) {
$this->setParameter('cardCode', $payment->getData('cc_cid'));
}
$result = $this->createTransaction();
$response = $this->interpretTransaction($result);
/**
* Check for and handle 'transaction not found' error (expired authorization).
*/
if ((int)$response->getResponseReasonCode() === 16 && !empty($this->getParameter('transId'))) {
$this->helper->log(
$this->code,
sprintf("Transaction not found. Attempting to recapture.\n%s", json_encode($response->getData()))
);
$this->setParameter('transId', null)
->setHaveAuthorized(false)
->setCard($this->getData('card'));
$payment->setAdditionalInformation('transaction_id', null);
$response = $this->capture($payment, $amount, '');
}
return $response;
}
/**
* Run a refund transaction for $amount with the given payment info
*
* @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount
* @param string $transactionId
* @return \ParadoxLabs\TokenBase\Model\Gateway\Response
* @throws CommandException
*/
public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount, $transactionId = null)
{
/** @var \Magento\Sales\Model\Order\Payment $payment */
$this->setParameter('transactionType', 'refundTransaction');
$this->setParameter('amount', $amount);
$this->setParameter('invoiceNumber', $payment->getOrder()->getIncrementId());
// Send CC last4 for verification of CC refunds
if ($payment->getMethod() === ConfigProvider::CODE) {
$this->setParameter('cardNumber', $payment->getCcLast4());
}
if ($payment->getCreditmemo() instanceof \Magento\Sales\Api\Data\CreditmemoInterface) {
if ($payment->getCreditmemo()->getBaseTaxAmount()) {
$this->setParameter('taxAmount', $payment->getCreditmemo()->getBaseTaxAmount());
}
if ($payment->getCreditmemo()->getBaseShippingAmount()) {
$this->setParameter('shipAmount', $payment->getCreditmemo()->getBaseShippingAmount());
}
/**
* Add billTo, in case the Authorize.Net payment form requires it.
*/
$billingAddress = $payment->getCreditmemo()->getBillingAddress();
if ($billingAddress instanceof \Magento\Sales\Api\Data\OrderAddressInterface) {
$this->setBillTo($billingAddress);
}
}
if ($transactionId !== null) {
$this->setParameter('transId', $transactionId);
} elseif (!empty($payment->getTransactionId())) {
$this->setParameter('transId', $payment->getTransactionId());
}
$result = $this->createTransaction();
$response = $this->interpretTransaction($result);
/**
* Check for 'transaction unsettled' error.
*/
if ((int)$response->getResponseReasonCode() === 54) {
/**
* Is this a full refund? If so, just void it. Nobody will see the difference.
*/
if ($payment->getCreditmemo() instanceof \Magento\Sales\Api\Data\CreditmemoInterface
&& $amount == $payment->getCreditmemo()->getInvoice()->getBaseGrandTotal()) {
$transactionId = $this->getParameter('transId');
return $this->clearParameters()
->setCard($this->getData('card'))
->void($payment, $transactionId);
}
$response->setIsError(true);
$this->helper->log(
$this->code,
sprintf(
"Transaction error: %s\n%s\n%s",
$response->getResponseReasonText(),
json_encode($response->getData()),
$this->log
)
);
throw new CommandException(
__('Authorize.Net CIM Gateway: Transaction failed. ' . $response->getResponseReasonText())
);
}
return $response;
}
/**
* Run a void transaction for the given payment info
*
* @param \Magento\Payment\Model\InfoInterface $payment
* @param string $transactionId
* @return \ParadoxLabs\TokenBase\Model\Gateway\Response
*/
public function void(\Magento\Payment\Model\InfoInterface $payment, $transactionId = null)
{
/** @var \Magento\Sales\Model\Order\Payment $payment */
$this->setParameter('transactionType', 'voidTransaction');
if ($transactionId !== null) {
$this->setParameter('transId', $transactionId);
} elseif (!empty($payment->getTransactionId())) {
$this->setParameter('transId', $payment->getTransactionId());
}
$result = $this->createTransaction();
return $this->interpretTransaction($result);
}
/**
* Approve a held transaction
*
* @param \Magento\Payment\Model\InfoInterface $payment
* @param string $transactionId
* @return \ParadoxLabs\TokenBase\Model\Gateway\Response
*/
public function acceptPayment(\Magento\Payment\Model\InfoInterface $payment, $transactionId = null)
{
/** @var \Magento\Sales\Model\Order\Payment $payment */
$this->setParameter('transactionType', 'updateHeldTransaction');
$this->setParameter('updateAction', 'approve');
if ($transactionId !== null) {
$this->setParameter('transId', $transactionId);
} elseif (!empty($payment->getLastTransId())) {
$this->setParameter('transId', $payment->getLastTransId());
}
$result = $this->updateHeldTransaction();
$resultData = $this->getDataFromTransactionResponse($result['transactionResponse']);
/** @var \ParadoxLabs\TokenBase\Model\Gateway\Response $response */
$response = $this->responseFactory->create();
$response->setData($resultData + ['is_approved' => false, 'is_denied' => false]);
if ((int)$response->getResponseCode() !== 1 || $result['messages']['resultCode'] !== 'Ok') {
$this->helper->log(
$this->code,
sprintf(
"Transaction error: %s\n%s\n%s",
$response->getResponseReasonText(),
json_encode($response->getData()),
$this->log
)
);
throw new CommandException(
__('Authorize.Net CIM Gateway: Transaction failed. ' . $response->getResponseReasonText())
);
}
$response->setData('is_approved', true);
return $response;
}
/**
* Deny a held transaction
*
* @param \Magento\Payment\Model\InfoInterface $payment
* @param string $transactionId
* @return \ParadoxLabs\TokenBase\Model\Gateway\Response
*/
public function denyPayment(\Magento\Payment\Model\InfoInterface $payment, $transactionId = null)
{
/** @var \Magento\Sales\Model\Order\Payment $payment */
$this->setParameter('transactionType', 'updateHeldTransaction');
$this->setParameter('updateAction', 'decline');
if ($transactionId !== null) {
$this->setParameter('transId', $transactionId);
} elseif (!empty($payment->getLastTransId())) {
$this->setParameter('transId', $payment->getLastTransId());
}
$result = $this->updateHeldTransaction();
$resultData = $this->getDataFromTransactionResponse($result['transactionResponse']);
/** @var \ParadoxLabs\TokenBase\Model\Gateway\Response $response */
$response = $this->responseFactory->create();
$response->setData($resultData + ['is_approved' => false, 'is_denied' => false]);
if ((int)$response->getResponseCode() !== 2 || $result['messages']['resultCode'] !== 'Ok') {
$this->helper->log(
$this->code,
sprintf(
"Transaction error: %s\n%s\n%s",
$response->getResponseReasonText(),
json_encode($response->getData()),
$this->log
)
);
throw new CommandException(
__('Authorize.Net CIM Gateway: Transaction failed. ' . $response->getResponseReasonText())
);
}
$response->setData('is_denied', true);
return $response;
}
/**
* Fetch a transaction status update
*
* @param \Magento\Payment\Model\InfoInterface $payment
* @param string $transactionId
* @return \ParadoxLabs\TokenBase\Model\Gateway\Response
*/
public function fraudUpdate(\Magento\Payment\Model\InfoInterface $payment, $transactionId)
{
$this->setParameter('transId', $transactionId);
$result = $this->getTransactionDetails();
foreach ($result as $k => $v) {
if (is_array($v)) {
foreach ($v as $l => $u) {
if (is_array($u)) {
$u = json_encode($u);
}
$result[ $k . '_' . $l ] = $u;