forked from civicrm/civicrm-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPayPalImpl.php
1123 lines (1001 loc) · 36.7 KB
/
PayPalImpl.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
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
use Civi\Payment\Exception\PaymentProcessorException;
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class CRM_Core_Payment_PayPalImpl for paypal pro, paypal standard & paypal express.
*/
class CRM_Core_Payment_PayPalImpl extends CRM_Core_Payment {
const CHARSET = 'iso-8859-1';
protected $_mode = NULL;
/**
* Constructor.
*
* @param string $mode
* The mode of operation: live or test.
*
* @param CRM_Core_Payment $paymentProcessor
*
* @return \CRM_Core_Payment_PayPalImpl
*/
public function __construct($mode, &$paymentProcessor) {
$this->_mode = $mode;
$this->_paymentProcessor = $paymentProcessor;
$this->_processorName = ts('PayPal Pro');
$paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
if ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
$this->_processorName = ts('PayPal Standard');
return;
}
elseif ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Express', $paymentProcessorType)) {
$this->_processorName = ts('PayPal Express');
}
}
/**
* Are back office payments supported.
*
* E.g paypal standard won't permit you to enter a credit card associated
* with someone else's login.
*
* @return bool
*/
protected function supportsBackOffice() {
if ($this->_processorName == ts('PayPal Pro')) {
return TRUE;
}
return FALSE;
}
/**
* Does this processor support pre-approval.
*
* This would generally look like a redirect to enter credentials which can then be used in a later payment call.
*
* Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
* contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
* 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
*
* @return bool
*/
protected function supportsPreApproval() {
if ($this->_processorName == ts('PayPal Express') || $this->_processorName == ts('PayPal Pro')) {
return TRUE;
}
return FALSE;
}
/**
* Opportunity for the payment processor to override the entire form build.
*
* @param CRM_Core_Form $form
*
* @return bool
* Should form building stop at this point?
*/
public function buildForm(&$form) {
if ($this->supportsPreApproval()) {
$this->addPaypalExpressCode($form);
if ($this->_processorName == ts('PayPal Express')) {
CRM_Core_Region::instance('billing-block-post')->add(array(
'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
'name' => 'paypal_express',
));
}
if ($this->_processorName == ts('PayPal Pro')) {
CRM_Core_Region::instance('billing-block-pre')->add(array(
'template' => 'CRM/Financial/Form/PaypalPro.tpl',
));
}
}
return FALSE;
}
/**
* Billing mode button is basically synonymous with paypal express.
*
* This is probably a good example of 'odds & sods' code we
* need to find a way for the payment processor to assign.
*
* A tricky aspect is that the payment processor may need to set the order
*
* @param CRM_Core_Form $form
*/
protected function addPaypalExpressCode(&$form) {
if (empty($form->isBackOffice)) {
$form->_expressButtonName = $form->getButtonName('upload', 'express');
$form->assign('expressButtonName', $form->_expressButtonName);
$form->add(
'image',
$form->_expressButtonName,
$this->_paymentProcessor['url_button'],
array('class' => 'crm-form-submit')
);
}
}
/**
* Can recurring contributions be set against pledges.
*
* In practice all processors that use the baseIPN function to finish transactions or
* call the completetransaction api support this by looking up previous contributions in the
* series and, if there is a prior contribution against a pledge, and the pledge is not complete,
* adding the new payment to the pledge.
*
* However, only enabling for processors it has been tested against.
*
* @return bool
*/
protected function supportsRecurContributionsForPledges() {
return TRUE;
}
/**
* Default payment instrument validation.
*
* Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
* Not a static function, because I need to check for payment_type.
*
* @param array $values
* @param array $errors
*/
public function validatePaymentInstrument($values, &$errors) {
if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !$this->isPaypalExpress($values)) {
CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
}
}
/**
* Express checkout code.
*
* Check PayPal documentation for more information
*
* @param array $params
* Assoc array of input parameters for this transaction.
*
* @return array
* the result in an nice formatted array (or an error object)
* @throws \Civi\Payment\Exception\PaymentProcessorException
*/
protected function setExpressCheckOut(&$params) {
$args = array();
$this->initialize($args, 'SetExpressCheckout');
$args['paymentAction'] = 'Sale';
$args['amt'] = $params['amount'];
$args['currencyCode'] = $params['currencyID'];
$args['desc'] = CRM_Utils_Array::value('description', $params);
$args['invnum'] = $params['invoiceID'];
$args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
$args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
$args['version'] = '56.0';
//LCD if recurring, collect additional data and set some values
if (!empty($params['is_recur'])) {
$args['L_BILLINGTYPE0'] = 'RecurringPayments';
//$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
$args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
$args['L_PAYMENTTYPE0'] = 'Any';
}
// Allow further manipulation of the arguments via custom hooks ..
CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
$result = $this->invokeAPI($args);
if (is_a($result, 'CRM_Core_Error')) {
throw new PaymentProcessorException($result->message);
}
/* Success */
return $result['token'];
}
/**
* Get any details that may be available to the payment processor due to an approval process having happened.
*
* In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
* result.
*
* @param array $storedDetails
*
* @return array
*/
public function getPreApprovalDetails($storedDetails) {
return empty($storedDetails['token']) ? array() : $this->getExpressCheckoutDetails($storedDetails['token']);
}
/**
* Get details from paypal.
*
* Check PayPal documentation for more information
*
* @param string $token
* The key associated with this transaction.
*
* @return array
* the result in an nice formatted array (or an error object)
*/
public function getExpressCheckoutDetails($token) {
$args = array();
$this->initialize($args, 'GetExpressCheckoutDetails');
$args['token'] = $token;
// LCD
$args['method'] = 'GetExpressCheckoutDetails';
$result = $this->invokeAPI($args);
if (is_a($result, 'CRM_Core_Error')) {
throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
}
/* Success */
$fieldMap = array(
'token' => 'token',
'payer_status' => 'payerstatus',
'payer_id' => 'payerid',
'first_name' => 'firstname',
'middle_name' => 'middlename',
'last_name' => 'lastname',
'street_address' => 'shiptostreet',
'supplemental_address_1' => 'shiptostreet2',
'city' => 'shiptocity',
'postal_code' => 'shiptozip',
'state_province' => 'shiptostate',
'country' => 'shiptocountrycode',
);
return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
}
/**
* Do the express checkout at paypal.
*
* Check PayPal documentation for more information
*
* @param array $params
*
* @return array
* The result in an nice formatted array.
*
* @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function doExpressCheckout(&$params) {
$statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
if (!empty($params['is_recur'])) {
return $this->createRecurringPayments($params);
}
$args = array();
$this->initialize($args, 'DoExpressCheckoutPayment');
$args['token'] = $params['token'];
$args['paymentAction'] = 'Sale';
$args['amt'] = $params['amount'];
$args['currencyCode'] = $params['currencyID'];
$args['payerID'] = $params['payer_id'];
$args['invnum'] = $params['invoiceID'];
$args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
$args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
$args['desc'] = $params['description'];
// add CiviCRM BN code
$args['BUTTONSOURCE'] = 'CiviCRM_SP';
$result = $this->invokeAPI($args);
if (is_a($result, 'CRM_Core_Error')) {
throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
}
/* Success */
$params['trxn_id'] = $result['transactionid'];
$params['gross_amount'] = $result['amt'];
$params['fee_amount'] = $result['feeamt'];
$params['net_amount'] = CRM_Utils_Array::value('settleamt', $result);
if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
$params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
}
$params['payment_status'] = $result['paymentstatus'];
$params['pending_reason'] = $result['pendingreason'];
if (!empty($params['is_recur'])) {
// See comment block.
$params['payment_status_id'] = array_search('Pending', $statuses);
}
else {
$params['payment_status_id'] = array_search('Completed', $statuses);
}
return $params;
}
/**
* Create recurring payments.
*
* @param array $params
*
* @return mixed
*/
public function createRecurringPayments(&$params) {
$args = array();
// @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
$this->initialize($args, 'CreateRecurringPaymentsProfile');
$start_time = strtotime(date('m/d/Y'));
$start_date = date('Y-m-d\T00:00:00\Z', $start_time);
$args['token'] = $params['token'];
$args['paymentAction'] = 'Sale';
$args['amt'] = $params['amount'];
$args['currencyCode'] = $params['currencyID'];
$args['payerID'] = $params['payer_id'];
$args['invnum'] = $params['invoiceID'];
$args['returnURL'] = $params['returnURL'];
$args['cancelURL'] = $params['cancelURL'];
$args['profilestartdate'] = $start_date;
$args['method'] = 'CreateRecurringPaymentsProfile';
$args['billingfrequency'] = $params['frequency_interval'];
$args['billingperiod'] = ucwords($params['frequency_unit']);
$args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
//$args['desc'] = 'Recurring Contribution';
$args['totalbillingcycles'] = $params['installments'];
$args['version'] = '56.0';
$args['profilereference'] = "i={$params['invoiceID']}" .
"&m=" .
"&c={$params['contactID']}" .
"&r={$params['contributionRecurID']}" .
"&b={$params['contributionID']}" .
"&p={$params['contributionPageID']}";
// add CiviCRM BN code
$args['BUTTONSOURCE'] = 'CiviCRM_SP';
$result = $this->invokeAPI($args);
if (is_a($result, 'CRM_Core_Error')) {
return $result;
}
/* Success */
$params['trxn_id'] = $result['transactionid'];
$params['gross_amount'] = $result['amt'];
$params['fee_amount'] = $result['feeamt'];
$params['net_amount'] = $result['settleamt'];
if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
$params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
}
$params['payment_status'] = $result['paymentstatus'];
$params['pending_reason'] = $result['pendingreason'];
return $params;
}
/**
* Initialise.
*
* @param $args
* @param $method
*/
public function initialize(&$args, $method) {
$args['user'] = $this->_paymentProcessor['user_name'];
$args['pwd'] = $this->_paymentProcessor['password'];
$args['version'] = 3.0;
$args['signature'] = $this->_paymentProcessor['signature'];
$args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
$args['method'] = $method;
}
/**
* Process payment - this function wraps around both doTransferPayment and doDirectPayment.
*
* The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
* more agnostic.
*
* Payment processors should set payment_status_id. This function adds some historical defaults ie. the
* assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
* doTransferCheckout would not traditionally come back.
*
* doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
* to be Pending.
*
* Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
* return Error objects
*
* @param array $params
*
* @param string $component
*
* @return array
* Result array
*
* @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function doPayment(&$params, $component = 'contribute') {
if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express'
|| ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !empty($params['token']))
) {
$this->_component = $component;
return $this->doExpressCheckout($params);
}
return parent::doPayment($params, $component);
}
/**
* This function collects all the information from a web/api form and invokes
* the relevant payment processor specific functions to perform the transaction
*
* @param array $params
* Assoc array of input parameters for this transaction.
*
* @param string $component
* @return array
* the result in an nice formatted array (or an error object)
*/
public function doDirectPayment(&$params, $component = 'contribute') {
$args = array();
$this->initialize($args, 'DoDirectPayment');
$args['paymentAction'] = 'Sale';
$args['amt'] = $params['amount'];
$args['currencyCode'] = $params['currencyID'];
$args['invnum'] = $params['invoiceID'];
$args['ipaddress'] = $params['ip_address'];
$args['creditCardType'] = $params['credit_card_type'];
$args['acct'] = $params['credit_card_number'];
$args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
$args['cvv2'] = $params['cvv2'];
$args['firstName'] = $params['first_name'];
$args['lastName'] = $params['last_name'];
$args['email'] = CRM_Utils_Array::value('email', $params);
$args['street'] = $params['street_address'];
$args['city'] = $params['city'];
$args['state'] = $params['state_province'];
$args['countryCode'] = $params['country'];
$args['zip'] = $params['postal_code'];
$args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
$args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
// add CiviCRM BN code
$args['BUTTONSOURCE'] = 'CiviCRM_SP';
if (CRM_Utils_Array::value('is_recur', $params) == 1) {
$start_time = strtotime(date('m/d/Y'));
$start_date = date('Y-m-d\T00:00:00\Z', $start_time);
$args['PaymentAction'] = 'Sale';
$args['billingperiod'] = ucwords($params['frequency_unit']);
$args['billingfrequency'] = $params['frequency_interval'];
$args['method'] = "CreateRecurringPaymentsProfile";
$args['profilestartdate'] = $start_date;
$args['desc'] = "" .
$params['description'] . ": " .
$params['amount'] . " Per " .
$params['frequency_interval'] . " " .
$params['frequency_unit'];
$args['amt'] = $params['amount'];
$args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params);
$args['version'] = 56.0;
$args['PROFILEREFERENCE'] = "" .
"i=" . $params['invoiceID'] . "&m=" . $component .
"&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
"&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
}
// Allow further manipulation of the arguments via custom hooks ..
CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
$result = $this->invokeAPI($args);
//WAG
if (is_a($result, 'CRM_Core_Error')) {
return $result;
}
$params['recurr_profile_id'] = NULL;
if (CRM_Utils_Array::value('is_recur', $params) == 1) {
$params['recurr_profile_id'] = $result['profileid'];
}
/* Success */
$params['trxn_id'] = CRM_Utils_Array::value('transactionid', $result);
$params['gross_amount'] = CRM_Utils_Array::value('amt', $result);
$params = array_merge($params, $this->doQuery($params));
return $params;
}
/**
* Query payment processor for details about a transaction.
*
* For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
*
* @param array $params
* Array of parameters containing one of:
* - trxn_id Id of an individual transaction.
* - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
*
* @return array
* Extra parameters retrieved.
* Any parameters retrievable through this should be documented in the function comments at
* CRM_Core_Payment::doQuery. Currently
* - fee_amount Amount of fee paid
*
* @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function doQuery($params) {
//CRM-18140 - trxn_id not returned for recurring paypal transaction
if (!empty($params['is_recur'])) {
return array();
}
elseif (empty($params['trxn_id'])) {
throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set');
}
$args = array(
'TRANSACTIONID' => $params['trxn_id'],
);
$this->initialize($args, 'GetTransactionDetails');
$result = $this->invokeAPI($args);
return array(
'fee_amount' => $result['feeamt'],
'net_amount' => $params['gross_amount'] - $result['feeamt'],
);
}
/**
* This function checks to see if we have the right config values.
*
* @return string
* the error message if any
*/
public function checkConfig() {
$error = array();
$paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
if (empty($this->_paymentProcessor['signature'])) {
$error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
}
if (empty($this->_paymentProcessor['password'])) {
$error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
}
}
if (empty($this->_paymentProcessor['user_name'])) {
$error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
}
if (!empty($error)) {
return implode('<p>', $error);
}
else {
return NULL;
}
}
/**
* @return null|string
*/
public function cancelSubscriptionURL() {
if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
}
else {
return NULL;
}
}
/**
* Check whether a method is present ( & supported ) by the payment processor object.
*
* @param string $method
* Method to check for.
*
* @return bool
*/
public function isSupported($method) {
if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
// since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
// by standard or express.
return FALSE;
}
return parent::isSupported($method);
}
/**
* Paypal express replaces the submit button with it's own.
*
* @return bool
* Should the form button by suppressed?
*/
public function isSuppressSubmitButtons() {
if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express') {
return TRUE;
}
return FALSE;
}
/**
* @param string $message
* @param array $params
*
* @return array|bool|object
*/
public function cancelSubscription(&$message = '', $params = array()) {
if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
$args = array();
$this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
$args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
$args['ACTION'] = 'Cancel';
$args['NOTE'] = CRM_Utils_Array::value('reason', $params);
$result = $this->invokeAPI($args);
if (is_a($result, 'CRM_Core_Error')) {
return $result;
}
$message = "{$result['ack']}: profileid={$result['profileid']}";
return TRUE;
}
return FALSE;
}
/**
* Process incoming notification.
*/
static public function handlePaymentNotification() {
$params = array_merge($_GET, $_REQUEST);
$q = explode('/', CRM_Utils_Array::value('q', $params, ''));
$lastParam = array_pop($q);
if (is_numeric($lastParam)) {
$params['processor_id'] = $lastParam;
}
if (civicrm_api3('PaymentProcessor', 'getvalue', array(
'id' => $params['processor_id'],
'return' => 'class_name')
) == 'Payment_PayPalImpl') {
$paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
}
else {
$paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
}
$paypalIPN->main();
}
/**
* @param string $message
* @param array $params
*
* @return array|bool|object
*/
public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
$config = CRM_Core_Config::singleton();
$args = array();
$this->initialize($args, 'UpdateRecurringPaymentsProfile');
$args['PROFILEID'] = $params['subscriptionId'];
$args['AMT'] = $params['amount'];
$args['CURRENCYCODE'] = $config->defaultCurrency;
$args['CREDITCARDTYPE'] = $params['credit_card_type'];
$args['ACCT'] = $params['credit_card_number'];
$args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
$args['CVV2'] = $params['cvv2'];
$args['FIRSTNAME'] = $params['first_name'];
$args['LASTNAME'] = $params['last_name'];
$args['STREET'] = $params['street_address'];
$args['CITY'] = $params['city'];
$args['STATE'] = $params['state_province'];
$args['COUNTRYCODE'] = $params['postal_code'];
$args['ZIP'] = $params['country'];
$result = $this->invokeAPI($args);
if (is_a($result, 'CRM_Core_Error')) {
return $result;
}
$message = "{$result['ack']}: profileid={$result['profileid']}";
return TRUE;
}
return FALSE;
}
/**
* @param string $message
* @param array $params
*
* @return array|bool|object
*/
public function changeSubscriptionAmount(&$message = '', $params = array()) {
if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
$config = CRM_Core_Config::singleton();
$args = array();
$this->initialize($args, 'UpdateRecurringPaymentsProfile');
$args['PROFILEID'] = $params['subscriptionId'];
$args['AMT'] = $params['amount'];
$args['CURRENCYCODE'] = $config->defaultCurrency;
$args['BILLINGFREQUENCY'] = $params['installments'];
$result = $this->invokeAPI($args);
CRM_Core_Error::debug_var('$result', $result);
if (is_a($result, 'CRM_Core_Error')) {
return $result;
}
$message = "{$result['ack']}: profileid={$result['profileid']}";
return TRUE;
}
return FALSE;
}
/**
* Function to action pre-approval if supported
*
* @param array $params
* Parameters from the form
*
* @return array
* - pre_approval_parameters (this will be stored on the calling form & available later)
* - redirect_url (if set the browser will be redirected to this.
*/
public function doPreApproval(&$params) {
if (!$this->isPaypalExpress($params)) {
return array();
}
$this->_component = $params['component'];
$token = $this->setExpressCheckOut($params);
return array(
'pre_approval_parameters' => array('token' => $token),
'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
);
}
/**
* @param array $params
* @param string $component
*
* @throws Exception
*/
public function doTransferCheckout(&$params, $component = 'contribute') {
$notifyParameters = array('module' => $component);
$notifyParameterMap = array(
'contactID' => 'contactID',
'contributionID' => 'contributionID',
'eventID' => 'eventID',
'participantID' => 'participantID',
'membershipID' => 'membershipID',
'related_contact' => 'relatedContactID',
'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
'accountingCode' => 'accountingCode',
'contributionRecurID' => 'contributionRecurID',
'contributionPageID' => 'contributionPageID',
);
foreach ($notifyParameterMap as $paramsName => $notifyName) {
if (!empty($params[$paramsName])) {
$notifyParameters[$notifyName] = $params[$paramsName];
}
}
$notifyURL = $this->getNotifyUrl();
$config = CRM_Core_Config::singleton();
$url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
$cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
$cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
if (!empty($params['is_recur'])) {
$cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
}
$cancelURL = CRM_Utils_System::url(
$url,
$cancelUrlString,
TRUE, NULL, FALSE
);
$paypalParams = array(
'business' => $this->_paymentProcessor['user_name'],
'notify_url' => $notifyURL,
'item_name' => $this->getPaymentDescription($params, 127),
'quantity' => 1,
'undefined_quantity' => 0,
'cancel_return' => $cancelURL,
'no_note' => 1,
'no_shipping' => 1,
'return' => $this->getReturnSuccessUrl($params['qfKey']),
'rm' => 2,
'currency_code' => $params['currencyID'],
'invoice' => $params['invoiceID'],
'lc' => substr($config->lcMessages, -2),
'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
'custom' => json_encode($notifyParameters),
'bn' => 'CiviCRM_SP',
);
// add name and address if available, CRM-3130
$otherVars = array(
'first_name' => 'first_name',
'last_name' => 'last_name',
'street_address' => 'address1',
'country' => 'country',
'preferred_language' => 'lc',
'city' => 'city',
'state_province' => 'state',
'postal_code' => 'zip',
'email' => 'email',
);
foreach (array_keys($params) as $p) {
// get the base name without the location type suffixed to it
$parts = explode('-', $p);
$name = count($parts) > 1 ? $parts[0] : $p;
if (isset($otherVars[$name])) {
$value = $params[$p];
if ($value) {
if ($name == 'state_province') {
$stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
$value = $stateName;
}
if ($name == 'country') {
$countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
$value = $countryName;
}
// ensure value is not an array
// CRM-4174
if (!is_array($value)) {
$paypalParams[$otherVars[$name]] = $value;
}
}
}
}
// if recurring donations, add a few more items
if (!empty($params['is_recur'])) {
if (!$params['contributionRecurID']) {
CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
}
$paypalParams += array(
'cmd' => '_xclick-subscriptions',
'a3' => $params['amount'],
'p3' => $params['frequency_interval'],
't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
'src' => 1,
'sra' => 1,
'srt' => CRM_Utils_Array::value('installments', $params),
'no_note' => 1,
'modify' => 0,
);
}
else {
$paypalParams += array(
'cmd' => '_xclick',
'amount' => $params['amount'],
);
}
// Allow further manipulation of the arguments via custom hooks ..
CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
$uri = '';
foreach ($paypalParams as $key => $value) {
if ($value === NULL) {
continue;
}
$value = urlencode($value);
if ($key == 'return' ||
$key == 'cancel_return' ||
$key == 'notify_url'
) {
$value = str_replace('%2F', '/', $value);
}
$uri .= "&{$key}={$value}";
}
$uri = substr($uri, 1);
$url = $this->_paymentProcessor['url_site'];
$sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
$paypalURL = "{$url}{$sub}?$uri";
CRM_Utils_System::redirect($paypalURL);
}
/**
* Hash_call: Function to perform the API call to PayPal using API signature.
*
* @methodName is name of API method.
* @nvpStr is nvp string.
* returns an associative array containing the response from the server.
*
* @param array $args
* @param null $url
*
* @return array|object
* @throws \Exception
*/
public function invokeAPI($args, $url = NULL) {
if ($url === NULL) {
if (empty($this->_paymentProcessor['url_api'])) {
CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
}
$url = $this->_paymentProcessor['url_api'] . 'nvp';
}
if (!function_exists('curl_init')) {
CRM_Core_Error::fatal("curl functions NOT available.");
}
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL'));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, Civi::settings()->get('verifySSL') ? 2 : 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$p = array();
foreach ($args as $n => $v) {
$p[] = "$n=" . urlencode($v);
}
//NVPRequest for submitting to server
$nvpreq = implode('&', $p);
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//getting response from server
$response = curl_exec($ch);
//converting NVPResponse to an Associative Array
$result = self::deformat($response);
if (curl_errno($ch)) {
$e = CRM_Core_Error::singleton();