/
Payment.php
1648 lines (1516 loc) · 62.9 KB
/
Payment.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
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Magento
* @package Magento_Sales
* @copyright Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Order payment information
*
* @method \Magento\Sales\Model\Resource\Order\Payment _getResource()
* @method \Magento\Sales\Model\Resource\Order\Payment getResource()
* @method int getParentId()
* @method \Magento\Sales\Model\Order\Payment setParentId(int $value)
* @method float getBaseShippingCaptured()
* @method \Magento\Sales\Model\Order\Payment setBaseShippingCaptured(float $value)
* @method float getShippingCaptured()
* @method \Magento\Sales\Model\Order\Payment setShippingCaptured(float $value)
* @method float getAmountRefunded()
* @method \Magento\Sales\Model\Order\Payment setAmountRefunded(float $value)
* @method float getBaseAmountPaid()
* @method \Magento\Sales\Model\Order\Payment setBaseAmountPaid(float $value)
* @method float getAmountCanceled()
* @method \Magento\Sales\Model\Order\Payment setAmountCanceled(float $value)
* @method float getBaseAmountAuthorized()
* @method \Magento\Sales\Model\Order\Payment setBaseAmountAuthorized(float $value)
* @method float getBaseAmountPaidOnline()
* @method \Magento\Sales\Model\Order\Payment setBaseAmountPaidOnline(float $value)
* @method float getBaseAmountRefundedOnline()
* @method \Magento\Sales\Model\Order\Payment setBaseAmountRefundedOnline(float $value)
* @method float getBaseShippingAmount()
* @method \Magento\Sales\Model\Order\Payment setBaseShippingAmount(float $value)
* @method float getShippingAmount()
* @method \Magento\Sales\Model\Order\Payment setShippingAmount(float $value)
* @method float getAmountPaid()
* @method \Magento\Sales\Model\Order\Payment setAmountPaid(float $value)
* @method float getAmountAuthorized()
* @method \Magento\Sales\Model\Order\Payment setAmountAuthorized(float $value)
* @method float getBaseAmountOrdered()
* @method \Magento\Sales\Model\Order\Payment setBaseAmountOrdered(float $value)
* @method float getBaseShippingRefunded()
* @method \Magento\Sales\Model\Order\Payment setBaseShippingRefunded(float $value)
* @method float getShippingRefunded()
* @method \Magento\Sales\Model\Order\Payment setShippingRefunded(float $value)
* @method float getBaseAmountRefunded()
* @method \Magento\Sales\Model\Order\Payment setBaseAmountRefunded(float $value)
* @method float getAmountOrdered()
* @method \Magento\Sales\Model\Order\Payment setAmountOrdered(float $value)
* @method float getBaseAmountCanceled()
* @method \Magento\Sales\Model\Order\Payment setBaseAmountCanceled(float $value)
* @method int getQuotePaymentId()
* @method \Magento\Sales\Model\Order\Payment setQuotePaymentId(int $value)
* @method string getAdditionalData()
* @method \Magento\Sales\Model\Order\Payment setAdditionalData(string $value)
* @method string getCcExpMonth()
* @method \Magento\Sales\Model\Order\Payment setCcExpMonth(string $value)
* @method string getCcSsStartYear()
* @method \Magento\Sales\Model\Order\Payment setCcSsStartYear(string $value)
* @method string getEcheckBankName()
* @method \Magento\Sales\Model\Order\Payment setEcheckBankName(string $value)
* @method string getMethod()
* @method \Magento\Sales\Model\Order\Payment setMethod(string $value)
* @method string getCcDebugRequestBody()
* @method \Magento\Sales\Model\Order\Payment setCcDebugRequestBody(string $value)
* @method string getCcSecureVerify()
* @method \Magento\Sales\Model\Order\Payment setCcSecureVerify(string $value)
* @method string getProtectionEligibility()
* @method \Magento\Sales\Model\Order\Payment setProtectionEligibility(string $value)
* @method string getCcApproval()
* @method \Magento\Sales\Model\Order\Payment setCcApproval(string $value)
* @method string getCcLast4()
* @method \Magento\Sales\Model\Order\Payment setCcLast4(string $value)
* @method string getCcStatusDescription()
* @method \Magento\Sales\Model\Order\Payment setCcStatusDescription(string $value)
* @method string getEcheckType()
* @method \Magento\Sales\Model\Order\Payment setEcheckType(string $value)
* @method string getCcDebugResponseSerialized()
* @method \Magento\Sales\Model\Order\Payment setCcDebugResponseSerialized(string $value)
* @method string getCcSsStartMonth()
* @method \Magento\Sales\Model\Order\Payment setCcSsStartMonth(string $value)
* @method string getEcheckAccountType()
* @method \Magento\Sales\Model\Order\Payment setEcheckAccountType(string $value)
* @method string getLastTransId()
* @method \Magento\Sales\Model\Order\Payment setLastTransId(string $value)
* @method string getCcCidStatus()
* @method \Magento\Sales\Model\Order\Payment setCcCidStatus(string $value)
* @method string getCcOwner()
* @method \Magento\Sales\Model\Order\Payment setCcOwner(string $value)
* @method string getCcType()
* @method \Magento\Sales\Model\Order\Payment setCcType(string $value)
* @method string getPoNumber()
* @method \Magento\Sales\Model\Order\Payment setPoNumber(string $value)
* @method string getCcExpYear()
* @method \Magento\Sales\Model\Order\Payment setCcExpYear(string $value)
* @method string getCcStatus()
* @method \Magento\Sales\Model\Order\Payment setCcStatus(string $value)
* @method string getEcheckRoutingNumber()
* @method \Magento\Sales\Model\Order\Payment setEcheckRoutingNumber(string $value)
* @method string getAccountStatus()
* @method \Magento\Sales\Model\Order\Payment setAccountStatus(string $value)
* @method string getAnetTransMethod()
* @method \Magento\Sales\Model\Order\Payment setAnetTransMethod(string $value)
* @method string getCcDebugResponseBody()
* @method \Magento\Sales\Model\Order\Payment setCcDebugResponseBody(string $value)
* @method string getCcSsIssue()
* @method \Magento\Sales\Model\Order\Payment setCcSsIssue(string $value)
* @method string getEcheckAccountName()
* @method \Magento\Sales\Model\Order\Payment setEcheckAccountName(string $value)
* @method string getCcAvsStatus()
* @method \Magento\Sales\Model\Order\Payment setCcAvsStatus(string $value)
* @method string getCcNumberEnc()
* @method \Magento\Sales\Model\Order\Payment setCcNumberEnc(string $value)
* @method string getCcTransId()
* @method \Magento\Sales\Model\Order\Payment setCcTransId(string $value)
* @method string getAddressStatus()
* @method \Magento\Sales\Model\Order\Payment setAddressStatus(string $value)
*/
namespace Magento\Sales\Model\Order;
class Payment extends \Magento\Payment\Model\Info
{
/**
* Actions for payment when it triggered review state
*
* @var string
*/
const REVIEW_ACTION_ACCEPT = 'accept';
const REVIEW_ACTION_DENY = 'deny';
const REVIEW_ACTION_UPDATE = 'update';
/**
* Order model object
*
* @var \Magento\Sales\Model\Order
*/
protected $_order;
/**
* Billing agreement instance that may be created during payment processing
*
* @var \Magento\Sales\Model\Billing\Agreement
*/
protected $_billingAgreement = null;
/**
* Whether can void
* @var string
*/
protected $_canVoidLookup = null;
/**
* Transactions registry to spare resource calls
* array(txn_id => sales/order_payment_transaction)
* @var array
*/
protected $_transactionsLookup = array();
protected $_eventPrefix = 'sales_order_payment';
protected $_eventObject = 'payment';
/**
* Transaction addditional information container
*
* @var array
*/
protected $_transactionAdditionalInfo = array();
/**
* Core event manager proxy
*
* @var \Magento\Core\Model\Event\Manager
*/
protected $_eventManager = null;
/**
* @var \Magento\Sales\Model\Service\Order
*/
protected $_serviceOrderFactory;
/**
* @var \Magento\Sales\Model\Order\Payment\TransactionFactory
*/
protected $_transactionFactory;
/**
* @var \Magento\Sales\Model\Resource\Order\Payment\Transaction\CollectionFactory
*/
protected $_transactionCollFactory;
/**
* @var \Magento\Sales\Model\Billing\AgreementFactory
*/
protected $_agreementFactory;
/**
* @var \Magento\Core\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @param \Magento\Core\Model\Event\Manager $eventManager
* @param \Magento\Core\Helper\Data $coreData
* @param \Magento\Payment\Helper\Data $paymentData
* @param \Magento\Core\Model\Context $context
* @param \Magento\Core\Model\Registry $registry
* @param \Magento\Sales\Model\Service\Order $serviceOrderFactory
* @param \Magento\Sales\Model\Order\Payment\TransactionFactory $transactionFactory
* @param \Magento\Sales\Model\Resource\Order\Payment\Transaction\CollectionFactory $transactionCollFactory
* @param \Magento\Sales\Model\Billing\AgreementFactory $agreementFactory
* @param \Magento\Core\Model\StoreManagerInterface $storeManager
* @param \Magento\Core\Model\Resource\AbstractResource $resource
* @param \Magento\Data\Collection\Db $resourceCollection
* @param array $data
*/
public function __construct(
\Magento\Core\Model\Event\Manager $eventManager,
\Magento\Core\Helper\Data $coreData,
\Magento\Payment\Helper\Data $paymentData,
\Magento\Core\Model\Context $context,
\Magento\Core\Model\Registry $registry,
\Magento\Sales\Model\Service\Order $serviceOrderFactory,
\Magento\Sales\Model\Order\Payment\TransactionFactory $transactionFactory,
\Magento\Sales\Model\Resource\Order\Payment\Transaction\CollectionFactory $transactionCollFactory,
\Magento\Sales\Model\Billing\AgreementFactory $agreementFactory,
\Magento\Core\Model\StoreManagerInterface $storeManager,
\Magento\Core\Model\Resource\AbstractResource $resource = null,
\Magento\Data\Collection\Db $resourceCollection = null,
array $data = array()
) {
$this->_eventManager = $eventManager;
$this->_serviceOrderFactory = $serviceOrderFactory;
$this->_transactionFactory = $transactionFactory;
$this->_transactionCollFactory = $transactionCollFactory;
$this->_agreementFactory = $agreementFactory;
$this->_storeManager = $storeManager;
parent::__construct($coreData, $paymentData, $context, $registry, $resource, $resourceCollection, $data);
}
/**
* Initialize resource model
*/
protected function _construct()
{
$this->_init('Magento\Sales\Model\Resource\Order\Payment');
}
/**
* Declare order model object
*
* @param \Magento\Sales\Model\Order $order
* @return \Magento\Sales\Model\Order\Payment
*/
public function setOrder(\Magento\Sales\Model\Order $order)
{
$this->_order = $order;
return $this;
}
/**
* Retrieve order model object
*
* @return \Magento\Sales\Model\Order
*/
public function getOrder()
{
return $this->_order;
}
/**
* Check order payment capture action availability
*
* @return bool
*/
public function canCapture()
{
if (!$this->getMethodInstance()->canCapture()) {
return false;
}
// Check Authorization transaction state
$authTransaction = $this->getAuthorizationTransaction();
if ($authTransaction && $authTransaction->getIsClosed()) {
$orderTransaction = $this->_lookupTransaction(null, \Magento\Sales\Model\Order\Payment\Transaction::TYPE_ORDER);
if (!$orderTransaction) {
return false;
}
}
return true;
}
/**
* @return bool
*/
public function canRefund()
{
return $this->getMethodInstance()->canRefund();
}
/**
* @return bool
*/
public function canRefundPartialPerInvoice()
{
return $this->getMethodInstance()->canRefundPartialPerInvoice();
}
/**
* @return bool
*/
public function canCapturePartial()
{
return $this->getMethodInstance()->canCapturePartial();
}
/**
* Authorize or authorize and capture payment on gateway, if applicable
* This method is supposed to be called only when order is placed
*
* @return \Magento\Sales\Model\Order\Payment
*/
public function place()
{
$this->_eventManager->dispatch('sales_order_payment_place_start', array('payment' => $this));
$order = $this->getOrder();
$this->setAmountOrdered($order->getTotalDue());
$this->setBaseAmountOrdered($order->getBaseTotalDue());
$this->setShippingAmount($order->getShippingAmount());
$this->setBaseShippingAmount($order->getBaseShippingAmount());
$methodInstance = $this->getMethodInstance();
$methodInstance->setStore($order->getStoreId());
$orderState = \Magento\Sales\Model\Order::STATE_NEW;
$stateObject = new \Magento\Object();
/**
* Do order payment validation on payment method level
*/
$methodInstance->validate();
$action = $methodInstance->getConfigPaymentAction();
if ($action) {
if ($methodInstance->isInitializeNeeded()) {
/**
* For method initialization we have to use original config value for payment action
*/
$methodInstance->initialize($methodInstance->getConfigData('payment_action'), $stateObject);
} else {
$orderState = \Magento\Sales\Model\Order::STATE_PROCESSING;
switch ($action) {
case \Magento\Payment\Model\Method\AbstractMethod::ACTION_ORDER:
$this->_order($order->getBaseTotalDue());
break;
case \Magento\Payment\Model\Method\AbstractMethod::ACTION_AUTHORIZE:
$this->_authorize(true, $order->getBaseTotalDue()); // base amount will be set inside
$this->setAmountAuthorized($order->getTotalDue());
break;
case \Magento\Payment\Model\Method\AbstractMethod::ACTION_AUTHORIZE_CAPTURE:
$this->setAmountAuthorized($order->getTotalDue());
$this->setBaseAmountAuthorized($order->getBaseTotalDue());
$this->capture(null);
break;
default:
break;
}
}
}
$this->_createBillingAgreement();
$orderIsNotified = null;
if ($stateObject->getState() && $stateObject->getStatus()) {
$orderState = $stateObject->getState();
$orderStatus = $stateObject->getStatus();
$orderIsNotified = $stateObject->getIsNotified();
} else {
$orderStatus = $methodInstance->getConfigData('order_status');
if (!$orderStatus) {
$orderStatus = $order->getConfig()->getStateDefaultStatus($orderState);
}
}
$isCustomerNotified = (null !== $orderIsNotified) ? $orderIsNotified : $order->getCustomerNoteNotify();
$message = $order->getCustomerNote();
// add message if order was put into review during authorization or capture
if ($order->getState() == \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW) {
if ($message) {
$order->addStatusToHistory($order->getStatus(), $message, $isCustomerNotified);
}
}
// add message to history if order state already declared
elseif ($order->getState() && ($orderStatus !== $order->getStatus() || $message)) {
$order->setState($orderState, $orderStatus, $message, $isCustomerNotified);
}
// set order state
elseif (($order->getState() != $orderState) || ($order->getStatus() != $orderStatus) || $message) {
$order->setState($orderState, $orderStatus, $message, $isCustomerNotified);
}
$this->_eventManager->dispatch('sales_order_payment_place_end', array('payment' => $this));
return $this;
}
/**
* Capture the payment online
* Requires an invoice. If there is no invoice specified, will automatically prepare an invoice for order
* Updates transactions hierarchy, if required
* Updates payment totals, updates order status and adds proper comments
*
* TODO: eliminate logic duplication with registerCaptureNotification()
*
* @param null|\Magento\Sales\Model\Order\Invoice $invoice
* @throws \Magento\Core\Exception
* @return \Magento\Sales\Model\Order\Payment
*/
public function capture($invoice)
{
if (is_null($invoice)) {
$invoice = $this->_invoice();
$this->setCreatedInvoice($invoice);
return $this; // @see \Magento\Sales\Model\Order\Invoice::capture()
}
$amountToCapture = $this->_formatAmount($invoice->getBaseGrandTotal());
$order = $this->getOrder();
// prepare parent transaction and its amount
$paidWorkaround = 0;
if (!$invoice->wasPayCalled()) {
$paidWorkaround = (float)$amountToCapture;
}
$this->_isCaptureFinal($paidWorkaround);
$this->_generateTransactionId(
\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE,
$this->getAuthorizationTransaction()
);
$this->_eventManager->dispatch('sales_order_payment_capture', array('payment' => $this, 'invoice' => $invoice));
/**
* Fetch an update about existing transaction. It can determine whether the transaction can be paid
* Capture attempt will happen only when invoice is not yet paid and the transaction can be paid
*/
if ($invoice->getTransactionId()) {
$this->getMethodInstance()
->setStore($order->getStoreId())
->fetchTransactionInfo($this, $invoice->getTransactionId());
}
$status = true;
if (!$invoice->getIsPaid() && !$this->getIsTransactionPending()) {
// attempt to capture: this can trigger "is_transaction_pending"
$this->getMethodInstance()->setStore($order->getStoreId())->capture($this, $amountToCapture);
$transaction = $this->_addTransaction(
\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE,
$invoice,
true
);
if ($this->getIsTransactionPending()) {
$message = __('An amount of %1 will be captured after being approved at the payment gateway.', $this->_formatPrice($amountToCapture));
$state = \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW;
if ($this->getIsFraudDetected()) {
$status = \Magento\Sales\Model\Order::STATUS_FRAUD;
}
$invoice->setIsPaid(false);
} else { // normal online capture: invoice is marked as "paid"
$message = __('Captured amount of %1 online', $this->_formatPrice($amountToCapture));
$state = \Magento\Sales\Model\Order::STATE_PROCESSING;
$invoice->setIsPaid(true);
$this->_updateTotals(array('base_amount_paid_online' => $amountToCapture));
}
if ($order->isNominal()) {
$message = $this->_prependMessage(__('An order with subscription items was registered.'));
} else {
$message = $this->_prependMessage($message);
$message = $this->_appendTransactionToMessage($transaction, $message);
}
$order->setState($state, $status, $message);
$this->getMethodInstance()->processInvoice($invoice, $this);
return $this;
}
throw new \Magento\Core\Exception(
__('The transaction "%1" cannot be captured yet.', $invoice->getTransactionId())
);
}
/**
* Process a capture notification from a payment gateway for specified amount
* Creates an invoice automatically if the amount covers the order base grand total completely
* Updates transactions hierarchy, if required
* Prevents transaction double processing
* Updates payment totals, updates order status and adds proper comments
*
* TODO: eliminate logic duplication with capture()
*
* @param float $amount
* @return \Magento\Sales\Model\Order\Payment
*/
public function registerCaptureNotification($amount)
{
$this->_generateTransactionId(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE,
$this->getAuthorizationTransaction()
);
$order = $this->getOrder();
$amount = (float)$amount;
$invoice = $this->_getInvoiceForTransactionId($this->getTransactionId());
// register new capture
if (!$invoice) {
if ($this->_isSameCurrency() && $this->_isCaptureFinal($amount)) {
$invoice = $order->prepareInvoice()->register();
$order->addRelatedObject($invoice);
$this->setCreatedInvoice($invoice);
} else {
$this->setIsFraudDetected(true);
$this->_updateTotals(array('base_amount_paid_online' => $amount));
}
}
$status = true;
if ($this->getIsTransactionPending()) {
$message = __('An amount of %1 will be captured after being approved at the payment gateway.', $this->_formatPrice($amount));
$state = \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW;
if ($this->getIsFraudDetected()) {
$message = __('Order is suspended as its capture amount %1 is suspected to be fraudulent.', $this->_formatPrice($amount));
$status = \Magento\Sales\Model\Order::STATUS_FRAUD;
}
} else {
$message = __('Registered notification about captured amount of %1.', $this->_formatPrice($amount));
$state = \Magento\Sales\Model\Order::STATE_PROCESSING;
if ($this->getIsFraudDetected()) {
$state = \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW;
$message = __('Order is suspended as its capture amount %1 is suspected to be fraudulent.', $this->_formatPrice($amount));
$status = \Magento\Sales\Model\Order::STATUS_FRAUD;
}
// register capture for an existing invoice
if ($invoice && \Magento\Sales\Model\Order\Invoice::STATE_OPEN == $invoice->getState()) {
$invoice->pay();
$this->_updateTotals(array('base_amount_paid_online' => $amount));
$order->addRelatedObject($invoice);
}
}
$transaction = $this->_addTransaction(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE, $invoice, true);
$message = $this->_prependMessage($message);
$message = $this->_appendTransactionToMessage($transaction, $message);
$order->setState($state, $status, $message);
return $this;
}
/**
* Process authorization notification
*
* @see self::_authorize()
* @param float $amount
* @return \Magento\Sales\Model\Order\Payment
*/
public function registerAuthorizationNotification($amount)
{
return ($this->_isTransactionExists()) ? $this : $this->_authorize(false, $amount);
}
/**
* Register payment fact: update self totals from the invoice
*
* @param \Magento\Sales\Model\Order\Invoice $invoice
* @return \Magento\Sales\Model\Order\Payment
*/
public function pay($invoice)
{
$this->_updateTotals(array(
'amount_paid' => $invoice->getGrandTotal(),
'base_amount_paid' => $invoice->getBaseGrandTotal(),
'shipping_captured' => $invoice->getShippingAmount(),
'base_shipping_captured' => $invoice->getBaseShippingAmount(),
));
$this->_eventManager->dispatch('sales_order_payment_pay', array('payment' => $this, 'invoice' => $invoice));
return $this;
}
/**
* Cancel specified invoice: update self totals from it
*
* @param \Magento\Sales\Model\Order\Invoice $invoice
* @return \Magento\Sales\Model\Order\Payment
*/
public function cancelInvoice($invoice)
{
$this->_updateTotals(array(
'amount_paid' => -1 * $invoice->getGrandTotal(),
'base_amount_paid' => -1 * $invoice->getBaseGrandTotal(),
'shipping_captured' => -1 * $invoice->getShippingAmount(),
'base_shipping_captured' => -1 * $invoice->getBaseShippingAmount(),
));
$this->_eventManager->dispatch('sales_order_payment_cancel_invoice', array('payment' => $this, 'invoice' => $invoice));
return $this;
}
/**
* Create new invoice with maximum qty for invoice for each item
* register this invoice and capture
*
* @return \Magento\Sales\Model\Order\Invoice
*/
protected function _invoice()
{
$invoice = $this->getOrder()->prepareInvoice();
$invoice->register();
if ($this->getMethodInstance()->canCapture()) {
$invoice->capture();
}
$this->getOrder()->addRelatedObject($invoice);
return $invoice;
}
/**
* Check order payment void availability
*
* @param \Magento\Object $document
* @return bool
*/
public function canVoid(\Magento\Object $document)
{
if (null === $this->_canVoidLookup) {
$this->_canVoidLookup = (bool)$this->getMethodInstance()->canVoid($document);
if ($this->_canVoidLookup) {
$authTransaction = $this->getAuthorizationTransaction();
$this->_canVoidLookup = (bool)$authTransaction && !(int)$authTransaction->getIsClosed();
}
}
return $this->_canVoidLookup;
}
/**
* Void payment online
*
* @see self::_void()
* @param \Magento\Object $document
* @return \Magento\Sales\Model\Order\Payment
*/
public function void(\Magento\Object $document)
{
$this->_void(true);
$this->_eventManager->dispatch('sales_order_payment_void', array('payment' => $this, 'invoice' => $document));
return $this;
}
/**
* Process void notification
*
* @see self::_void()
* @param float $amount
* @return \Magento\Sales\Model\Order\Payment
*/
public function registerVoidNotification($amount = null)
{
if (!$this->hasMessage()) {
$this->setMessage(__('Registered a Void notification.'));
}
return $this->_void(false, $amount);
}
/**
* Refund payment online or offline, depending on whether there is invoice set in the creditmemo instance
* Updates transactions hierarchy, if required
* Updates payment totals, updates order status and adds proper comments
*
* @param \Magento\Sales\Model\Order\Creditmemo $creditmemo
* @return \Magento\Sales\Model\Order\Payment
* @throws \Exception|\Magento\Core\Exception
*/
public function refund($creditmemo)
{
$baseAmountToRefund = $this->_formatAmount($creditmemo->getBaseGrandTotal());
$order = $this->getOrder();
$this->_generateTransactionId(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND);
// call refund from gateway if required
$isOnline = false;
$gateway = $this->getMethodInstance();
$invoice = null;
if ($gateway->canRefund() && $creditmemo->getDoTransaction()) {
$this->setCreditmemo($creditmemo);
$invoice = $creditmemo->getInvoice();
if ($invoice) {
$isOnline = true;
$captureTxn = $this->_lookupTransaction($invoice->getTransactionId());
if ($captureTxn) {
$this->setParentTransactionId($captureTxn->getTxnId());
}
$this->setShouldCloseParentTransaction(true); // TODO: implement multiple refunds per capture
try {
$gateway->setStore($this->getOrder()->getStoreId())
->processBeforeRefund($invoice, $this)
->refund($this, $baseAmountToRefund)
->processCreditmemo($creditmemo, $this)
;
} catch (\Magento\Core\Exception $e) {
if (!$captureTxn) {
$e->setMessage(' ' . __('If the invoice was created offline, try creating an offline credit memo.'), true);
}
throw $e;
}
}
}
// update self totals from creditmemo
$this->_updateTotals(array(
'amount_refunded' => $creditmemo->getGrandTotal(),
'base_amount_refunded' => $baseAmountToRefund,
'base_amount_refunded_online' => $isOnline ? $baseAmountToRefund : null,
'shipping_refunded' => $creditmemo->getShippingAmount(),
'base_shipping_refunded' => $creditmemo->getBaseShippingAmount(),
));
// update transactions and order state
$transaction = $this->_addTransaction(
\Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND,
$creditmemo,
$isOnline
);
if ($invoice) {
$message = __('We refunded %1 online.', $this->_formatPrice($baseAmountToRefund));
} else {
$message = $this->hasMessage() ? $this->getMessage()
: __('We refunded %1 offline.', $this->_formatPrice($baseAmountToRefund));
}
$message = $message = $this->_prependMessage($message);
$message = $this->_appendTransactionToMessage($transaction, $message);
$order->setState(\Magento\Sales\Model\Order::STATE_PROCESSING, true, $message);
$this->_eventManager->dispatch('sales_order_payment_refund', array('payment' => $this, 'creditmemo' => $creditmemo));
return $this;
}
/**
* Process payment refund notification
* Updates transactions hierarchy, if required
* Prevents transaction double processing
* Updates payment totals, updates order status and adds proper comments
* TODO: potentially a full capture can be refunded. In this case if there was only one invoice for that transaction
* then we should create a creditmemo from invoice and also refund it offline
* TODO: implement logic of chargebacks reimbursements (via negative amount)
*
* @param float $amount
* @return \Magento\Sales\Model\Order\Payment
*/
public function registerRefundNotification($amount)
{
$notificationAmount = $amount;
$this->_generateTransactionId(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND,
$this->_lookupTransaction($this->getParentTransactionId())
);
if ($this->_isTransactionExists()) {
return $this;
}
$order = $this->getOrder();
$invoice = $this->_getInvoiceForTransactionId($this->getParentTransactionId());
if ($invoice) {
$baseGrandTotal = $invoice->getBaseGrandTotal();
$amountRefundLeft = $baseGrandTotal - $invoice->getBaseTotalRefunded();
} else {
$baseGrandTotal = $order->getBaseGrandTotal();
$amountRefundLeft = $baseGrandTotal - $order->getBaseTotalRefunded();
}
if ($amountRefundLeft < $amount) {
$amount = $amountRefundLeft;
}
if ($amount <= 0) {
$order->addStatusHistoryComment(__('IPN "Refunded". Refund issued by merchant. Registered notification about refunded amount of %1. Transaction ID: "%2"', $this->_formatPrice($notificationAmount), $this->getTransactionId()), false);
return $this;
}
$serviceModel = $this->_serviceOrderFactory->create(array('order' => $order));
if ($invoice) {
if ($invoice->getBaseTotalRefunded() > 0) {
$adjustment = array('adjustment_positive' => $amount);
} else {
$adjustment = array('adjustment_negative' => $baseGrandTotal - $amount);
}
$creditmemo = $serviceModel->prepareInvoiceCreditmemo($invoice, $adjustment);
if ($creditmemo) {
$totalRefunded = $invoice->getBaseTotalRefunded() + $creditmemo->getBaseGrandTotal();
$this->setShouldCloseParentTransaction($invoice->getBaseGrandTotal() <= $totalRefunded);
}
} else {
if ($order->getBaseTotalRefunded() > 0) {
$adjustment = array('adjustment_positive' => $amount);
} else {
$adjustment = array('adjustment_negative' => $baseGrandTotal - $amount);
}
$creditmemo = $serviceModel->prepareCreditmemo($adjustment);
if ($creditmemo) {
$totalRefunded = $order->getBaseTotalRefunded() + $creditmemo->getBaseGrandTotal();
$this->setShouldCloseParentTransaction($order->getBaseGrandTotal() <= $totalRefunded);
}
}
$creditmemo->setPaymentRefundDisallowed(true)
->setAutomaticallyCreated(true)
->register()
->addComment(__('The credit memo has been created automatically.'))
->save();
$this->_updateTotals(array(
'amount_refunded' => $creditmemo->getGrandTotal(),
'base_amount_refunded_online' => $amount
));
$this->setCreatedCreditmemo($creditmemo);
// update transactions and order state
$transaction = $this->_addTransaction(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND, $creditmemo);
$message = $this->_prependMessage(
__('Registered notification about refunded amount of %1.', $this->_formatPrice($amount))
);
$message = $this->_appendTransactionToMessage($transaction, $message);
$order->setState(\Magento\Sales\Model\Order::STATE_PROCESSING, true, $message);
return $this;
}
/**
* Cancel a creditmemo: substract its totals from the payment
*
* @param \Magento\Sales\Model\Order\Creditmemo $creditmemo
* @return \Magento\Sales\Model\Order\Payment
*/
public function cancelCreditmemo($creditmemo)
{
$this->_updateTotals(array(
'amount_refunded' => -1 * $creditmemo->getGrandTotal(),
'base_amount_refunded' => -1 * $creditmemo->getBaseGrandTotal(),
'shipping_refunded' => -1 * $creditmemo->getShippingAmount(),
'base_shipping_refunded' => -1 * $creditmemo->getBaseShippingAmount()
));
$this->_eventManager->dispatch('sales_order_payment_cancel_creditmemo',
array('payment' => $this, 'creditmemo' => $creditmemo)
);
return $this;
}
/**
* Order cancellation hook for payment method instance
* Adds void transaction if needed
* @return \Magento\Sales\Model\Order\Payment
*/
public function cancel()
{
$isOnline = true;
if (!$this->canVoid(new \Magento\Object())) {
$isOnline = false;
}
if (!$this->hasMessage()) {
$this->setMessage($isOnline ? __('Canceled order online')
: __('Canceled order offline')
);
}
if ($isOnline) {
$this->_void($isOnline, null, 'cancel');
}
$this->_eventManager->dispatch('sales_order_payment_cancel', array('payment' => $this));
return $this;
}
/**
* Check order payment review availability
*
* @return bool
*/
public function canReviewPayment()
{
return (bool)$this->getMethodInstance()->canReviewPayment($this);
}
/**
* @return bool
*/
public function canFetchTransactionInfo()
{
return (bool)$this->getMethodInstance()->canFetchTransactionInfo();
}
/**
* Accept online a payment that is in review state
*
* @return \Magento\Sales\Model\Order\Payment
*/
public function accept()
{
$this->registerPaymentReviewAction(self::REVIEW_ACTION_ACCEPT, true);
return $this;
}
/**
* Accept order with payment method instance
*
* @return \Magento\Sales\Model\Order\Payment
*/
public function deny()
{
$this->registerPaymentReviewAction(self::REVIEW_ACTION_DENY, true);
return $this;
}
/**
* Perform the payment review action: either initiated by merchant or by a notification
*
* Sets order to processing state and optionally approves invoice or cancels the order
*
* @param string $action
* @param bool $isOnline
* @return \Magento\Sales\Model\Order\Payment
* @throws \Exception
*/
public function registerPaymentReviewAction($action, $isOnline)
{
$order = $this->getOrder();
$transactionId = $isOnline ? $this->getLastTransId() : $this->getTransactionId();
$invoice = $this->_getInvoiceForTransactionId($transactionId);
// invoke the payment method to determine what to do with the transaction
$result = null; $message = null;
switch ($action) {
case self::REVIEW_ACTION_ACCEPT:
if ($isOnline) {
if ($this->getMethodInstance()->setStore($order->getStoreId())->acceptPayment($this)) {
$result = true;
$message = __('Approved the payment online.');
} else {
$result = -1;
$message = __('There is no need to approve this payment.');
}
} else {
$result = (bool)$this->getNotificationResult() ? true : -1;
$message = __('Registered notification about approved payment.');
}
break;
case self::REVIEW_ACTION_DENY:
if ($isOnline) {
if ($this->getMethodInstance()->setStore($order->getStoreId())->denyPayment($this)) {
$result = false;
$message = __('Denied the payment online');
} else {
$result = -1;
$message = __('There is no need to deny this payment.');
}
} else {
$result = (bool)$this->getNotificationResult() ? false : -1;
$message = __('Registered notification about denied payment.');
}
break;
case self::REVIEW_ACTION_UPDATE:
if ($isOnline) {
$this->getMethodInstance()
->setStore($order->getStoreId())
->fetchTransactionInfo($this, $transactionId);
} else {
// notification mechanism is responsible to update the payment object first
}
if ($this->getIsTransactionApproved()) {
$result = true;
$message = __('Registered update about approved payment.');
} elseif ($this->getIsTransactionDenied()) {
$result = false;
$message = __('Registered update about denied payment.');
} else {
$result = -1;
$message = __('There is no update for the payment.');
}