Merge pull request #15590 from alifrumin/subjecthelp
[civicrm-core.git] / CRM / Core / Payment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 use Civi\Payment\System;
29 use Civi\Payment\Exception\PaymentProcessorException;
30
31 /**
32 * Class CRM_Core_Payment.
33 *
34 * This class is the main class for the payment processor subsystem.
35 *
36 * It is the parent class for payment processors. It also holds some IPN related functions
37 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
38 */
39 abstract class CRM_Core_Payment {
40
41 /**
42 * Component - ie. event or contribute.
43 *
44 * This is used for setting return urls.
45 *
46 * @var string
47 */
48 protected $_component;
49
50 /**
51 * How are we getting billing information.
52 *
53 * We are trying to completely deprecate these parameters.
54 *
55 * FORM - we collect it on the same page
56 * BUTTON - the processor collects it and sends it back to us via some protocol
57 */
58 const
59 BILLING_MODE_FORM = 1,
60 BILLING_MODE_BUTTON = 2,
61 BILLING_MODE_NOTIFY = 4;
62
63 /**
64 * Which payment type(s) are we using?
65 *
66 * credit card
67 * direct debit
68 * or both
69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
70 */
71 const
72 PAYMENT_TYPE_CREDIT_CARD = 1,
73 PAYMENT_TYPE_DIRECT_DEBIT = 2;
74
75 /**
76 * Subscription / Recurring payment Status
77 * START, END
78 */
79 const
80 RECURRING_PAYMENT_START = 'START',
81 RECURRING_PAYMENT_END = 'END';
82
83 /**
84 * @var array
85 */
86 protected $_paymentProcessor;
87
88 /**
89 * Base url of the calling form (offsite processors).
90 *
91 * @var string
92 */
93 protected $baseReturnUrl;
94
95 /**
96 * Return url upon success (offsite processors).
97 *
98 * @var string
99 */
100 protected $successUrl;
101
102 /**
103 * Return url upon failure (offsite processors).
104 *
105 * @var string
106 */
107 protected $cancelUrl;
108
109 /**
110 * Processor type label.
111 *
112 * (Deprecated parameter but used in some messages).
113 *
114 * @var string
115 * @deprecated
116 *
117 */
118 public $_processorName;
119
120 /**
121 * The profile configured to show on the billing form.
122 *
123 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
124 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
125 * requirements with the configured requirements.
126 *
127 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
128 * of fields.
129 *
130 * Note this change would probably include converting 'billing' to a reserved profile.
131 *
132 * @var int|string
133 */
134 protected $billingProfile;
135
136 /**
137 * Payment instrument ID.
138 *
139 * This is normally retrieved from the payment_processor table.
140 *
141 * @var int
142 */
143 protected $paymentInstrumentID;
144
145 /**
146 * Is this a back office transaction.
147 *
148 * @var bool
149 */
150 protected $backOffice = FALSE;
151
152 /**
153 * Contribution that is being paid.
154 *
155 * @var int
156 */
157 protected $contributionID;
158
159 /**
160 * Contact ID for payment.
161 *
162 * @var int
163 */
164 protected $contactID;
165
166 /**
167 * Recurring contribution that is being paid.
168 *
169 * @var int
170 */
171 protected $contributionRecurID;
172
173 /**
174 * Description of purchase.
175 *
176 * @var string
177 */
178 protected $description;
179
180 /**
181 * CiviCRM generated Invoice ID.
182 *
183 * @var string
184 */
185 protected $invoiceID;
186
187 /**
188 * Is this a recurring contribution.
189 *
190 * @var bool
191 */
192 protected $isRecur;
193
194 /**
195 * Payment processor generated string for charging.
196 *
197 * A payment token could be a single use token (e.g generated by
198 * a client side script) or a token that permits recurring or on demand charging.
199 *
200 * The key thing is it is passed to the processor in lieu of card details to
201 * initiate a payment.
202 *
203 * Generally if a processor is going to pass in a payment token generated through
204 * javascript it would add 'payment_token' to the array it returns in it's
205 * implementation of getPaymentFormFields. This will add a hidden 'payment_token' field to
206 * the form. A good example is client side encryption where credit card details are replaced by
207 * an encrypted token using a gateway provided javascript script. In this case the javascript will
208 * remove the credit card details from the form before submitting and populate the payment_token field.
209 *
210 * A more complex example is used by paypal checkout where the payment token is generated
211 * via a pre-approval process. In that case the doPreApproval function is called on the processor
212 * class to get information to then interact with paypal via js, finally getting a payment token.
213 * (at this stage the pre-approve api is not in core but that is likely to change - we just need
214 * to think about the permissions since we don't want to expose to anonymous user without thinking
215 * through any risk of credit-card testing using it.
216 *
217 * If the token is not totally transient it would be saved to civicrm_payment_token.token.
218 *
219 * @var string
220 */
221 protected $paymentToken;
222
223 /**
224 * Three digit currency code.
225 *
226 * @var string
227 */
228 protected $currency;
229
230 /**
231 * Payment processor generated string for the transaction ID.
232 *
233 * Note some gateways generate a reference for the order and one for the
234 * payment. This is for the payment reference and is saved to
235 * civicrm_financial_trxn.trxn_id.
236 *
237 * @var string
238 */
239 protected $transactionID;
240
241 /**
242 * Amount of money charged in fees by the payment processor.
243 *
244 * This is notified by (some) payment processers.
245 *
246 * @var float
247 */
248 protected $feeAmount;
249
250 /**
251 * Additional information returned by the payment processor regarding the payment outcome.
252 *
253 * This would normally be saved in civicrm_financial_trxn.trxn_result_code.
254 *
255 * @var string
256 */
257 protected $trxnResultCode;
258
259 /**
260 * Combined with recurFrequencyUnit this gives how often billing will take place.
261 *
262 * e.g every if this is 1 and recurFrequencyUnit is 'month' then it is every 1 month.
263 *
264 * @var int
265 */
266 protected $recurFrequencyInterval;
267
268 /**
269 * Combined with recurFrequencyInterval this gives how often billing will take place.
270 *
271 * e.g every if this is 'month' and recurFrequencyInterval is 1 then it is every 1 month.
272 *
273 * @var string
274 * month|day|year
275 */
276 protected $recurFrequencyUnit;
277
278 /**
279 * Passed in parameters.
280 *
281 * Using individual getters & setters is preferred but these will be used if
282 * they are not available.
283 *
284 * @var array
285 */
286 protected $inputParams = [];
287
288 /**
289 * @return int
290 */
291 public function getContactID(): int {
292 return $this->contactID ?? $this->inputParams['contactID'];
293 }
294
295 /**
296 * @param int $contactID
297 */
298 public function setContactID(int $contactID) {
299 $this->contactID = $contactID;
300 }
301
302 /**
303 * Getter for contributionRecurID.
304 *
305 * Ideally this would always be set by the calling function using the setting
306 * but we need to fall back to the historical passing on inputParams as a transition.
307 *
308 * In time we can add a notice if it's set in input params & not via a setter.
309 *
310 * @return int
311 */
312 public function getContributionRecurID(): int {
313 return $this->contributionRecurID ?? $this->inputParams['contributionRecurID'];
314 }
315
316 /**
317 * @param int $contributionRecurID
318 */
319 public function setContributionRecurID(int $contributionRecurID) {
320 $this->contributionRecurID = $contributionRecurID;
321 }
322
323 /**
324 * Getter for Payment Token.
325 *
326 * @return string
327 */
328 public function getPaymentToken(): string {
329 return $this->paymentToken ?? $this->inputParams['token'];
330 }
331
332 /**
333 * Setter for Payment Token.
334 *
335 * @param string $paymentToken
336 */
337 public function setPaymentToken(string $paymentToken) {
338 $this->paymentToken = $paymentToken;
339 }
340
341 /**
342 * Get gateway generated transaction ID.
343 *
344 * @return string
345 */
346 public function getTransactionID(): string {
347 return $this->transactionID;
348 }
349
350 /**
351 * Set gateway generated transaction ID for the payment.
352 *
353 * Note some gateways generate a reference for the order and one for the
354 * payment. This is for the payment reference and is saved to
355 * civicrm_financial_trxn.trxn_id.
356 *
357 * @param string $transactionID
358 */
359 public function setTransactionID(string $transactionID) {
360 $this->transactionID = $transactionID;
361 }
362
363 /**
364 * Get additional result information received from gateway.
365 *
366 * This is saved to civicrm_financial_trxn.trxn_result_code.
367 *
368 * @return string
369 */
370 public function getTrxnResultCode(): string {
371 return $this->trxnResultCode;
372 }
373
374 /**
375 * Set additional result information from gateway.
376 *
377 * This is saved to civicrm_financial_trxn.trxn_result_code.
378 *
379 * @param string $resultCode
380 */
381 public function setTrxnResultCode(string $resultCode) {
382 $this->trxnResultCode = $resultCode;
383 }
384
385 /**
386 * Get recurring frequency interval.
387 *
388 * @return int
389 */
390 public function getRecurFrequencyInterval(): int {
391 return $this->recurFrequencyInterval ?? $this->inputParams['frequency_interval'];
392 }
393
394 /**
395 * Set recurring frequency interval.
396 *
397 * @param int $recurFrequencyInterval
398 */
399 public function setRecurFrequencyInterval(int $recurFrequencyInterval) {
400 $this->recurFrequencyInterval = $recurFrequencyInterval;
401 }
402
403 /**
404 * Get recurring frequency unit.
405 *
406 * @return string
407 */
408 public function getRecurFrequencyUnit(): string {
409 return $this->recurFrequencyUnit;
410 }
411
412 /**
413 * Set recurring frequency unit.
414 *
415 * @param string $recurFrequencyUnit
416 */
417 public function setRecurFrequencyUnit(string $recurFrequencyUnit) {
418 $this->recurFrequencyUnit = $recurFrequencyUnit ?? $this->inputParams['frequency_unit'];
419 }
420
421 /**
422 * Get invoice ID (CiviCRM generated invoice reference).
423 *
424 * @return string
425 */
426 public function getInvoiceID(): string {
427 return $this->invoiceID ?? $this->inputParams['invoiceID'];
428 }
429
430 /**
431 * Set invoice ID (CiviCRM generated invoice reference).
432 *
433 * @param string $invoiceID
434 */
435 public function setInvoiceID(string $invoiceID) {
436 $this->invoiceID = $invoiceID;
437 }
438
439 /**
440 * Get whether the payment is recurring.
441 *
442 * @return bool
443 */
444 public function isRecur(): bool {
445 return $this->isRecur;
446 }
447
448 /**
449 * Set whether the payment is recurring.
450 *
451 * @param bool $isRecur
452 */
453 public function setIsRecur(bool $isRecur) {
454 $this->isRecur = $isRecur ?? $this->inputParams['is_recur'];
455 }
456
457 /**
458 * Get the description.
459 *
460 * This generates a description string from params if one has been passed in but
461 * ideally calling functions would use the setDescription function.
462 *
463 * @return string
464 */
465 public function getDescription(): string {
466 if ($this->description) {
467 return $this->description;
468 }
469 if (isset($this->inputParams['description'])) {
470 $uninformativeStrings = [
471 ts('Online Event Registration: '),
472 ts('Online Contribution: '),
473 ];
474 $this->description = str_replace($uninformativeStrings, '', $this->inputParams['description']);
475 }
476 return $this->description;
477 }
478
479 /**
480 * Set description.
481 *
482 * Generally this should be called when instantiating the processor to override
483 * getPaymentDescription, if desired.
484 *
485 * @param string $description
486 */
487 public function setDescription(string $description) {
488 $this->description = $description;
489 }
490
491 /**
492 * Get fee amount returned by processor.
493 *
494 * @return float
495 */
496 public function getFeeAmount(): float {
497 return $this->feeAmount;
498 }
499
500 /**
501 * Set fee amount returned by processor.
502 *
503 * @param float $feeAmount
504 */
505 public function setFeeAmount(float $feeAmount) {
506 $this->feeAmount = $feeAmount;
507 }
508
509 /**
510 * Get the contribution ID.
511 *
512 * We prefer the one set by the setter but traditional forms just pass in 'contributionID'.
513 *
514 * @return int
515 */
516 public function getContributionID(): int {
517 return $this->contributionID ?? $this->inputParams['contributionID'];
518 }
519
520 /**
521 * @param int $contributionID
522 */
523 public function setContributionID(int $contributionID) {
524 $this->contributionID = $contributionID;
525 }
526
527 /**
528 * @return bool
529 */
530 public function isBackOffice() {
531 return $this->backOffice;
532 }
533
534 /**
535 * Set back office property.
536 *
537 * @param bool $isBackOffice
538 */
539 public function setBackOffice($isBackOffice) {
540 $this->backOffice = $isBackOffice;
541 }
542
543 /**
544 * Get payment instrument id.
545 *
546 * @return int
547 */
548 public function getPaymentInstrumentID() {
549 return $this->paymentInstrumentID ? $this->paymentInstrumentID : $this->_paymentProcessor['payment_instrument_id'];
550 }
551
552 /**
553 * Getter for the id.
554 *
555 * @return int
556 */
557 public function getID() {
558 return (int) $this->_paymentProcessor['id'];
559 }
560
561 /**
562 * Set payment Instrument id.
563 *
564 * By default we actually ignore the form value. The manual processor takes it more seriously.
565 *
566 * @param int $paymentInstrumentID
567 */
568 public function setPaymentInstrumentID($paymentInstrumentID) {
569 $this->paymentInstrumentID = $this->_paymentProcessor['payment_instrument_id'];
570 }
571
572 /**
573 * Set base return path (offsite processors).
574 *
575 * This is only useful with an internal civicrm form.
576 *
577 * @param string $url
578 * Internal civicrm path.
579 */
580 public function setBaseReturnUrl($url) {
581 $this->baseReturnUrl = $url;
582 }
583
584 /**
585 * Set success return URL (offsite processors).
586 *
587 * This overrides $baseReturnUrl
588 *
589 * @param string $url
590 * Full url of site to return browser to upon success.
591 */
592 public function setSuccessUrl($url) {
593 $this->successUrl = $url;
594 }
595
596 /**
597 * Set cancel return URL (offsite processors).
598 *
599 * This overrides $baseReturnUrl
600 *
601 * @param string $url
602 * Full url of site to return browser to upon failure.
603 */
604 public function setCancelUrl($url) {
605 $this->cancelUrl = $url;
606 }
607
608 /**
609 * Set the configured payment profile.
610 *
611 * @param int|string $value
612 */
613 public function setBillingProfile($value) {
614 $this->billingProfile = $value;
615 }
616
617 /**
618 * Opportunity for the payment processor to override the entire form build.
619 *
620 * @param CRM_Core_Form $form
621 *
622 * @return bool
623 * Should form building stop at this point?
624 */
625 public function buildForm(&$form) {
626 return FALSE;
627 }
628
629 /**
630 * Log payment notification message to forensic system log.
631 *
632 * @todo move to factory class \Civi\Payment\System (or similar)
633 *
634 * @param array $params
635 */
636 public static function logPaymentNotification($params) {
637 $message = 'payment_notification ';
638 if (!empty($params['processor_name'])) {
639 $message .= 'processor_name=' . $params['processor_name'];
640 }
641 if (!empty($params['processor_id'])) {
642 $message .= 'processor_id=' . $params['processor_id'];
643 }
644
645 $log = new CRM_Utils_SystemLogger();
646 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
647 $rawRequestData = file_get_contents("php://input");
648 if (CRM_Utils_JSON::isValidJSON($rawRequestData)) {
649 $log->alert($message, json_decode($rawRequestData, TRUE));
650 }
651 else {
652 $log->alert($message, $_REQUEST);
653 }
654 }
655
656 /**
657 * Check if capability is supported.
658 *
659 * Capabilities have a one to one relationship with capability-related functions on this class.
660 *
661 * Payment processor classes should over-ride the capability-specific function rather than this one.
662 *
663 * @param string $capability
664 * E.g BackOffice, LiveMode, FutureRecurStartDate.
665 *
666 * @return bool
667 */
668 public function supports($capability) {
669 $function = 'supports' . ucfirst($capability);
670 if (method_exists($this, $function)) {
671 return $this->$function();
672 }
673 return FALSE;
674 }
675
676 /**
677 * Are back office payments supported.
678 *
679 * e.g paypal standard won't permit you to enter a credit card associated
680 * with someone else's login.
681 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
682 * reach a 'stable' point we disable.
683 *
684 * @return bool
685 */
686 protected function supportsBackOffice() {
687 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
688 return FALSE;
689 }
690 else {
691 return TRUE;
692 }
693 }
694
695 /**
696 * Can more than one transaction be processed at once?
697 *
698 * In general processors that process payment by server to server communication support this while others do not.
699 *
700 * In future we are likely to hit an issue where this depends on whether a token already exists.
701 *
702 * @return bool
703 */
704 protected function supportsMultipleConcurrentPayments() {
705 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
706 return FALSE;
707 }
708 else {
709 return TRUE;
710 }
711 }
712
713 /**
714 * Are live payments supported - e.g dummy doesn't support this.
715 *
716 * @return bool
717 */
718 protected function supportsLiveMode() {
719 return TRUE;
720 }
721
722 /**
723 * Are test payments supported.
724 *
725 * @return bool
726 */
727 protected function supportsTestMode() {
728 return TRUE;
729 }
730
731 /**
732 * Does this payment processor support refund?
733 *
734 * @return bool
735 */
736 public function supportsRefund() {
737 return FALSE;
738 }
739
740 /**
741 * Should the first payment date be configurable when setting up back office recurring payments.
742 *
743 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
744 *
745 * @return bool
746 */
747 protected function supportsFutureRecurStartDate() {
748 return FALSE;
749 }
750
751 /**
752 * Does this processor support cancelling recurring contributions through code.
753 *
754 * If the processor returns true it must be possible to take action from within CiviCRM
755 * that will result in no further payments being processed. In the case of token processors (e.g
756 * IATS, eWay) updating the contribution_recur table is probably sufficient.
757 *
758 * @return bool
759 */
760 protected function supportsCancelRecurring() {
761 return method_exists(CRM_Utils_System::getClassName($this), 'cancelSubscription');
762 }
763
764 /**
765 * Does this processor support pre-approval.
766 *
767 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
768 *
769 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
770 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
771 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
772 *
773 * @return bool
774 */
775 protected function supportsPreApproval() {
776 return FALSE;
777 }
778
779 /**
780 * Does this processor support updating billing info for recurring contributions through code.
781 *
782 * If the processor returns true then it must be possible to update billing info from within CiviCRM
783 * that will be updated at the payment processor.
784 *
785 * @return bool
786 */
787 protected function supportsUpdateSubscriptionBillingInfo() {
788 return method_exists(CRM_Utils_System::getClassName($this), 'updateSubscriptionBillingInfo');
789 }
790
791 /**
792 * Can recurring contributions be set against pledges.
793 *
794 * In practice all processors that use the baseIPN function to finish transactions or
795 * call the completetransaction api support this by looking up previous contributions in the
796 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
797 * adding the new payment to the pledge.
798 *
799 * However, only enabling for processors it has been tested against.
800 *
801 * @return bool
802 */
803 protected function supportsRecurContributionsForPledges() {
804 return FALSE;
805 }
806
807 /**
808 * Function to action pre-approval if supported
809 *
810 * @param array $params
811 * Parameters from the form
812 *
813 * This function returns an array which should contain
814 * - pre_approval_parameters (this will be stored on the calling form & available later)
815 * - redirect_url (if set the browser will be redirected to this.
816 */
817 public function doPreApproval(&$params) {
818 }
819
820 /**
821 * Get any details that may be available to the payment processor due to an approval process having happened.
822 *
823 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
824 * result.
825 *
826 * @param array $storedDetails
827 *
828 * @return array
829 */
830 public function getPreApprovalDetails($storedDetails) {
831 return [];
832 }
833
834 /**
835 * Default payment instrument validation.
836 *
837 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
838 * Not a static function, because I need to check for payment_type.
839 *
840 * @param array $values
841 * @param array $errors
842 */
843 public function validatePaymentInstrument($values, &$errors) {
844 CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
845 if ($this->_paymentProcessor['payment_type'] == 1) {
846 CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
847 }
848 }
849
850 /**
851 * Getter for the payment processor.
852 *
853 * The payment processor array is based on the civicrm_payment_processor table entry.
854 *
855 * @return array
856 * Payment processor array.
857 */
858 public function getPaymentProcessor() {
859 return $this->_paymentProcessor;
860 }
861
862 /**
863 * Setter for the payment processor.
864 *
865 * @param array $processor
866 */
867 public function setPaymentProcessor($processor) {
868 $this->_paymentProcessor = $processor;
869 }
870
871 /**
872 * Setter for the payment form that wants to use the processor.
873 *
874 * @deprecated
875 *
876 * @param CRM_Core_Form $paymentForm
877 */
878 public function setForm(&$paymentForm) {
879 $this->_paymentForm = $paymentForm;
880 }
881
882 /**
883 * Getter for payment form that is using the processor.
884 * @deprecated
885 * @return CRM_Core_Form
886 * A form object
887 */
888 public function getForm() {
889 return $this->_paymentForm;
890 }
891
892 /**
893 * Get help text information (help, description, etc.) about this payment,
894 * to display to the user.
895 *
896 * @param string $context
897 * Context of the text.
898 * Only explicitly supported contexts are handled without error.
899 * Currently supported:
900 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
901 *
902 * @param array $params
903 * Parameters for the field, context specific.
904 *
905 * @return string
906 */
907 public function getText($context, $params) {
908 // I have deliberately added a noisy fail here.
909 // The function is intended to be extendable, but not by changes
910 // not documented clearly above.
911 switch ($context) {
912 case 'contributionPageRecurringHelp':
913 // require exactly two parameters
914 if (array_keys($params) == [
915 'is_recur_installments',
916 'is_email_receipt',
917 ]) {
918 $gotText = ts('Your recurring contribution will be processed automatically.');
919 if ($params['is_recur_installments']) {
920 $gotText .= ' ' . ts('You can specify the number of installments, or you can leave the number of installments blank if you want to make an open-ended commitment. In either case, you can choose to cancel at any time.');
921 }
922 if ($params['is_email_receipt']) {
923 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
924 }
925 }
926 return $gotText;
927
928 case 'contributionPageContinueText':
929 if ($params['amount'] <= 0) {
930 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
931 }
932 if ($this->_paymentProcessor['billing_mode'] == 4) {
933 return ts('Click the <strong>Continue</strong> button to go to %1, where you will select your payment method and complete the contribution.', [$this->_paymentProcessor['payment_processor_type']]);
934 }
935 if ($params['is_payment_to_existing']) {
936 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
937 }
938 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
939
940 }
941 CRM_Core_Error::deprecatedFunctionWarning('Calls to getText must use a supported method');
942 return '';
943 }
944
945 /**
946 * Getter for accessing member vars.
947 *
948 * @todo believe this is unused
949 *
950 * @param string $name
951 *
952 * @return null
953 */
954 public function getVar($name) {
955 return isset($this->$name) ? $this->$name : NULL;
956 }
957
958 /**
959 * Get name for the payment information type.
960 * @todo - use option group + name field (like Omnipay does)
961 * @return string
962 */
963 public function getPaymentTypeName() {
964 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
965 }
966
967 /**
968 * Get label for the payment information type.
969 * @todo - use option group + labels (like Omnipay does)
970 * @return string
971 */
972 public function getPaymentTypeLabel() {
973 return $this->_paymentProcessor['payment_type'] == 1 ? ts('Credit Card') : ts('Direct Debit');
974 }
975
976 /**
977 * Get array of fields that should be displayed on the payment form.
978 *
979 * Common results are
980 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
981 * or
982 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
983 * or
984 * array()
985 *
986 * @return array
987 * Array of payment fields appropriate to the payment processor.
988 *
989 * @throws CiviCRM_API3_Exception
990 */
991 public function getPaymentFormFields() {
992 if ($this->_paymentProcessor['billing_mode'] == 4) {
993 return [];
994 }
995 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
996 }
997
998 /**
999 * Get an array of the fields that can be edited on the recurring contribution.
1000 *
1001 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
1002 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
1003 * can be updated from the contribution recur edit screen.
1004 *
1005 * The fields are likely to be a subset of these
1006 * - 'amount',
1007 * - 'installments',
1008 * - 'frequency_interval',
1009 * - 'frequency_unit',
1010 * - 'cycle_day',
1011 * - 'next_sched_contribution_date',
1012 * - 'end_date',
1013 * - 'failure_retry_day',
1014 *
1015 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
1016 * metadata is not defined in the xml for the field it will cause an error.
1017 *
1018 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
1019 * form (UpdateSubscription).
1020 *
1021 * @return array
1022 */
1023 public function getEditableRecurringScheduleFields() {
1024 if ($this->supports('changeSubscriptionAmount')) {
1025 return ['amount'];
1026 }
1027 return [];
1028 }
1029
1030 /**
1031 * Get the help text to present on the recurring update page.
1032 *
1033 * This should reflect what can or cannot be edited.
1034 *
1035 * @return string
1036 */
1037 public function getRecurringScheduleUpdateHelpText() {
1038 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
1039 return ts('Updates made using this form will change the recurring contribution information stored in your CiviCRM database, but will NOT be sent to the payment processor. You must enter the same changes using the payment processor web site.');
1040 }
1041 return ts('Use this form to change the amount or number of installments for this recurring contribution. Changes will be automatically sent to the payment processor. You can not change the contribution frequency.');
1042 }
1043
1044 /**
1045 * Get the metadata for all required fields.
1046 *
1047 * @return array;
1048 */
1049 protected function getMandatoryFields() {
1050 $mandatoryFields = [];
1051 foreach ($this->getAllFields() as $field_name => $field_spec) {
1052 if (!empty($field_spec['is_required'])) {
1053 $mandatoryFields[$field_name] = $field_spec;
1054 }
1055 }
1056 return $mandatoryFields;
1057 }
1058
1059 /**
1060 * Get the metadata of all the fields configured for this processor.
1061 *
1062 * @return array
1063 *
1064 * @throws \CiviCRM_API3_Exception
1065 */
1066 protected function getAllFields() {
1067 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
1068 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
1069 return array_merge($paymentFields, $billingFields);
1070 }
1071
1072 /**
1073 * Get array of fields that should be displayed on the payment form for credit cards.
1074 *
1075 * @return array
1076 */
1077 protected function getCreditCardFormFields() {
1078 return [
1079 'credit_card_type',
1080 'credit_card_number',
1081 'cvv2',
1082 'credit_card_exp_date',
1083 ];
1084 }
1085
1086 /**
1087 * Get array of fields that should be displayed on the payment form for direct debits.
1088 *
1089 * @return array
1090 */
1091 protected function getDirectDebitFormFields() {
1092 return [
1093 'account_holder',
1094 'bank_account_number',
1095 'bank_identification_number',
1096 'bank_name',
1097 ];
1098 }
1099
1100 /**
1101 * Return an array of all the details about the fields potentially required for payment fields.
1102 *
1103 * Only those determined by getPaymentFormFields will actually be assigned to the form
1104 *
1105 * @return array
1106 * field metadata
1107 *
1108 * @throws \Exception
1109 */
1110 public function getPaymentFormFieldsMetadata() {
1111 //@todo convert credit card type into an option value
1112 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::creditCard();
1113 $isCVVRequired = Civi::settings()->get('cvv_backoffice_required');
1114 if (!$this->isBackOffice()) {
1115 $isCVVRequired = TRUE;
1116 }
1117 return [
1118 'credit_card_number' => [
1119 'htmlType' => 'text',
1120 'name' => 'credit_card_number',
1121 'title' => ts('Card Number'),
1122 'attributes' => [
1123 'size' => 20,
1124 'maxlength' => 20,
1125 'autocomplete' => 'off',
1126 'class' => 'creditcard',
1127 ],
1128 'is_required' => TRUE,
1129 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
1130 ],
1131 'cvv2' => [
1132 'htmlType' => 'text',
1133 'name' => 'cvv2',
1134 'title' => ts('Security Code'),
1135 'attributes' => [
1136 'size' => 5,
1137 'maxlength' => 10,
1138 'autocomplete' => 'off',
1139 ],
1140 'is_required' => $isCVVRequired,
1141 'rules' => [
1142 [
1143 'rule_message' => ts('Please enter a valid value for your card security code. This is usually the last 3-4 digits on the card\'s signature panel.'),
1144 'rule_name' => 'integer',
1145 'rule_parameters' => NULL,
1146 ],
1147 ],
1148 ],
1149 'credit_card_exp_date' => [
1150 'htmlType' => 'date',
1151 'name' => 'credit_card_exp_date',
1152 'title' => ts('Expiration Date'),
1153 'attributes' => CRM_Core_SelectValues::date('creditCard'),
1154 'is_required' => TRUE,
1155 'rules' => [
1156 [
1157 'rule_message' => ts('Card expiration date cannot be a past date.'),
1158 'rule_name' => 'currentDate',
1159 'rule_parameters' => TRUE,
1160 ],
1161 ],
1162 'extra' => ['class' => 'crm-form-select'],
1163 ],
1164 'credit_card_type' => [
1165 'htmlType' => 'select',
1166 'name' => 'credit_card_type',
1167 'title' => ts('Card Type'),
1168 'attributes' => $creditCardType,
1169 'is_required' => FALSE,
1170 ],
1171 'account_holder' => [
1172 'htmlType' => 'text',
1173 'name' => 'account_holder',
1174 'title' => ts('Account Holder'),
1175 'attributes' => [
1176 'size' => 20,
1177 'maxlength' => 34,
1178 'autocomplete' => 'on',
1179 ],
1180 'is_required' => TRUE,
1181 ],
1182 //e.g. IBAN can have maxlength of 34 digits
1183 'bank_account_number' => [
1184 'htmlType' => 'text',
1185 'name' => 'bank_account_number',
1186 'title' => ts('Bank Account Number'),
1187 'attributes' => [
1188 'size' => 20,
1189 'maxlength' => 34,
1190 'autocomplete' => 'off',
1191 ],
1192 'rules' => [
1193 [
1194 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
1195 'rule_name' => 'nopunctuation',
1196 'rule_parameters' => NULL,
1197 ],
1198 ],
1199 'is_required' => TRUE,
1200 ],
1201 //e.g. SWIFT-BIC can have maxlength of 11 digits
1202 'bank_identification_number' => [
1203 'htmlType' => 'text',
1204 'name' => 'bank_identification_number',
1205 'title' => ts('Bank Identification Number'),
1206 'attributes' => [
1207 'size' => 20,
1208 'maxlength' => 11,
1209 'autocomplete' => 'off',
1210 ],
1211 'is_required' => TRUE,
1212 'rules' => [
1213 [
1214 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
1215 'rule_name' => 'nopunctuation',
1216 'rule_parameters' => NULL,
1217 ],
1218 ],
1219 ],
1220 'bank_name' => [
1221 'htmlType' => 'text',
1222 'name' => 'bank_name',
1223 'title' => ts('Bank Name'),
1224 'attributes' => [
1225 'size' => 20,
1226 'maxlength' => 64,
1227 'autocomplete' => 'off',
1228 ],
1229 'is_required' => TRUE,
1230
1231 ],
1232 'check_number' => [
1233 'htmlType' => 'text',
1234 'name' => 'check_number',
1235 'title' => ts('Check Number'),
1236 'is_required' => FALSE,
1237 'attributes' => NULL,
1238 ],
1239 'pan_truncation' => [
1240 'htmlType' => 'text',
1241 'name' => 'pan_truncation',
1242 'title' => ts('Last 4 digits of the card'),
1243 'is_required' => FALSE,
1244 'attributes' => [
1245 'size' => 4,
1246 'maxlength' => 4,
1247 'minlength' => 4,
1248 'autocomplete' => 'off',
1249 ],
1250 'rules' => [
1251 [
1252 'rule_message' => ts('Please enter valid last 4 digit card number.'),
1253 'rule_name' => 'numeric',
1254 'rule_parameters' => NULL,
1255 ],
1256 ],
1257 ],
1258 'payment_token' => [
1259 'htmlType' => 'hidden',
1260 'name' => 'payment_token',
1261 'title' => ts('Authorization token'),
1262 'is_required' => FALSE,
1263 'attributes' => [
1264 'size' => 10,
1265 'autocomplete' => 'off',
1266 'id' => 'payment_token',
1267 ],
1268 ],
1269 ];
1270 }
1271
1272 /**
1273 * Get billing fields required for this processor.
1274 *
1275 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
1276 * alter.
1277 *
1278 * @param int $billingLocationID
1279 *
1280 * @return array
1281 */
1282 public function getBillingAddressFields($billingLocationID = NULL) {
1283 if (!$billingLocationID) {
1284 // Note that although the billing id is passed around the forms the idea that it would be anything other than
1285 // the result of the function below doesn't seem to have eventuated.
1286 // So taking this as a param is possibly something to be removed in favour of the standard default.
1287 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
1288 }
1289 if ($this->_paymentProcessor['billing_mode'] != 1 && $this->_paymentProcessor['billing_mode'] != 3) {
1290 return [];
1291 }
1292 return [
1293 'first_name' => 'billing_first_name',
1294 'middle_name' => 'billing_middle_name',
1295 'last_name' => 'billing_last_name',
1296 'street_address' => "billing_street_address-{$billingLocationID}",
1297 'city' => "billing_city-{$billingLocationID}",
1298 'country' => "billing_country_id-{$billingLocationID}",
1299 'state_province' => "billing_state_province_id-{$billingLocationID}",
1300 'postal_code' => "billing_postal_code-{$billingLocationID}",
1301 ];
1302 }
1303
1304 /**
1305 * Get form metadata for billing address fields.
1306 *
1307 * @param int $billingLocationID
1308 *
1309 * @return array
1310 * Array of metadata for address fields.
1311 */
1312 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
1313 if (!$billingLocationID) {
1314 // Note that although the billing id is passed around the forms the idea that it would be anything other than
1315 // the result of the function below doesn't seem to have eventuated.
1316 // So taking this as a param is possibly something to be removed in favour of the standard default.
1317 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
1318 }
1319 $metadata = [];
1320 $metadata['billing_first_name'] = [
1321 'htmlType' => 'text',
1322 'name' => 'billing_first_name',
1323 'title' => ts('Billing First Name'),
1324 'cc_field' => TRUE,
1325 'attributes' => [
1326 'size' => 30,
1327 'maxlength' => 60,
1328 'autocomplete' => 'off',
1329 ],
1330 'is_required' => TRUE,
1331 ];
1332
1333 $metadata['billing_middle_name'] = [
1334 'htmlType' => 'text',
1335 'name' => 'billing_middle_name',
1336 'title' => ts('Billing Middle Name'),
1337 'cc_field' => TRUE,
1338 'attributes' => [
1339 'size' => 30,
1340 'maxlength' => 60,
1341 'autocomplete' => 'off',
1342 ],
1343 'is_required' => FALSE,
1344 ];
1345
1346 $metadata['billing_last_name'] = [
1347 'htmlType' => 'text',
1348 'name' => 'billing_last_name',
1349 'title' => ts('Billing Last Name'),
1350 'cc_field' => TRUE,
1351 'attributes' => [
1352 'size' => 30,
1353 'maxlength' => 60,
1354 'autocomplete' => 'off',
1355 ],
1356 'is_required' => TRUE,
1357 ];
1358
1359 $metadata["billing_street_address-{$billingLocationID}"] = [
1360 'htmlType' => 'text',
1361 'name' => "billing_street_address-{$billingLocationID}",
1362 'title' => ts('Street Address'),
1363 'cc_field' => TRUE,
1364 'attributes' => [
1365 'size' => 30,
1366 'maxlength' => 60,
1367 'autocomplete' => 'off',
1368 ],
1369 'is_required' => TRUE,
1370 ];
1371
1372 $metadata["billing_city-{$billingLocationID}"] = [
1373 'htmlType' => 'text',
1374 'name' => "billing_city-{$billingLocationID}",
1375 'title' => ts('City'),
1376 'cc_field' => TRUE,
1377 'attributes' => [
1378 'size' => 30,
1379 'maxlength' => 60,
1380 'autocomplete' => 'off',
1381 ],
1382 'is_required' => TRUE,
1383 ];
1384
1385 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1386 'htmlType' => 'chainSelect',
1387 'title' => ts('State/Province'),
1388 'name' => "billing_state_province_id-{$billingLocationID}",
1389 'cc_field' => TRUE,
1390 'is_required' => TRUE,
1391 ];
1392
1393 $metadata["billing_postal_code-{$billingLocationID}"] = [
1394 'htmlType' => 'text',
1395 'name' => "billing_postal_code-{$billingLocationID}",
1396 'title' => ts('Postal Code'),
1397 'cc_field' => TRUE,
1398 'attributes' => [
1399 'size' => 30,
1400 'maxlength' => 60,
1401 'autocomplete' => 'off',
1402 ],
1403 'is_required' => TRUE,
1404 ];
1405
1406 $metadata["billing_country_id-{$billingLocationID}"] = [
1407 'htmlType' => 'select',
1408 'name' => "billing_country_id-{$billingLocationID}",
1409 'title' => ts('Country'),
1410 'cc_field' => TRUE,
1411 'attributes' => [
1412 '' => ts('- select -'),
1413 ] + CRM_Core_PseudoConstant::country(),
1414 'is_required' => TRUE,
1415 ];
1416 return $metadata;
1417 }
1418
1419 /**
1420 * Get base url dependent on component.
1421 *
1422 * (or preferably set it using the setter function).
1423 *
1424 * @return string
1425 */
1426 protected function getBaseReturnUrl() {
1427 if ($this->baseReturnUrl) {
1428 return $this->baseReturnUrl;
1429 }
1430 if ($this->_component == 'event') {
1431 $baseURL = 'civicrm/event/register';
1432 }
1433 else {
1434 $baseURL = 'civicrm/contribute/transact';
1435 }
1436 return $baseURL;
1437 }
1438
1439 /**
1440 * Get the currency for the transaction.
1441 *
1442 * Handle any inconsistency about how it is passed in here.
1443 *
1444 * @param $params
1445 *
1446 * @return string
1447 */
1448 protected function getCurrency($params = []) {
1449 $params = array_merge($params, (array) $this->inputParams);
1450 return $this->currency ?? CRM_Utils_Array::value('currencyID', $params, CRM_Utils_Array::value('currency', $params));
1451 }
1452
1453 /**
1454 * Get the currency for the transaction.
1455 *
1456 * Handle any inconsistency about how it is passed in here.
1457 *
1458 * @param array $params
1459 *
1460 * @return string
1461 * @throws \CRM_Core_Exception
1462 */
1463 protected function getAmount($params = []) {
1464 $amount = $this->amount ?? $params['amount'];
1465 return CRM_Utils_Money::format($amount, NULL, NULL, TRUE);
1466 }
1467
1468 /**
1469 * Get url to return to after cancelled or failed transaction.
1470 *
1471 * @param string $qfKey
1472 * @param int $participantID
1473 *
1474 * @return string cancel url
1475 */
1476 public function getCancelUrl($qfKey, $participantID) {
1477 if (isset($this->cancelUrl)) {
1478 return $this->cancelUrl;
1479 }
1480
1481 if ($this->_component == 'event') {
1482 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1483 'reset' => 1,
1484 'cc' => 'fail',
1485 'participantId' => $participantID,
1486 ],
1487 TRUE, NULL, FALSE
1488 );
1489 }
1490
1491 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1492 '_qf_Main_display' => 1,
1493 'qfKey' => $qfKey,
1494 'cancel' => 1,
1495 ],
1496 TRUE, NULL, FALSE
1497 );
1498 }
1499
1500 /**
1501 * Get URL to return the browser to on success.
1502 *
1503 * @param $qfKey
1504 *
1505 * @return string
1506 */
1507 protected function getReturnSuccessUrl($qfKey) {
1508 if (isset($this->successUrl)) {
1509 return $this->successUrl;
1510 }
1511
1512 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1513 '_qf_ThankYou_display' => 1,
1514 'qfKey' => $qfKey,
1515 ],
1516 TRUE, NULL, FALSE
1517 );
1518 }
1519
1520 /**
1521 * Get URL to return the browser to on failure.
1522 *
1523 * @param string $key
1524 * @param int $participantID
1525 * @param int $eventID
1526 *
1527 * @return string
1528 * URL for a failing transactor to be redirected to.
1529 */
1530 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1531 if (isset($this->cancelUrl)) {
1532 return $this->cancelUrl;
1533 }
1534
1535 $test = $this->_is_test ? '&action=preview' : '';
1536 if ($this->_component == "event") {
1537 return CRM_Utils_System::url('civicrm/event/register',
1538 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1539 FALSE, NULL, FALSE
1540 );
1541 }
1542 else {
1543 return CRM_Utils_System::url('civicrm/contribute/transact',
1544 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1545 FALSE, NULL, FALSE
1546 );
1547 }
1548 }
1549
1550 /**
1551 * Get URl for when the back button is pressed.
1552 *
1553 * @param $qfKey
1554 *
1555 * @return string url
1556 */
1557 protected function getGoBackUrl($qfKey) {
1558 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1559 '_qf_Confirm_display' => 'true',
1560 'qfKey' => $qfKey,
1561 ],
1562 TRUE, NULL, FALSE
1563 );
1564 }
1565
1566 /**
1567 * Get the notify (aka ipn, web hook or silent post) url.
1568 *
1569 * If there is no '.' in it we assume that we are dealing with localhost or
1570 * similar and it is unreachable from the web & hence invalid.
1571 *
1572 * @return string
1573 * URL to notify outcome of transaction.
1574 */
1575 protected function getNotifyUrl() {
1576 $url = CRM_Utils_System::url(
1577 'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
1578 [],
1579 TRUE,
1580 NULL,
1581 FALSE,
1582 TRUE
1583 );
1584 return (stristr($url, '.')) ? $url : '';
1585 }
1586
1587 /**
1588 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1589 * @deprecated
1590 * Does a server to server payment transaction.
1591 *
1592 * @param array $params
1593 * Assoc array of input parameters for this transaction.
1594 *
1595 * @return array
1596 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1597 */
1598 protected function doDirectPayment(&$params) {
1599 return $params;
1600 }
1601
1602 /**
1603 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1604 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1605 *
1606 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1607 * the transaction & in fact doTransferCheckout would not traditionally come back.
1608 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1609 *
1610 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1611 * In some cases the IPN will set the payment to "Completed" some time later.
1612 *
1613 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1614 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1615 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1616 *
1617 * @param array $params
1618 *
1619 * @param string $component
1620 *
1621 * @return array
1622 * Result array (containing at least the key payment_status_id)
1623 *
1624 * @throws \Civi\Payment\Exception\PaymentProcessorException
1625 */
1626 public function doPayment(&$params, $component = 'contribute') {
1627 $this->inputParams = $params;
1628 $this->_component = $component;
1629 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
1630
1631 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1632 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1633 // have an example of that at the mome.
1634 if ($params['amount'] == 0) {
1635 $result['payment_status_id'] = array_search('Completed', $statuses);
1636 return $result;
1637 }
1638
1639 if ($this->_paymentProcessor['billing_mode'] == 4) {
1640 $result = $this->doTransferCheckout($params, $component);
1641 if (is_array($result) && !isset($result['payment_status_id'])) {
1642 $result['payment_status_id'] = array_search('Pending', $statuses);
1643 }
1644 }
1645 else {
1646 $result = $this->doDirectPayment($params, $component);
1647 if (is_array($result) && !isset($result['payment_status_id'])) {
1648 if (!empty($params['is_recur'])) {
1649 // See comment block.
1650 $result['payment_status_id'] = array_search('Pending', $statuses);
1651 }
1652 else {
1653 $result['payment_status_id'] = array_search('Completed', $statuses);
1654 }
1655 }
1656 }
1657 if (is_a($result, 'CRM_Core_Error')) {
1658 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
1659 }
1660 return $result;
1661 }
1662
1663 /**
1664 * Refunds payment
1665 *
1666 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1667 *
1668 * @param array $params
1669 *
1670 * @throws \Civi\Payment\Exception\PaymentProcessorException
1671 */
1672 public function doRefund(&$params) {}
1673
1674 /**
1675 * Query payment processor for details about a transaction.
1676 *
1677 * @param array $params
1678 * Array of parameters containing one of:
1679 * - trxn_id Id of an individual transaction.
1680 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1681 *
1682 * @return array
1683 * Extra parameters retrieved.
1684 * Any parameters retrievable through this should be documented in the function comments at
1685 * CRM_Core_Payment::doQuery. Currently:
1686 * - fee_amount Amount of fee paid
1687 */
1688 public function doQuery($params) {
1689 return [];
1690 }
1691
1692 /**
1693 * This function checks to see if we have the right config values.
1694 *
1695 * @return string
1696 * the error message if any
1697 */
1698 abstract protected function checkConfig();
1699
1700 /**
1701 * Redirect for paypal.
1702 *
1703 * @todo move to paypal class or remove
1704 *
1705 * @param $paymentProcessor
1706 *
1707 * @return bool
1708 */
1709 public static function paypalRedirect(&$paymentProcessor) {
1710 if (!$paymentProcessor) {
1711 return FALSE;
1712 }
1713
1714 if (isset($_GET['payment_date']) &&
1715 isset($_GET['merchant_return_link']) &&
1716 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
1717 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1718 ) {
1719 return TRUE;
1720 }
1721
1722 return FALSE;
1723 }
1724
1725 /**
1726 * Handle incoming payment notification.
1727 *
1728 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1729 *
1730 * @todo move to0 \Civi\Payment\System factory method
1731 * Page callback for civicrm/payment/ipn
1732 */
1733 public static function handleIPN() {
1734 try {
1735 self::handlePaymentMethod(
1736 'PaymentNotification',
1737 [
1738 'processor_name' => CRM_Utils_Request::retrieveValue('processor_name', 'String'),
1739 'processor_id' => CRM_Utils_Request::retrieveValue('processor_id', 'Integer'),
1740 'mode' => CRM_Utils_Request::retrieveValue('mode', 'Alphanumeric'),
1741 ]
1742 );
1743 }
1744 catch (CRM_Core_Exception $e) {
1745 Civi::log()->error('ipn_payment_callback_exception', [
1746 'context' => [
1747 'backtrace' => CRM_Core_Error::formatBacktrace(debug_backtrace()),
1748 ],
1749 ]);
1750 }
1751 CRM_Utils_System::civiExit();
1752 }
1753
1754 /**
1755 * Payment callback handler.
1756 *
1757 * The processor_name or processor_id is passed in.
1758 * Note that processor_id is more reliable as one site may have more than one instance of a
1759 * processor & ideally the processor will be validating the results
1760 * Load requested payment processor and call that processor's handle<$method> method
1761 *
1762 * @todo move to \Civi\Payment\System factory method
1763 *
1764 * @param string $method
1765 * 'PaymentNotification' or 'PaymentCron'
1766 * @param array $params
1767 *
1768 * @throws \CRM_Core_Exception
1769 * @throws \Exception
1770 */
1771 public static function handlePaymentMethod($method, $params = []) {
1772 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1773 $q = explode('/', CRM_Utils_Array::value(CRM_Core_Config::singleton()->userFrameworkURLVar, $_GET, ''));
1774 $lastParam = array_pop($q);
1775 if (is_numeric($lastParam)) {
1776 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1777 }
1778 else {
1779 self::logPaymentNotification($params);
1780 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1781 }
1782 }
1783
1784 self::logPaymentNotification($params);
1785
1786 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1787 FROM civicrm_payment_processor_type ppt
1788 INNER JOIN civicrm_payment_processor pp
1789 ON pp.payment_processor_type_id = ppt.id
1790 AND pp.is_active";
1791
1792 if (isset($params['processor_id'])) {
1793 $sql .= " WHERE pp.id = %2";
1794 $args[2] = [$params['processor_id'], 'Integer'];
1795 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1796 }
1797 else {
1798 // This is called when processor_name is passed - passing processor_id instead is recommended.
1799 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1800 $args[1] = [
1801 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
1802 'Integer',
1803 ];
1804 $args[2] = [$params['processor_name'], 'String'];
1805 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1806 }
1807
1808 $dao = CRM_Core_DAO::executeQuery($sql, $args);
1809
1810 // Check whether we found anything at all.
1811 if (!$dao->N) {
1812 throw new CRM_Core_Exception($notFound);
1813 }
1814
1815 $method = 'handle' . $method;
1816 $extension_instance_found = FALSE;
1817
1818 // In all likelihood, we'll just end up with the one instance returned here. But it's
1819 // possible we may get more. Hence, iterate through all instances ..
1820
1821 while ($dao->fetch()) {
1822 // Check pp is extension - is this still required - surely the singleton below handles it.
1823 $ext = CRM_Extension_System::singleton()->getMapper();
1824 if ($ext->isExtensionKey($dao->class_name)) {
1825 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
1826 require_once $ext->classToPath($paymentClass);
1827 }
1828
1829 $processorInstance = System::singleton()->getById($dao->processor_id);
1830
1831 // Should never be empty - we already established this processor_id exists and is active.
1832 if (empty($processorInstance)) {
1833 continue;
1834 }
1835
1836 // Does PP implement this method, and can we call it?
1837 if (!method_exists($processorInstance, $method) ||
1838 !is_callable([$processorInstance, $method])
1839 ) {
1840 // on the off chance there is a double implementation of this processor we should keep looking for another
1841 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1842 continue;
1843 }
1844
1845 // Everything, it seems, is ok - execute pp callback handler
1846 $processorInstance->$method();
1847 $extension_instance_found = TRUE;
1848 }
1849
1850 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1851 $IPNParams = array_merge($_GET, $_REQUEST);
1852 CRM_Utils_Hook::postIPNProcess($IPNParams);
1853 if (!$extension_instance_found) {
1854 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1855 "%2 method is unsupported in legacy payment processors.";
1856 throw new CRM_Core_Exception(ts($message, [
1857 1 => $params['processor_name'],
1858 2 => $method,
1859 ]));
1860 }
1861 }
1862
1863 /**
1864 * Check whether a method is present ( & supported ) by the payment processor object.
1865 *
1866 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1867 *
1868 * @param string $method
1869 * Method to check for.
1870 *
1871 * @return bool
1872 */
1873 public function isSupported($method) {
1874 return method_exists(CRM_Utils_System::getClassName($this), $method);
1875 }
1876
1877 /**
1878 * Some processors replace the form submit button with their own.
1879 *
1880 * Returning false here will leave the button off front end forms.
1881 *
1882 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1883 */
1884 public function isSuppressSubmitButtons() {
1885 return FALSE;
1886 }
1887
1888 /**
1889 * Checks to see if invoice_id already exists in db.
1890 *
1891 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1892 * it is better to standardise to being here.
1893 *
1894 * @param int $invoiceId The ID to check.
1895 *
1896 * @param null $contributionID
1897 * If a contribution exists pass in the contribution ID.
1898 *
1899 * @return bool
1900 * True if invoice ID otherwise exists, else false
1901 */
1902 protected function checkDupe($invoiceId, $contributionID = NULL) {
1903 $contribution = new CRM_Contribute_DAO_Contribution();
1904 $contribution->invoice_id = $invoiceId;
1905 if ($contributionID) {
1906 $contribution->whereAdd("id <> $contributionID");
1907 }
1908 return $contribution->find();
1909 }
1910
1911 /**
1912 * Get url for users to manage this recurring contribution for this processor.
1913 *
1914 * @param int $entityID
1915 * @param null $entity
1916 * @param string $action
1917 *
1918 * @return string
1919 */
1920 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1921 // Set URL
1922 switch ($action) {
1923 case 'cancel':
1924 if (!$this->supports('cancelRecurring')) {
1925 return NULL;
1926 }
1927 $url = 'civicrm/contribute/unsubscribe';
1928 break;
1929
1930 case 'billing':
1931 //in notify mode don't return the update billing url
1932 if (!$this->supports('updateSubscriptionBillingInfo')) {
1933 return NULL;
1934 }
1935 $url = 'civicrm/contribute/updatebilling';
1936 break;
1937
1938 case 'update':
1939 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1940 return NULL;
1941 }
1942 $url = 'civicrm/contribute/updaterecur';
1943 break;
1944 }
1945
1946 $userId = CRM_Core_Session::singleton()->get('userID');
1947 $contactID = 0;
1948 $checksumValue = '';
1949 $entityArg = '';
1950
1951 // Find related Contact
1952 if ($entityID) {
1953 switch ($entity) {
1954 case 'membership':
1955 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1956 $entityArg = 'mid';
1957 break;
1958
1959 case 'contribution':
1960 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1961 $entityArg = 'coid';
1962 break;
1963
1964 case 'recur':
1965 $sql = "
1966 SELECT DISTINCT con.contact_id
1967 FROM civicrm_contribution_recur rec
1968 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1969 WHERE rec.id = %1";
1970 $contactID = CRM_Core_DAO::singleValueQuery($sql, [
1971 1 => [
1972 $entityID,
1973 'Integer',
1974 ],
1975 ]);
1976 $entityArg = 'crid';
1977 break;
1978 }
1979 }
1980
1981 // Add entity arguments
1982 if ($entityArg != '') {
1983 // Add checksum argument
1984 if ($contactID != 0 && $userId != $contactID) {
1985 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1986 }
1987 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1988 }
1989
1990 // Else login URL
1991 if ($this->supports('accountLoginURL')) {
1992 return $this->accountLoginURL();
1993 }
1994
1995 // Else default
1996 return isset($this->_paymentProcessor['url_recur']) ? $this->_paymentProcessor['url_recur'] : '';
1997 }
1998
1999 /**
2000 * Get description of payment to pass to processor.
2001 *
2002 * This is often what people see in the interface so we want to get
2003 * as much unique information in as possible within the field length (& presumably the early part of the field)
2004 *
2005 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
2006 * having field names to clarify
2007 *
2008 * @param array $params
2009 * @param int $length
2010 *
2011 * @return string
2012 */
2013 protected function getPaymentDescription($params = [], $length = 24) {
2014 $parts = [
2015 'contactID',
2016 'contributionID',
2017 'description',
2018 'billing_first_name',
2019 'billing_last_name',
2020 ];
2021 $validParts = [];
2022 $params['description'] = $this->getDescription();
2023 foreach ($parts as $part) {
2024 if ((!empty($params[$part]))) {
2025 $validParts[] = $params[$part];
2026 }
2027 }
2028 return substr(implode('-', $validParts), 0, $length);
2029 }
2030
2031 /**
2032 * Checks if backoffice recurring edit is allowed
2033 *
2034 * @return bool
2035 */
2036 public function supportsEditRecurringContribution() {
2037 return FALSE;
2038 }
2039
2040 /**
2041 * Does this processor support changing the amount for recurring contributions through code.
2042 *
2043 * If the processor returns true then it must be possible to update the amount from within CiviCRM
2044 * that will be updated at the payment processor.
2045 *
2046 * @return bool
2047 */
2048 protected function supportsChangeSubscriptionAmount() {
2049 return method_exists(CRM_Utils_System::getClassName($this), 'changeSubscriptionAmount');
2050 }
2051
2052 /**
2053 * Checks if payment processor supports recurring contributions
2054 *
2055 * @return bool
2056 */
2057 public function supportsRecurring() {
2058 if (!empty($this->_paymentProcessor['is_recur'])) {
2059 return TRUE;
2060 }
2061 return FALSE;
2062 }
2063
2064 /**
2065 * Checks if payment processor supports an account login URL
2066 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
2067 * TODO: It is implemented by AuthorizeNET, any others?
2068 *
2069 * @return bool
2070 */
2071 protected function supportsAccountLoginURL() {
2072 return method_exists(CRM_Utils_System::getClassName($this), 'accountLoginURL');
2073 }
2074
2075 /**
2076 * Should a receipt be sent out for a pending payment.
2077 *
2078 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
2079 */
2080 public function isSendReceiptForPending() {
2081 return FALSE;
2082 }
2083
2084 }