-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPluginPaypalCallback.php
More file actions
1604 lines (1365 loc) · 77.7 KB
/
PluginPaypalCallback.php
File metadata and controls
1604 lines (1365 loc) · 77.7 KB
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
require_once 'modules/admin/models/PluginCallback.php';
require_once 'modules/admin/models/StatusAliasGateway.php';
require_once 'modules/billing/models/class.gateway.plugin.php';
require_once 'modules/billing/models/Invoice_EventLog.php';
require_once 'modules/admin/models/Error_EventLog.php';
require_once 'modules/billing/models/BillingGateway.php';
class PluginPaypalCallback extends PluginCallback
{
//NEW API CODE
var $params;
//NEW API CODE
function setCallbackParams($params)
{
$this->params = $params;
}
function processCallback()
{
CE_Lib::log(4, 'Paypal callback invoked');
if (!isset($GLOBALS['testing'])) {
$testing = false;
} else {
$testing = $GLOBALS['testing'];
}
//NEW API CODE
//Subscription
if (isset($_REQUEST['newApi']) && $_REQUEST['newApi'] == 1) {
//Execute an agreement
//https://developer.paypal.com/docs/subscriptions/integrate/integrate-steps/#5-execute-an-agreement
if (isset($_REQUEST['token'])) {
$token = $_REQUEST['token'];
$access_token = '';
$agreement = array();
//Get an access token
//https://developer.paypal.com/docs/api/overview/#get-an-access-token
$access_token = $this->getAnAccessToken();
//Execute an agreement
//https://developer.paypal.com/docs/subscriptions/integrate/integrate-steps/#5-execute-an-agreement
$agreement = $this->executeAnAgreement($access_token, $token);
$customValues = explode("_", $agreement['description']);
$tInvoiceID = $customValues[0];
$tIsRecurring = $customValues[1];
$tGenerateInvoice = $customValues[2];
$tRecurringExclude = '';
if (isset($customValues[3])) {
$tRecurringExclude = $customValues[3];
}
if (!is_numeric($tInvoiceID)) {
throw new CE_Exception('Paypal event has failed. Invoice was not found');
}
// Create Plugin class object to interact with CE.
$cPlugin = new Plugin($tInvoiceID, 'paypal', $this->user);
//Lets mark the recurring fees as active subscription.
$cPlugin->setSubscriptionId($agreement['id'], $tRecurringExclude);
$transaction = "Started paypal subscription. Subscription ID: ".$agreement['id'];
$cPlugin->logSubscriptionStarted($transaction, $agreement['id'].' '.$agreement['start_date']);
$clientExecURL = CE_Lib::getSoftwareURL();
$invoiceviewURLSuccess = $clientExecURL."/index.php?fuse=billing&paid=1&controller=invoice&view=invoice&id=".$tInvoiceID;
$invoiceviewURLCancel = $clientExecURL."/index.php?fuse=billing&cancel=1&controller=invoice&view=invoice&id=".$tInvoiceID;
//Need to check to see if user is coming from signup
if (isset($_REQUEST['isSignup']) && $_REQUEST['isSignup'] == 1) {
if ($this->settings->get('Signup Completion URL') != '') {
$return_url = $this->settings->get('Signup Completion URL').'?success=1';
$cancel_url = $this->settings->get('Signup Completion URL');
} else {
$return_url = $clientExecURL."/order.php?step=complete&pass=1";
$cancel_url = $clientExecURL."/order.php?step=3";
}
} else {
$return_url = $invoiceviewURLSuccess;
$cancel_url = $invoiceviewURLCancel;
}
header('Location: '.$return_url);
exit;
} else {
$response = file_get_contents("php://input");
$response = json_decode($response, true);
CE_Lib::log(4, 'Paypal Response: ' . print_r($response, true));
$logOK = $this->_logPaypalCallback(true, $response);
if (!$logOK) {
return;
}
$subscriptionID = '';
$tInvoiceID = '';
switch (strtoupper($response['event_type'])) {
case 'BILLING.SUBSCRIPTION.CREATED':
if (!isset($response['resource']['id'])) {
throw new CE_Exception('Paypal BILLING.SUBSCRIPTION.CREATED event has failed. "resource" => "id" is not defined');
}
$subscriptionID = $response['resource']['id'];
break;
case 'PAYMENT.CAPTURE.COMPLETED':
case 'PAYMENT.SALE.COMPLETED':
case 'PAYMENT.SALE.PENDING':
case 'PAYMENT.SALE.DENIED':
if (!isset($response['resource']['billing_agreement_id'])) {
if (!isset($response['resource']['id'])) {
if (strtoupper($response['event_type']) == 'PAYMENT.CAPTURE.COMPLETED') {
throw new CE_Exception('Paypal PAYMENT.CAPTURE event has failed. "resource" => "id" is not defined');
} else {
throw new CE_Exception('Paypal PAYMENT.SALE event has failed. "resource" => "id" is not defined');
}
}
$cPlugin = new Plugin();
$newInvoice = $cPlugin->retrieveInvoiceForTransaction($response['resource']['id']);
if ($newInvoice) {
$tInvoiceID = $cPlugin->m_ID;
}
} else {
$subscriptionID = $response['resource']['billing_agreement_id'];
}
break;
case 'BILLING.SUBSCRIPTION.CANCELLED':
if (!isset($response['resource']['id'])) {
throw new CE_Exception('Paypal BILLING.SUBSCRIPTION.CANCELLED event has failed. "resource" => "id" is not defined');
}
$subscriptionID = $response['resource']['id'];
break;
case 'PAYMENT.SALE.REFUNDED':
$cPlugin = new Plugin();
$newInvoice = $cPlugin->retrieveInvoiceForTransaction($response['resource']['sale_id']);
if ($newInvoice) {
$tInvoiceID = $cPlugin->m_ID;
}
break;
}
if ($subscriptionID === '' && $tInvoiceID === '') {
if ($subscriptionID === '') {
throw new CE_Exception('Paypal event has failed. Subscription id was not defined');
}
if ($tInvoiceID === '') {
throw new CE_Exception('Paypal event has failed. Invoice was not found');
}
}
if ($subscriptionID !== '') {
$access_token = '';
$agreement = array();
//Get an access token
//https://developer.paypal.com/docs/api/overview/#get-an-access-token
$access_token = $this->getAnAccessToken();
//Show agreement details
//https://developer.paypal.com/docs/api/payments.billing-agreements/v1/#billing-agreements_get
$agreement = $this->showAgreementDetails($access_token, $subscriptionID);
$tIsRecurring = 1;
$tGenerateInvoice = 1;
$tRecurringExclude = '';
if (isset($this->params) && isset($_REQUEST['redirected']) && $_REQUEST['redirected'] == 1) {
$ppTransID = $response['resource']['id'];
$cPlugin = new Plugin(0, 'paypal', $this->user);
if ($cPlugin->TransExists($ppTransID)) {
$newInvoice = $cPlugin->retrieveInvoiceForTransaction($ppTransID);
if ($newInvoice) {
$tInvoiceID = $cPlugin->m_Invoice->getId();
}
} else {
//Search for existing invoice, unpaid and with same subscription id
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($agreement['id'], $ppTransID);
if ($newInvoice) {
$tInvoiceID = $cPlugin->m_Invoice->getId();
} else {
//get client id based on the subscription id of recurring fees
$customerid = $cPlugin->retrieveUserdIdForSubscription($agreement['id']);
$message = "There was a PayPal subscription payment for subscription ".$agreement['id'].".\n"
."However, the system could not find any pending invoice for this subscription. The PayPal transaction id for the payment is ".$ppTransID.".\n"
."Please take a look at the customer to confirm if this payment was required.\n"
."If the payment was not required, please make sure to login to your PayPal account and refund the payment. If the subscription should no longer apply, please cancel the subscription in your PayPal account.\n"
."\n"
."Thanks.";
if ($customerid !== false) {
//try to generate the customer invoices and search again
$billingGateway = new BillingGateway($this->user);
$billingGateway->processCustomerBilling($customerid, $agreement['id']);
//Search for existing invoice, unpaid and with same subscription id
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($agreement['id'], $ppTransID);
if ($newInvoice) {
$tInvoiceID = $cPlugin->m_Invoice->getId();
} else {
if (isset($customerid)) {
// GENERATE TICKET
$tUser = new User($customerid);
$subject = 'Issue with paypal subscription payment';
$cPlugin->createTicket($agreement['id'], $subject, $message, $tUser);
} else {
CE_Lib::log(1, $message);
}
$errorLog = Error_EventLog::newInstance(
false,
(isset($customerid))? $customerid : 0,
$tInvoiceID,
ERROR_EVENTLOG_PAYPAL_CALLBACK,
NE_EVENTLOG_USER_SYSTEM,
serialize($this->_utf8EncodePaypalCallback($response))
);
$errorLog->save();
exit;
}
} else {
CE_Lib::log(1, $message);
$errorLog = Error_EventLog::newInstance(
false,
0,
$tInvoiceID,
ERROR_EVENTLOG_PAYPAL_CALLBACK,
NE_EVENTLOG_USER_SYSTEM,
serialize($this->_utf8EncodePaypalCallback($response))
);
$errorLog->save();
exit;
}
}
}
} else {
$customValues = explode("_", $agreement['description']);
$tInvoiceID = $customValues[0];
$tIsRecurring = $customValues[1];
$tGenerateInvoice = $customValues[2];
if (isset($customValues[3])) {
$tRecurringExclude = $customValues[3];
}
}
if (!is_numeric($tInvoiceID)) {
throw new CE_Exception('Paypal event has failed. Invoice was not found');
}
} elseif (strtoupper($response['event_type']) != 'PAYMENT.CAPTURE.COMPLETED') {
CE_Lib::log(4, 'Exiting Paypal callback invocation');
exit;
}
// Create Plugin class object to interact with CE.
$cPlugin = new Plugin($tInvoiceID, 'paypal', $this->user);
//Webhooks
//https://developer.paypal.com/docs/api/webhooks/v1/
//https://github.com/paypal/PayPal-PHP-SDK/blob/master/sample/notifications/CreateWebhook.php
//https://developer.paypal.com/docs/integration/direct/webhooks/rest-webhooks/
//https://developer.paypal.com/docs/integration/direct/webhooks/event-names/
// - Login to https://developer.paypal.com
// - Go to Dashboard -> Webhooks Simulator -> Enter the Webhooks URL, select the Event type and then click on 'Send test'.
//This will give you a basic sample of the different events/notifications
//subscr_signup => BILLING.SUBSCRIPTION.CREATED
//subscr_payment => PAYMENT.SALE.COMPLETED
//subscr_eot =>
//subscr_cancel => ? BILLING.SUBSCRIPTION.CANCELLED
//subscr_failed =>
//refund => ? PAYMENT.SALE.REFUNDED
switch (strtoupper($response['event_type'])) {
case 'BILLING.SUBSCRIPTION.CREATED':
//Lets mark the recurring fees as active subscription.
$set = $cPlugin->setSubscriptionId($agreement['id'], $tRecurringExclude);
if ($set) {
$transaction = "Started paypal subscription. Subscription ID: ".$agreement['id'];
$cPlugin->logSubscriptionStarted($transaction, $agreement['id'].' '.$agreement['start_date']);
}
return;
break;
case 'PAYMENT.CAPTURE.COMPLETED':
if (!isset($response['resource']['id'])) {
throw new CE_Exception('Paypal PAYMENT.CAPTURE event has failed. "resource" => "id" is not defined');
}
if (!isset($response['resource']['status'])) {
throw new CE_Exception('Paypal PAYMENT.CAPTURE event has failed. "resource" => "status" is not defined');
}
if (!isset($response['resource']['amount']['value'])) {
throw new CE_Exception('Paypal PAYMENT.CAPTURE event has failed. "resource" => "amount" => "value" is not defined');
}
$ppTransID = $response['resource']['id'];
$ppPayStatus = strtolower($response['resource']['status']);
$ppPayAmount = $response['resource']['amount']['value'];
//Add plugin details
$cPlugin->setAmount($ppPayAmount);
$cPlugin->m_TransactionID = $ppTransID;
$cPlugin->m_Action = "charge";
$cPlugin->m_Last4 = "NA";
switch ($ppPayStatus) {
case "completed": // The payment has been completed, and the funds have been added successfully to your account balance.
$transaction = "Paypal payment of $ppPayAmount was accepted. Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentAccepted($ppPayAmount, $transaction, $ppTransID, $testing);
break;
case "pending": // The payment is pending. See pending_reason for more information.
$pendingReason = '';
if (isset($response['resource']['pending_reason'])) {
$pendingReason = '. Reason: '.$response['resource']['pending_reason'];
}
$transaction = "Paypal payment of $ppPayAmount was marked 'pending' by Paypal".$pendingReason.". Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentPending($transaction, $ppTransID);
break;
case "denied": // The payment was denied.
$transaction = "Paypal payment of $ppPayAmount was denied. Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentRejected($transaction);
break;
}
return;
break;
case 'PAYMENT.SALE.COMPLETED':
case 'PAYMENT.SALE.PENDING':
case 'PAYMENT.SALE.DENIED':
if (!isset($response['resource']['id'])) {
throw new CE_Exception('Paypal PAYMENT.SALE event has failed. "resource" => "id" is not defined');
}
if (!isset($response['resource']['state'])) {
throw new CE_Exception('Paypal PAYMENT.SALE event has failed. "resource" => "state" is not defined');
}
if (!isset($response['resource']['amount']['total'])) {
throw new CE_Exception('Paypal PAYMENT.SALE event has failed. "resource" => "amount" => "total" is not defined');
}
$ppTransID = $response['resource']['id'];
$ppPayStatus = strtolower($response['resource']['state']);
$ppPayAmount = $response['resource']['amount']['total'];
$newInvoice = false;
// Check to see if this Invoice is not unpaid
if ($cPlugin->IsUnpaid() == 0) {
$cPlugin->setSubscriptionId($agreement['id'], $tRecurringExclude);
CE_Lib::log(4, 'Previous subscription invoice is already paid');
// If it is, then check to see if the GenerateInvoice variable was passed to the script
if ($tGenerateInvoice) {
// If it was and is TRUE (1), set internal Plugin object variables to the existing invoice's information.
if ($cPlugin->TransExists($ppTransID)) {
$newInvoice = $cPlugin->retrieveInvoiceForTransaction($ppTransID);
if ($newInvoice && $cPlugin->m_Invoice->isPending()) {
CE_Lib::log(4, 'Invoice already exists, and is marked as pending');
}
} else {
//Search for existing invoice, unpaid and with same subscription id
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($agreement['id'], $ppTransID);
if ($newInvoice === false) {
$customerid = $cPlugin->m_Invoice->getUserID();
//try to generate the customer invoices and search again
$billingGateway = new BillingGateway($this->user);
$billingGateway->processCustomerBilling($customerid, $agreement['id']);
//Search for existing invoice, unpaid and with same subscription id
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($agreement['id'], $ppTransID);
if ($newInvoice === false) {
$message = "There was a PayPal subscription payment for subscription ".$agreement['id'].".\n"
."However, the system could not find any pending invoice for this subscription. The PayPal transaction id for the payment is ".$ppTransID.".\n"
."Please take a look at the customer to confirm if this payment was required.\n"
."If the payment was not required, please make sure to login to your PayPal account and refund the payment. If the subscription should no longer apply, please cancel the subscription in your PayPal account.\n"
."\n"
."Thanks.";
if (isset($customerid)) {
// GENERATE TICKET
$tUser = new User($customerid);
$subject = 'Issue with paypal subscription payment';
$cPlugin->createTicket($agreement['id'], $subject, $message, $tUser);
} else {
CE_Lib::log(1, $message);
}
$errorLog = Error_EventLog::newInstance(
false,
(isset($customerid))? $customerid : 0,
$tInvoiceID,
ERROR_EVENTLOG_PAYPAL_CALLBACK,
NE_EVENTLOG_USER_SYSTEM,
serialize($this->_utf8EncodePaypalCallback($response))
);
$errorLog->save();
exit;
}
}
}
} else {
CE_Lib::log(4, 'Exiting Paypal callback invocation');
exit;
}
}
//Add plugin details
$cPlugin->setAmount($ppPayAmount);
$cPlugin->m_TransactionID = $ppTransID;
$cPlugin->m_Action = "charge";
$cPlugin->m_Last4 = "NA";
if ($tIsRecurring) {
switch ($ppPayStatus) {
case "completed": // The payment has been completed, and the funds have been added successfully to your account balance.
//The subscription will be updated when getting the payment callback, to avoid a conflcik with the subscr_signup callback
$cPlugin->setSubscriptionId($agreement['id'], $tRecurringExclude);
$transaction = "Paypal payment of $ppPayAmount was accepted. Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentAccepted($ppPayAmount, $transaction, $ppTransID, $testing);
break;
case "pending": // The payment is pending. See pending_reason for more information.
//The subscription will be updated when getting the payment callback, to avoid a conflcik with the subscr_signup callback
$cPlugin->setSubscriptionId($agreement['id'], $tRecurringExclude);
$pendingReason = '';
if (isset($response['resource']['pending_reason'])) {
$pendingReason = '. Reason: '.$response['resource']['pending_reason'];
}
$transaction = "Paypal payment of $ppPayAmount was marked 'pending' by Paypal".$pendingReason.". Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentPending($transaction, $ppTransID);
break;
case "denied": // The payment was denied.
$transaction = "Paypal payment of $ppPayAmount was denied. Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentRejected($transaction);
break;
}
}
return;
break;
case 'BILLING.SUBSCRIPTION.CANCELLED':
if ($tIsRecurring) {
CE_Lib::log(4, "Subscription has been cancelled.");
$transaction = "Paypal subscription cancelled. Original Signup Invoice: $tInvoiceID";
$old_processorid = '';
$reset = $cPlugin->resetRecurring($transaction, $agreement['id'], $tRecurringExclude, $tInvoiceID, $old_processorid);
$tUser = new User($cPlugin->m_Invoice->m_UserID);
if (in_array($tUser->getStatus(), StatusAliasGateway::getInstance($this->user)->getUserStatusIdsFor(USER_STATUS_CANCELLED))) {
CE_Lib::log(4, 'User is already cancelled. Ignore callback.');
} elseif ($reset) {
$subject = 'Gateway recurring payment cancelled';
$message = "Recurring payment for invoice $tInvoiceID has been cancelled.";
// If createTicket returns false it's because this transaction has already been done
if (!$cPlugin->createTicket($agreement['id'], $subject, $message, $tUser)) {
exit;
}
}
}
return;
break;
case 'PAYMENT.SALE.REFUNDED':
if (strtolower($response['resource']["state"]) == 'completed' && $response['resource']['sale_id'] == $transactionID) {
// Create Plugin class object to interact with CE.
$cPlugin = new Plugin($params['invoiceNumber'], 'paypal', $this->user);
//Add plugin details
$cPlugin->setAmount($params['invoiceTotal']);
$cPlugin->m_TransactionID = $response['resource']['id'];
$cPlugin->m_Action = "refund";
$cPlugin->m_Last4 = "NA";
if (isset($response['resource']['sale_id'])) {
$ppParentTransID = $response['resource']['sale_id'];
if ($cPlugin->TransExists($ppParentTransID)) {
$newInvoice = $cPlugin->retrieveInvoiceForTransaction($ppParentTransID);
if ($newInvoice && ($cPlugin->m_Invoice->isPaid() || $cPlugin->m_Invoice->isPartiallyPaid())) {
$transaction = "Paypal payment of ".$params['invoiceTotal']." was refunded. Original Signup Invoice: ".$params['invoiceNumber']." (OrderID: ".$response['resource']['id'].")";
$cPlugin->PaymentRefunded($params['invoiceTotal'], $transaction, $response['resource']['id']);
} elseif (!$cPlugin->m_Invoice->isRefunded()) {
CE_Lib::log(1, 'Related invoice not found or not set as paid on the application, when doing the refund');
}
} else {
CE_Lib::log(1, 'Parent transaction id not matching any existing invoice on the application, when doing the refund');
}
} else {
CE_Lib::log(1, 'Callback not returning parent_txn_id when refunding');
}
return array('AMOUNT' => $params['invoiceTotal']);
} else {
CE_Lib::log(4, 'Error with PayPal Refund: ' . print_r($response, true));
return 'Error with PayPal Refund';
}
return;
break;
}
exit;
}
}
//Single Payment
if (isset($this->params) && isset($this->params['newApi']) && $this->params['newApi'] == 1) {
$params = $this->params;
$pluginFolderName = basename(dirname(__FILE__));
//Make sure to get and assign the invoice id from the parameters returned from the gateway.
$invoiceId = $params['invoiceId'];
$gatewayPlugin = new Plugin($invoiceId, $pluginFolderName, $this->user);
//If the gateway API provides a way to verify the response, make sure to verify it before performing any actions over the invoice.
$transactionVerified = true;
if (!$transactionVerified) {
$transaction = "Paypal transaction verification has failed.";
$gatewayPlugin->PaymentRejected($transaction);
exit;
}
//Make sure to get and assign the transaction id from the parameters returned from the gateway.
$transactionId = $params['transactionId'];
$gatewayPlugin->setTransactionID($transactionId);
//Make sure to get and assign the transaction amount from the parameters returned from the gateway.
$transactionAmount = $params['transactionAmount'];
$gatewayPlugin->setAmount($transactionAmount);
//Make sure to get and assign the credit card last four digits from the parameters returned from the gateway, or set it as 'NA' if not available.
//Allowed values: 'NA', credit card last four digits
$transactionLast4 = $params['transactionLast4'];
$gatewayPlugin->setLast4($transactionLast4);
//Make sure to get and assign the type of transaction from the parameters returned from the gateway.
//Allowed values: charge, refund
$transactionAction = $params['transactionAction'];
switch ($transactionAction) {
case 'charge':
$gatewayPlugin->setAction('charge');
//Make sure to get and assign the transaction status from the parameters returned from the gateway.
$transactionStatus = $params['transactionStatus'];
//Make sure to replace the case values in the following switch, to match the status values returned from the gateway.
switch ($transactionStatus) {
case 'completed':
$transaction = "Paypal payment of $transactionAmount was accepted. Original Signup Invoice: $invoiceId (OrderID: ".$transactionId.")";
$gatewayPlugin->PaymentAccepted($transactionAmount, $transaction, $transactionId);
break;
case 'pending':
$transaction = "Paypal payment of $transactionAmount was marked 'pending' by Paypal. Original Signup Invoice: $invoiceId (OrderID: ".$transactionId.")";
$gatewayPlugin->PaymentPending($transaction, $transactionId);
break;
case 'denied':
$transaction = "Paypal payment of $transactionAmount was rejected. Original Signup Invoice: $invoiceId (OrderID: ".$transactionId.")";
$gatewayPlugin->PaymentRejected($transaction);
break;
}
break;
case 'refund':
//REFUND NOT HANDLED YET
break;
}
return;
}
//NEW API CODE
$logOK = $this->_logPaypalCallback();
if ($this->settings->get('plugin_paypal_Use PayPal Sandbox') == '0' && isset($_POST['test_ipn']) && $_POST['test_ipn'] == '1') {
CE_Lib::log(4, "** Paypal sandbox callback but account is in production mode => callback discarded");
return;
}
$ppTransType = '';
if (!isset($_POST['txn_type']) && isset($_POST['payment_status']) && $_POST['payment_status'] == 'Refunded') {
$ppTransType = 'refund';
}
if (!isset($_POST['txn_type']) && $ppTransType == '') {
CE_Lib::log(4, 'Paypal callback ignored: txn_type is not defined');
return;
}
// Assign IPN Variables
// Different possible transaction types (txn_type) for subscriptions:
// 1. 'subscr_signup': issued just after the client has paid the inicial amount. We ignore this.
// 2. 'subscr_payment': issued just after the previous one and for every subsequent payment.
if ($ppTransType == '') {
$ppTransType = $_POST['txn_type'];
}
//Handling different names used for the same values in different transaction types
//CUSTOM FIELD
$custom = '';
if (isset($_POST['custom'])) {
$custom = $_POST['custom'];
}
if ($custom == '' && isset($_POST['product_name'])) {
$custom = $_POST['product_name'];
}
if ($custom == '' && isset($_POST['transaction_subject'])) {
$custom = $_POST['transaction_subject'];
}
$custom = str_replace('Invoice #', '', $custom);
//SUNSCRIPTION ID
$subscr_id = '';
if (isset($_POST['subscr_id'])) {
$subscr_id = $_POST['subscr_id'];
}
if ($subscr_id == '' && isset($_POST['recurring_payment_id'])) {
$subscr_id = $_POST['recurring_payment_id'];
}
//SUBSCRIPTION DATE
$subscr_date = '';
if (isset($_POST['subscr_date'])) {
$subscr_date = $_POST['subscr_date'];
}
if ($subscr_date == '' && isset($_POST['time_created'])) {
$subscr_date = $_POST['time_created'];
}
//Handling different names used for the same values in different transaction types
$ppTransID = @$_POST['txn_id']; // Transaction ID (Unique) (not defined for subscription cancellations)
$ppPayStatus = @$_POST['payment_status']; // Payment Status (not defined for subscription cancellations)
$ppPayAmount = @$_POST['mc_gross']; // Total paid for this transaction (not defined for subscription cancellations)
$customValues = explode("_", $custom);
$tInvoiceID = $customValues[0];
$tIsRecurring = 0;
if (isset($customValues[1])) {
$tIsRecurring = $customValues[1];
}
$tGenerateInvoice = 1;
if (isset($customValues[2])) {
$tGenerateInvoice = $customValues[2];
}
$tRecurringExclude = '';
if (isset($customValues[3])) {
$tRecurringExclude = $customValues[3];
}
CE_Lib::log(4, "\$ppTransType: $ppTransType; \$ppTransID: $ppTransID; \$ppPayStatus: $ppPayStatus;");
CE_Lib::log(4, "\$ppPayAmount: $ppPayAmount; \$tInvoiceID: $tInvoiceID; \$tIsRecurring: $tIsRecurring; \$tGenerateInvoice: $tGenerateInvoice \$tRecurringExclude: $tRecurringExclude");
if (!$logOK) {
return;
}
// Create Plugin class object to interact with CE.
$cPlugin = new Plugin($tInvoiceID, 'paypal', $this->user);
// Comfirm the callback before assuming anything
$exit = false;
$createTicket = false;
$maxRetries = 3;
for ($retry = 1; $retry <= $maxRetries; $retry++) {
$exit = false;
$createTicket = false;
CE_Lib::log(4, "Requesting callback confirmation (attempt $retry of $maxRetries); sending request: $paypal_url?$req");
try {
$res = $this->_requestConfirmation($testing);
} catch (Exception $e) {
$customerid = $cPlugin->m_Invoice->getUserID();
$errorLog = Error_EventLog::newInstance(
false,
(isset($customerid))? $customerid : 0,
$tInvoiceID,
ERROR_EVENTLOG_PAYPAL_REQUEST_CONFIRMATION,
NE_EVENTLOG_USER_SYSTEM,
serialize($this->_utf8EncodePaypalCallback($_POST))
);
$errorLog->save();
//exit;
$exit = true;
continue;
}
CE_Lib::log(4, "Request Confirmation Returned (attempt $retry of $maxRetries): ".$res);
if (strpos($res, "VERIFIED") !== false) {
CE_Lib::log(4, "Callback has been verified successfully");
break;
} elseif (strpos($res, "INVALID") !== false) {
CE_Lib::log(4, "Callback verification returned 'INVALID'");
$transaction = "Paypal IPN returned INVALID to Confirmation.";
$cPlugin->PaymentRejected($transaction);
//return;
$exit = true;
break;
} else {
CE_Lib::log(1, "Callback not returning verification code of 'VERIFIED' or 'INVALID' (attempt $retry of $maxRetries). Original Paypal callback details: ".print_r($_POST, true));
//return;
$createTicket = true;
$exit = true;
}
}
if ($exit) {
if ($createTicket) {
$customerid = $cPlugin->m_Invoice->getUserID();
$message = "There was a PayPal Callback not returning verification code of 'VERIFIED' or 'INVALID'. Attempted verification $maxRetries time(s).\n"
."\n"
."Original Paypal callback details:\n"
.print_r($_POST, true)."\n"
."\n"
."When trying to verify, Paypal returned:\n"
.$res."\n"
."\n"
."Please make sure to login to your PayPal account and verify the transaction by yourself. Also, you probably will need to take some manual actions over an invoice.\n"
."\n"
."Thanks.";
if (isset($customerid)) {
// GENERATE TICKET
$tUser = new User($customerid);
$subject = 'Issue when verifying paypal callback';
$cPlugin->createTicket(false, $subject, $message, $tUser);
} else {
CE_Lib::log(1, $message);
}
}
exit;
}
// Comfirm the callback before assuming anything
if ($ppTransType == 'subscr_signup') { // Subscription started
// Here we should update a field in the first invoice with the subscription date:
// $subscr_date
// Time/Date stamp generated by PayPal , in the following format: HH:MM:SS DD Mmm YY, YYYY PST
// 22:21:09 Oct 20, 2009 PDT
// However, I am not believing in this param now, because seems that the documentacion says
// one thing different than what I am really getting in this parameter.
//Lets mark the recurring fees as active subscription.
$cPlugin->setRecurring($tRecurringExclude);
//Lets avoid updating invoice instance on this callback because there is another callback very close that is also updating the invoice, causing to lost some data.
//The subscription will be instead updated when getting the payment callback.
//$cPlugin->setSubscriptionId($subscr_id, $tRecurringExclude);
$transaction = "Started paypal subscription. Subscription ID: ".$subscr_id;
$cPlugin->logSubscriptionStarted($transaction, $subscr_id.' '.$subscr_date);
CE_Lib::log(4, 'Paypal subscr_signup callback ignored');
return;
}
$newInvoice = false;
// Check to see if this Invoice is not unpaid
if ($cPlugin->IsUnpaid() == 0 && in_array($ppTransType, array('subscr_payment', 'recurring_payment'))) {
$cPlugin->setSubscriptionId($subscr_id, $tRecurringExclude);
CE_Lib::log(4, 'Previous subscription invoice is already paid');
// If it is, then check to see if the GenerateInvoice variable was passed to the script
if ($tGenerateInvoice) {
// If it was and is TRUE (1), set internal Plugin object variables to the existing invoice's information.
if ($cPlugin->TransExists($ppTransID)) {
$newInvoice = $cPlugin->retrieveInvoiceForTransaction($ppTransID);
if ($newInvoice && $cPlugin->m_Invoice->isPending()) {
CE_Lib::log(4, 'Invoice already exists, and is marked as pending');
}
} else {
//Search for existing invoice, unpaid and with same subscription id
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($subscr_id, $ppTransID);
if ($newInvoice === false && isset($_POST['old_subscr_id'])) {
//Search for existing invoice, unpaid and with the old subscription id
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($_POST['old_subscr_id'], $ppTransID);
if ($newInvoice) {
CE_Lib::log(4, 'The Subscription ID was changed from '.$_POST['old_subscr_id'].' to '.$subscr_id);
//Update the invoice with the new subscription id
$cPlugin->setSubscriptionId($subscr_id, $tRecurringExclude);
}
}
if ($newInvoice === false) {
$customerid = $cPlugin->m_Invoice->getUserID();
//try to generate the customer invoices and search again
$billingGateway = new BillingGateway($this->user);
$billingGateway->processCustomerBilling($customerid, $subscr_id);
//Search for existing invoice, unpaid and with same subscription id
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($subscr_id, $ppTransID);
if ($newInvoice === false) {
$message = "There was a PayPal subscription payment for subscription ".$subscr_id.".\n"
."However, the system could not find any pending invoice for this subscription. The PayPal transaction id for the payment is ".$ppTransID.".\n"
."Please take a look at the customer to confirm if this payment was required.\n"
."If the payment was not required, please make sure to login to your PayPal account and refund the payment. If the subscription should no longer apply, please cancel the subscription in your PayPal account.\n"
."\n"
."Thanks.";
if (isset($customerid)) {
// GENERATE TICKET
$tUser = new User($customerid);
$subject = 'Issue with paypal subscription payment';
$cPlugin->createTicket($subscr_id, $subject, $message, $tUser);
} else {
CE_Lib::log(1, $message);
}
$errorLog = Error_EventLog::newInstance(
false,
(isset($customerid))? $customerid : 0,
$tInvoiceID,
ERROR_EVENTLOG_PAYPAL_CALLBACK,
NE_EVENTLOG_USER_SYSTEM,
serialize($this->_utf8EncodePaypalCallback($_POST))
);
$errorLog->save();
exit;
}
}
}
} else {
CE_Lib::log(4, 'Exiting Paypal callback invocation');
exit;
}
} elseif ($cPlugin->IsUnpaid() == 0 && $tIsRecurring && $ppTransType != 'refund' && $ppPayStatus != 'Refunded') {
//LETS SEARCH THE LATEST SUBSCRIPTION INVOICE, NO MATTER THE STATUS
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($subscr_id, $ppTransID, false);
if ($newInvoice === false && isset($_POST['old_subscr_id'])) {
//LETS SEARCH THE LATEST SUBSCRIPTION INVOICE WITH THE OLD SUBSCRIPTION ID, NO MATTER THE STATUS
$newInvoice = $cPlugin->retrieveLastInvoiceForSubscription($_POST['old_subscr_id'], $ppTransID, false);
if ($newInvoice) {
CE_Lib::log(4, 'The Subscription ID was changed from '.$_POST['old_subscr_id'].' to '.$subscr_id);
//Update the invoice with the new subscription id
$cPlugin->setSubscriptionId($subscr_id, $tRecurringExclude);
}
}
if ($newInvoice === false) {
$errorLog = Error_EventLog::newInstance(
false,
(isset($customerid))? $customerid : 0,
$tInvoiceID,
ERROR_EVENTLOG_PAYPAL_CALLBACK,
NE_EVENTLOG_USER_SYSTEM,
serialize($this->_utf8EncodePaypalCallback($_POST))
);
$errorLog->save();
exit;
}
}
//Add plugin details
$cPlugin->setAmount($ppPayAmount);
$cPlugin->m_TransactionID = $ppTransID;
$cPlugin->m_Action = "charge";
$cPlugin->m_Last4 = "NA";
// Manage the payment
// TODO check that receiver_email is an email address in your PayPal account
if ($tIsRecurring && $ppTransType != 'refund' && $ppPayStatus != 'Refunded') {
// Uncomment to test payment failures through subscription cancellations
// if ($ppTransType == 'subscr_cancel') $ppTransType = 'subscr_failed';
switch ($ppTransType) {
case 'subscr_payment': // Subscription payment received
case 'recurring_payment': // Recurring payment received
switch ($ppPayStatus) {
case "Completed": // The payment has been completed, and the funds have been added successfully to your account balance.
//The subscription will be updated when getting the payment callback, to avoid a conflcik with the subscr_signup callback
$cPlugin->setSubscriptionId($subscr_id, $tRecurringExclude);
$transaction = "Paypal payment of $ppPayAmount was accepted. Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentAccepted($ppPayAmount, $transaction, $ppTransID, $testing);
break;
case "Pending": // The payment is pending. See pending_reason for more information.
//The subscription will be updated when getting the payment callback, to avoid a conflcik with the subscr_signup callback
$cPlugin->setSubscriptionId($subscr_id, $tRecurringExclude);
$transaction = "Paypal payment of $ppPayAmount was marked 'pending' by Paypal. Reason: ".$_POST['pending_reason'].". Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentPending($transaction, $ppTransID);
break;
case "Failed": // The payment has failed. This happens only if the payment was made from your customer�s bank account.
$transaction = "Paypal payment of $ppPayAmount was rejected. Original Signup Invoice: $tInvoiceID (OrderID: ".$ppTransID.")";
$cPlugin->PaymentRejected($transaction);
break;
}
break;
case 'subscr_eot': // Subscription expired
CE_Lib::log(4, "Subscription has expired on Paypal's side.");
$tUser = new User($cPlugin->m_Invoice->m_UserID);
if (in_array($tUser->getStatus(), StatusAliasGateway::getInstance($this->user)->getUserStatusIdsFor(USER_STATUS_CANCELLED))) {
CE_Lib::log(4, 'User is already cancelled. Ignore callback.');
} else {
$subject = 'Gateway recurring payment expired';
$message = "Recurring payment for invoice $tInvoiceID, corresponding to package \"{$_POST['item_name']}\" has expired.";
// If createTicket returns false it's because this transaction has already been done
// Use subscr_id because txn_id is not sent on cancellation IPNs from Paypal
if (!$cPlugin->createTicket($subscr_id, $subject, $message, $tUser)) {
exit;
}
}
$transaction = "Paypal subscription has expired. Original Signup Invoice: $tInvoiceID. Subscription ID: ".$subscr_id;
$old_processorid = '';
if (isset($_POST['old_subscr_id'])) {
$old_processorid = $_POST['old_subscr_id'];
}
$cPlugin->resetRecurring($transaction, $subscr_id, $tRecurringExclude, $tInvoiceID, $old_processorid);
break;
case 'subscr_cancel': // Subscription canceled
CE_Lib::log(4, "Subscription has been cancelled on Paypal's side.");
$tUser = new User($cPlugin->m_Invoice->m_UserID);
if (in_array($tUser->getStatus(), StatusAliasGateway::getInstance($this->user)->getUserStatusIdsFor(USER_STATUS_CANCELLED))) {
CE_Lib::log(4, 'User is already cancelled. Ignore callback.');
} else {
$subject = 'Gateway recurring payment cancelled';
$message = "Recurring payment for invoice $tInvoiceID, corresponding to package \"{$_POST['item_name']}\" has been cancelled by customer.";
// If createTicket returns false it's because this transaction has already been done
// Use subscr_id because txn_id is not sent on cancellation IPNs from Paypal
if (!$cPlugin->createTicket($subscr_id, $subject, $message, $tUser)) {
exit;
}
}
$transaction = "Paypal subscription cancelled. Original Signup Invoice: $tInvoiceID";
$old_processorid = '';
if (isset($_POST['old_subscr_id'])) {
$old_processorid = $_POST['old_subscr_id'];
}
$cPlugin->resetRecurring($transaction, $subscr_id, $tRecurringExclude, $tInvoiceID, $old_processorid);
break;
case 'subscr_failed': // Subscription signup failed
// this is caused by lack of funds for example
$subject = 'Gateway recurring payment failed';
$reason = isset($_POST['pending_reason'])? $_POST['pending_reason'] : 'unknown';
$message = "Recurring payment for invoice $tInvoiceID, corresponding to package \"{$_POST['item_name']}\" has failed.\n";
$message .= "Reason: $reason.";
$tUser = new User($cPlugin->m_Invoice->m_UserID);
// if createTicket returns false it's because this transaction has already been done
if (!$cPlugin->createTicket($subscr_id, $subject, $message, $tUser)) {
exit;
}
// log failed transaction
$transaction = "Recurring subscription payment failed. Reason: $reason.";
$cPlugin->logFailedSubscriptionPayment($transaction, $subscr_id.' '.$subscr_date);
break;
}
} elseif ($ppTransType == 'refund' && $ppPayStatus == 'Refunded') {
$cPlugin->m_Action = "refund";
$ppPayAmount = str_replace("-", "", $ppPayAmount);
if (isset($_POST['parent_txn_id'])) {
$ppParentTransID = $_POST['parent_txn_id'];