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