Merge pull request #19352 from colemanw/afformRef
[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 unused parameter).
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 the processor support the user having a choice as to whether to cancel the recurring with the processor?
404 *
405 * If this returns TRUE then there will be an option to send a cancellation request in the cancellation form.
406 *
407 * This would normally be false for processors where CiviCRM maintains the schedule.
408 *
409 * @return bool
410 */
411 protected function supportsCancelRecurringNotifyOptional() {
412 return $this->supportsCancelRecurring();
413 }
414
415 /**
416 * Does this processor support pre-approval.
417 *
418 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
419 *
420 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
421 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
422 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
423 *
424 * @return bool
425 */
426 protected function supportsPreApproval() {
427 return FALSE;
428 }
429
430 /**
431 * Does this processor support updating billing info for recurring contributions through code.
432 *
433 * If the processor returns true then it must be possible to update billing info from within CiviCRM
434 * that will be updated at the payment processor.
435 *
436 * @return bool
437 */
438 protected function supportsUpdateSubscriptionBillingInfo() {
439 return method_exists(CRM_Utils_System::getClassName($this), 'updateSubscriptionBillingInfo');
440 }
441
442 /**
443 * Can recurring contributions be set against pledges.
444 *
445 * In practice all processors that use the baseIPN function to finish transactions or
446 * call the completetransaction api support this by looking up previous contributions in the
447 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
448 * adding the new payment to the pledge.
449 *
450 * However, only enabling for processors it has been tested against.
451 *
452 * @return bool
453 */
454 protected function supportsRecurContributionsForPledges() {
455 return FALSE;
456 }
457
458 /**
459 * Does the processor work without an email address?
460 *
461 * The historic assumption is that all processors require an email address. This capability
462 * allows a processor to state it does not need to be provided with an email address.
463 * NB: when this was added (Feb 2020), the Manual processor class overrides this but
464 * the only use of the capability is in the webform_civicrm module. It is not currently
465 * used in core but may be in future.
466 *
467 * @return bool
468 */
469 protected function supportsNoEmailProvided() {
470 return FALSE;
471 }
472
473 /**
474 * Function to action pre-approval if supported
475 *
476 * @param array $params
477 * Parameters from the form
478 *
479 * This function returns an array which should contain
480 * - pre_approval_parameters (this will be stored on the calling form & available later)
481 * - redirect_url (if set the browser will be redirected to this.
482 */
483 public function doPreApproval(&$params) {
484 }
485
486 /**
487 * Get any details that may be available to the payment processor due to an approval process having happened.
488 *
489 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
490 * result.
491 *
492 * @param array $storedDetails
493 *
494 * @return array
495 */
496 public function getPreApprovalDetails($storedDetails) {
497 return [];
498 }
499
500 /**
501 * Default payment instrument validation.
502 *
503 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
504 * Not a static function, because I need to check for payment_type.
505 *
506 * @param array $values
507 * @param array $errors
508 */
509 public function validatePaymentInstrument($values, &$errors) {
510 CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
511 if ($this->_paymentProcessor['payment_type'] == 1) {
512 CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
513 }
514 }
515
516 /**
517 * Getter for the payment processor.
518 *
519 * The payment processor array is based on the civicrm_payment_processor table entry.
520 *
521 * @return array
522 * Payment processor array.
523 */
524 public function getPaymentProcessor() {
525 return $this->_paymentProcessor;
526 }
527
528 /**
529 * Setter for the payment processor.
530 *
531 * @param array $processor
532 */
533 public function setPaymentProcessor($processor) {
534 $this->_paymentProcessor = $processor;
535 }
536
537 /**
538 * Setter for the payment form that wants to use the processor.
539 *
540 * @deprecated
541 *
542 * @param CRM_Core_Form $paymentForm
543 */
544 public function setForm(&$paymentForm) {
545 $this->_paymentForm = $paymentForm;
546 }
547
548 /**
549 * Getter for payment form that is using the processor.
550 * @deprecated
551 * @return CRM_Core_Form
552 * A form object
553 */
554 public function getForm() {
555 return $this->_paymentForm;
556 }
557
558 /**
559 * Get help text information (help, description, etc.) about this payment,
560 * to display to the user.
561 *
562 * @param string $context
563 * Context of the text.
564 * Only explicitly supported contexts are handled without error.
565 * Currently supported:
566 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
567 * - contributionPageContinueText (params: amount, is_payment_to_existing)
568 * - cancelRecurDetailText:
569 * params:
570 * mode, amount, currency, frequency_interval, frequency_unit,
571 * installments, {membershipType|only if mode=auto_renew},
572 * selfService (bool) - TRUE if user doesn't have "edit contributions" permission.
573 * ie. they are accessing via a "self-service" link from an email receipt or similar.
574 * - cancelRecurNotSupportedText
575 *
576 * @param array $params
577 * Parameters for the field, context specific.
578 *
579 * @return string
580 */
581 public function getText($context, $params) {
582 // I have deliberately added a noisy fail here.
583 // The function is intended to be extendable, but not by changes
584 // not documented clearly above.
585 switch ($context) {
586 case 'contributionPageRecurringHelp':
587 // require exactly two parameters
588 if (array_keys($params) == [
589 'is_recur_installments',
590 'is_email_receipt',
591 ]) {
592 $gotText = ts('Your recurring contribution will be processed automatically.');
593 if ($params['is_recur_installments']) {
594 $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.');
595 }
596 if ($params['is_email_receipt']) {
597 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
598 }
599 }
600 return $gotText;
601
602 case 'contributionPageContinueText':
603 return ts('Click the <strong>Continue</strong> button to proceed with the payment.');
604
605 case 'cancelRecurDetailText':
606 if ($params['mode'] === 'auto_renew') {
607 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.',
608 [1 => $params['membershipType']]
609 );
610 }
611 else {
612 $text = ts('Recurring Contribution Details: %1 every %2 %3', [
613 1 => CRM_Utils_Money::format($params['amount'], $params['currency']),
614 2 => $params['frequency_interval'],
615 3 => $params['frequency_unit'],
616 ]);
617 if (!empty($params['installments'])) {
618 $text .= ' ' . ts('for %1 installments', [1 => $params['installments']]) . '.';
619 }
620 $text = "<strong>{$text}</strong><div class='content'>";
621 $text .= ts('Click the button below to cancel this commitment and stop future transactions. This does not affect contributions which have already been completed.');
622 $text .= '</div>';
623 return $text;
624 }
625
626 case 'cancelRecurNotSupportedText':
627 if (!$this->supportsCancelRecurring()) {
628 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.');
629 }
630 return '';
631
632 }
633 CRM_Core_Error::deprecatedFunctionWarning('Calls to getText must use a supported method');
634 return '';
635 }
636
637 /**
638 * Get the title of the payment processor to display to the user
639 *
640 * @return string
641 */
642 public function getTitle() {
643 return $this->getPaymentProcessor()['title'] ?? $this->getPaymentProcessor()['name'];
644 }
645
646 /**
647 * Getter for accessing member vars.
648 *
649 * @todo believe this is unused
650 *
651 * @param string $name
652 *
653 * @return null
654 */
655 public function getVar($name) {
656 return $this->$name ?? NULL;
657 }
658
659 /**
660 * Get name for the payment information type.
661 * @todo - use option group + name field (like Omnipay does)
662 * @return string
663 */
664 public function getPaymentTypeName() {
665 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
666 }
667
668 /**
669 * Get label for the payment information type.
670 * @todo - use option group + labels (like Omnipay does)
671 * @return string
672 */
673 public function getPaymentTypeLabel() {
674 return $this->_paymentProcessor['payment_type'] == 1 ? ts('Credit Card') : ts('Direct Debit');
675 }
676
677 /**
678 * Get array of fields that should be displayed on the payment form.
679 *
680 * Common results are
681 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
682 * or
683 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
684 * or
685 * array()
686 *
687 * @return array
688 * Array of payment fields appropriate to the payment processor.
689 *
690 * @throws CiviCRM_API3_Exception
691 */
692 public function getPaymentFormFields() {
693 if ($this->_paymentProcessor['billing_mode'] == 4) {
694 return [];
695 }
696 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
697 }
698
699 /**
700 * Get an array of the fields that can be edited on the recurring contribution.
701 *
702 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
703 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
704 * can be updated from the contribution recur edit screen.
705 *
706 * The fields are likely to be a subset of these
707 * - 'amount',
708 * - 'installments',
709 * - 'frequency_interval',
710 * - 'frequency_unit',
711 * - 'cycle_day',
712 * - 'next_sched_contribution_date',
713 * - 'end_date',
714 * - 'failure_retry_day',
715 *
716 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
717 * metadata is not defined in the xml for the field it will cause an error.
718 *
719 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
720 * form (UpdateSubscription).
721 *
722 * @return array
723 */
724 public function getEditableRecurringScheduleFields() {
725 if ($this->supports('changeSubscriptionAmount')) {
726 return ['amount'];
727 }
728 return [];
729 }
730
731 /**
732 * Get the help text to present on the recurring update page.
733 *
734 * This should reflect what can or cannot be edited.
735 *
736 * @return string
737 */
738 public function getRecurringScheduleUpdateHelpText() {
739 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
740 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.');
741 }
742 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.');
743 }
744
745 /**
746 * Get the metadata for all required fields.
747 *
748 * @return array;
749 */
750 protected function getMandatoryFields() {
751 $mandatoryFields = [];
752 foreach ($this->getAllFields() as $field_name => $field_spec) {
753 if (!empty($field_spec['is_required'])) {
754 $mandatoryFields[$field_name] = $field_spec;
755 }
756 }
757 return $mandatoryFields;
758 }
759
760 /**
761 * Get the metadata of all the fields configured for this processor.
762 *
763 * @return array
764 *
765 * @throws \CiviCRM_API3_Exception
766 */
767 protected function getAllFields() {
768 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
769 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
770 return array_merge($paymentFields, $billingFields);
771 }
772
773 /**
774 * Get array of fields that should be displayed on the payment form for credit cards.
775 *
776 * @return array
777 */
778 protected function getCreditCardFormFields() {
779 return [
780 'credit_card_type',
781 'credit_card_number',
782 'cvv2',
783 'credit_card_exp_date',
784 ];
785 }
786
787 /**
788 * Get array of fields that should be displayed on the payment form for direct debits.
789 *
790 * @return array
791 */
792 protected function getDirectDebitFormFields() {
793 return [
794 'account_holder',
795 'bank_account_number',
796 'bank_identification_number',
797 'bank_name',
798 ];
799 }
800
801 /**
802 * Return an array of all the details about the fields potentially required for payment fields.
803 *
804 * Only those determined by getPaymentFormFields will actually be assigned to the form
805 *
806 * @return array
807 * field metadata
808 */
809 public function getPaymentFormFieldsMetadata() {
810 //@todo convert credit card type into an option value
811 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::creditCard();
812 $isCVVRequired = Civi::settings()->get('cvv_backoffice_required');
813 if (!$this->isBackOffice()) {
814 $isCVVRequired = TRUE;
815 }
816 return [
817 'credit_card_number' => [
818 'htmlType' => 'text',
819 'name' => 'credit_card_number',
820 'title' => ts('Card Number'),
821 'attributes' => [
822 'size' => 20,
823 'maxlength' => 20,
824 'autocomplete' => 'off',
825 'class' => 'creditcard required',
826 ],
827 'is_required' => TRUE,
828 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
829 ],
830 'cvv2' => [
831 'htmlType' => 'text',
832 'name' => 'cvv2',
833 'title' => ts('Security Code'),
834 'attributes' => [
835 'size' => 5,
836 'maxlength' => 10,
837 'autocomplete' => 'off',
838 'class' => ($isCVVRequired ? 'required' : ''),
839 ],
840 'is_required' => $isCVVRequired,
841 'rules' => [
842 [
843 '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.'),
844 'rule_name' => 'integer',
845 'rule_parameters' => NULL,
846 ],
847 ],
848 ],
849 'credit_card_exp_date' => [
850 'htmlType' => 'date',
851 'name' => 'credit_card_exp_date',
852 'title' => ts('Expiration Date'),
853 'attributes' => CRM_Core_SelectValues::date('creditCard'),
854 'is_required' => TRUE,
855 'rules' => [
856 [
857 'rule_message' => ts('Card expiration date cannot be a past date.'),
858 'rule_name' => 'currentDate',
859 'rule_parameters' => TRUE,
860 ],
861 ],
862 'extra' => ['class' => 'crm-form-select required'],
863 ],
864 'credit_card_type' => [
865 'htmlType' => 'select',
866 'name' => 'credit_card_type',
867 'title' => ts('Card Type'),
868 'attributes' => $creditCardType,
869 'is_required' => FALSE,
870 ],
871 'account_holder' => [
872 'htmlType' => 'text',
873 'name' => 'account_holder',
874 'title' => ts('Account Holder'),
875 'attributes' => [
876 'size' => 20,
877 'maxlength' => 34,
878 'autocomplete' => 'on',
879 'class' => 'required',
880 ],
881 'is_required' => TRUE,
882 ],
883 //e.g. IBAN can have maxlength of 34 digits
884 'bank_account_number' => [
885 'htmlType' => 'text',
886 'name' => 'bank_account_number',
887 'title' => ts('Bank Account Number'),
888 'attributes' => [
889 'size' => 20,
890 'maxlength' => 34,
891 'autocomplete' => 'off',
892 'class' => 'required',
893 ],
894 'rules' => [
895 [
896 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
897 'rule_name' => 'nopunctuation',
898 'rule_parameters' => NULL,
899 ],
900 ],
901 'is_required' => TRUE,
902 ],
903 //e.g. SWIFT-BIC can have maxlength of 11 digits
904 'bank_identification_number' => [
905 'htmlType' => 'text',
906 'name' => 'bank_identification_number',
907 'title' => ts('Bank Identification Number'),
908 'attributes' => [
909 'size' => 20,
910 'maxlength' => 11,
911 'autocomplete' => 'off',
912 'class' => 'required',
913 ],
914 'is_required' => TRUE,
915 'rules' => [
916 [
917 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
918 'rule_name' => 'nopunctuation',
919 'rule_parameters' => NULL,
920 ],
921 ],
922 ],
923 'bank_name' => [
924 'htmlType' => 'text',
925 'name' => 'bank_name',
926 'title' => ts('Bank Name'),
927 'attributes' => [
928 'size' => 20,
929 'maxlength' => 64,
930 'autocomplete' => 'off',
931 'class' => 'required',
932 ],
933 'is_required' => TRUE,
934
935 ],
936 'check_number' => [
937 'htmlType' => 'text',
938 'name' => 'check_number',
939 'title' => ts('Check Number'),
940 'is_required' => FALSE,
941 'attributes' => NULL,
942 ],
943 'pan_truncation' => [
944 'htmlType' => 'text',
945 'name' => 'pan_truncation',
946 'title' => ts('Last 4 digits of the card'),
947 'is_required' => FALSE,
948 'attributes' => [
949 'size' => 4,
950 'maxlength' => 4,
951 'minlength' => 4,
952 'autocomplete' => 'off',
953 ],
954 'rules' => [
955 [
956 'rule_message' => ts('Please enter valid last 4 digit card number.'),
957 'rule_name' => 'numeric',
958 'rule_parameters' => NULL,
959 ],
960 ],
961 ],
962 'payment_token' => [
963 'htmlType' => 'hidden',
964 'name' => 'payment_token',
965 'title' => ts('Authorization token'),
966 'is_required' => FALSE,
967 'attributes' => [
968 'size' => 10,
969 'autocomplete' => 'off',
970 'id' => 'payment_token',
971 ],
972 ],
973 ];
974 }
975
976 /**
977 * Get billing fields required for this processor.
978 *
979 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
980 * alter.
981 *
982 * @param int $billingLocationID
983 *
984 * @return array
985 */
986 public function getBillingAddressFields($billingLocationID = NULL) {
987 if (!$billingLocationID) {
988 // Note that although the billing id is passed around the forms the idea that it would be anything other than
989 // the result of the function below doesn't seem to have eventuated.
990 // So taking this as a param is possibly something to be removed in favour of the standard default.
991 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
992 }
993 if ($this->_paymentProcessor['billing_mode'] != 1 && $this->_paymentProcessor['billing_mode'] != 3) {
994 return [];
995 }
996 return [
997 'first_name' => 'billing_first_name',
998 'middle_name' => 'billing_middle_name',
999 'last_name' => 'billing_last_name',
1000 'street_address' => "billing_street_address-{$billingLocationID}",
1001 'city' => "billing_city-{$billingLocationID}",
1002 'country' => "billing_country_id-{$billingLocationID}",
1003 'state_province' => "billing_state_province_id-{$billingLocationID}",
1004 'postal_code' => "billing_postal_code-{$billingLocationID}",
1005 ];
1006 }
1007
1008 /**
1009 * Get form metadata for billing address fields.
1010 *
1011 * @param int $billingLocationID
1012 *
1013 * @return array
1014 * Array of metadata for address fields.
1015 */
1016 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
1017 if (!$billingLocationID) {
1018 // Note that although the billing id is passed around the forms the idea that it would be anything other than
1019 // the result of the function below doesn't seem to have eventuated.
1020 // So taking this as a param is possibly something to be removed in favour of the standard default.
1021 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
1022 }
1023 $metadata = [];
1024 $metadata['billing_first_name'] = [
1025 'htmlType' => 'text',
1026 'name' => 'billing_first_name',
1027 'title' => ts('Billing First Name'),
1028 'cc_field' => TRUE,
1029 'attributes' => [
1030 'size' => 30,
1031 'maxlength' => 60,
1032 'autocomplete' => 'off',
1033 'class' => 'required',
1034 ],
1035 'is_required' => TRUE,
1036 ];
1037
1038 $metadata['billing_middle_name'] = [
1039 'htmlType' => 'text',
1040 'name' => 'billing_middle_name',
1041 'title' => ts('Billing Middle Name'),
1042 'cc_field' => TRUE,
1043 'attributes' => [
1044 'size' => 30,
1045 'maxlength' => 60,
1046 'autocomplete' => 'off',
1047 ],
1048 'is_required' => FALSE,
1049 ];
1050
1051 $metadata['billing_last_name'] = [
1052 'htmlType' => 'text',
1053 'name' => 'billing_last_name',
1054 'title' => ts('Billing Last Name'),
1055 'cc_field' => TRUE,
1056 'attributes' => [
1057 'size' => 30,
1058 'maxlength' => 60,
1059 'autocomplete' => 'off',
1060 'class' => 'required',
1061 ],
1062 'is_required' => TRUE,
1063 ];
1064
1065 $metadata["billing_street_address-{$billingLocationID}"] = [
1066 'htmlType' => 'text',
1067 'name' => "billing_street_address-{$billingLocationID}",
1068 'title' => ts('Street Address'),
1069 'cc_field' => TRUE,
1070 'attributes' => [
1071 'size' => 30,
1072 'maxlength' => 60,
1073 'autocomplete' => 'off',
1074 'class' => 'required',
1075 ],
1076 'is_required' => TRUE,
1077 ];
1078
1079 $metadata["billing_city-{$billingLocationID}"] = [
1080 'htmlType' => 'text',
1081 'name' => "billing_city-{$billingLocationID}",
1082 'title' => ts('City'),
1083 'cc_field' => TRUE,
1084 'attributes' => [
1085 'size' => 30,
1086 'maxlength' => 60,
1087 'autocomplete' => 'off',
1088 'class' => 'required',
1089 ],
1090 'is_required' => TRUE,
1091 ];
1092
1093 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1094 'htmlType' => 'chainSelect',
1095 'title' => ts('State/Province'),
1096 'name' => "billing_state_province_id-{$billingLocationID}",
1097 'cc_field' => TRUE,
1098 'is_required' => TRUE,
1099 'extra' => ['class' => 'required'],
1100 ];
1101
1102 $metadata["billing_postal_code-{$billingLocationID}"] = [
1103 'htmlType' => 'text',
1104 'name' => "billing_postal_code-{$billingLocationID}",
1105 'title' => ts('Postal Code'),
1106 'cc_field' => TRUE,
1107 'attributes' => [
1108 'size' => 30,
1109 'maxlength' => 60,
1110 'autocomplete' => 'off',
1111 'class' => 'required',
1112 ],
1113 'is_required' => TRUE,
1114 ];
1115
1116 $metadata["billing_country_id-{$billingLocationID}"] = [
1117 'htmlType' => 'select',
1118 'name' => "billing_country_id-{$billingLocationID}",
1119 'title' => ts('Country'),
1120 'cc_field' => TRUE,
1121 'attributes' => [
1122 '' => ts('- select -'),
1123 ] + CRM_Core_PseudoConstant::country(),
1124 'is_required' => TRUE,
1125 'extra' => ['class' => 'required crm-form-select2 crm-select2'],
1126 ];
1127 return $metadata;
1128 }
1129
1130 /**
1131 * Get base url dependent on component.
1132 *
1133 * (or preferably set it using the setter function).
1134 *
1135 * @return string
1136 */
1137 protected function getBaseReturnUrl() {
1138 if ($this->baseReturnUrl) {
1139 return $this->baseReturnUrl;
1140 }
1141 if ($this->_component == 'event') {
1142 $baseURL = 'civicrm/event/register';
1143 }
1144 else {
1145 $baseURL = 'civicrm/contribute/transact';
1146 }
1147 return $baseURL;
1148 }
1149
1150 /**
1151 * Get the currency for the transaction from the params.
1152 *
1153 * Legacy wrapper. Better for a method to work on its own PropertyBag.
1154 *
1155 * This code now uses PropertyBag to allow for old inputs like currencyID.
1156 *
1157 * @param $params
1158 *
1159 * @return string
1160 */
1161 protected function getCurrency($params = []) {
1162 $localPropertyBag = new PropertyBag();
1163 $localPropertyBag->mergeLegacyInputParams($params);
1164 return $localPropertyBag->getCurrency();
1165 }
1166
1167 /**
1168 * Legacy. Better for a method to work on its own PropertyBag,
1169 * but also, this function does not do very much.
1170 *
1171 * @param array $params
1172 *
1173 * @return string
1174 * @throws \CRM_Core_Exception
1175 */
1176 protected function getAmount($params = []) {
1177 return CRM_Utils_Money::format($params['amount'], NULL, NULL, TRUE);
1178 }
1179
1180 /**
1181 * Get url to return to after cancelled or failed transaction.
1182 *
1183 * @param string $qfKey
1184 * @param int $participantID
1185 *
1186 * @return string cancel url
1187 */
1188 public function getCancelUrl($qfKey, $participantID) {
1189 if (isset($this->cancelUrl)) {
1190 return $this->cancelUrl;
1191 }
1192
1193 if ($this->_component == 'event') {
1194 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1195 'reset' => 1,
1196 'cc' => 'fail',
1197 'participantId' => $participantID,
1198 ],
1199 TRUE, NULL, FALSE
1200 );
1201 }
1202
1203 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1204 '_qf_Main_display' => 1,
1205 'qfKey' => $qfKey,
1206 'cancel' => 1,
1207 ],
1208 TRUE, NULL, FALSE
1209 );
1210 }
1211
1212 /**
1213 * Get URL to return the browser to on success.
1214 *
1215 * @param string $qfKey
1216 *
1217 * @return string
1218 */
1219 protected function getReturnSuccessUrl($qfKey) {
1220 if (isset($this->successUrl)) {
1221 return $this->successUrl;
1222 }
1223
1224 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1225 '_qf_ThankYou_display' => 1,
1226 'qfKey' => $qfKey,
1227 ],
1228 TRUE, NULL, FALSE
1229 );
1230 }
1231
1232 /**
1233 * Get URL to return the browser to on failure.
1234 *
1235 * @param string $key
1236 * @param int $participantID
1237 * @param int $eventID
1238 *
1239 * @return string
1240 * URL for a failing transactor to be redirected to.
1241 */
1242 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1243 if (isset($this->cancelUrl)) {
1244 return $this->cancelUrl;
1245 }
1246
1247 $test = $this->_is_test ? '&action=preview' : '';
1248 if ($this->_component == "event") {
1249 return CRM_Utils_System::url('civicrm/event/register',
1250 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1251 FALSE, NULL, FALSE
1252 );
1253 }
1254 else {
1255 return CRM_Utils_System::url('civicrm/contribute/transact',
1256 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1257 FALSE, NULL, FALSE
1258 );
1259 }
1260 }
1261
1262 /**
1263 * Get URl for when the back button is pressed.
1264 *
1265 * @param $qfKey
1266 *
1267 * @return string url
1268 */
1269 protected function getGoBackUrl($qfKey) {
1270 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1271 '_qf_Confirm_display' => 'true',
1272 'qfKey' => $qfKey,
1273 ],
1274 TRUE, NULL, FALSE
1275 );
1276 }
1277
1278 /**
1279 * Get the notify (aka ipn, web hook or silent post) url.
1280 *
1281 * If there is no '.' in it we assume that we are dealing with localhost or
1282 * similar and it is unreachable from the web & hence invalid.
1283 *
1284 * @return string
1285 * URL to notify outcome of transaction.
1286 */
1287 protected function getNotifyUrl() {
1288 $url = CRM_Utils_System::url(
1289 'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
1290 [],
1291 TRUE,
1292 NULL,
1293 FALSE,
1294 TRUE
1295 );
1296 return (stristr($url, '.')) ? $url : '';
1297 }
1298
1299 /**
1300 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1301 * @deprecated
1302 * Does a server to server payment transaction.
1303 *
1304 * @param array $params
1305 * Assoc array of input parameters for this transaction.
1306 *
1307 * @return array
1308 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1309 */
1310 protected function doDirectPayment(&$params) {
1311 return $params;
1312 }
1313
1314 /**
1315 * Processors may need to inspect, validate, cast and copy data that is
1316 * specific to this Payment Processor from the input array to custom fields
1317 * on the PropertyBag.
1318 *
1319 * @param Civi\Payment\PropertyBag $propertyBag
1320 * @param array $params
1321 * @param string $component
1322 *
1323 * @throws \Civi\Payment\Exception\PaymentProcessorException
1324 */
1325 public function extractCustomPropertiesForDoPayment(PropertyBag $propertyBag, array $params, $component = 'contribute') {
1326 // example
1327 // (validation and casting goes first)
1328 // $propertyBag->setCustomProperty('myprocessor_customPropertyName', $value);
1329 }
1330
1331 /**
1332 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1333 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1334 *
1335 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1336 * the transaction & in fact doTransferCheckout would not traditionally come back.
1337 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1338 *
1339 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1340 * In some cases the IPN will set the payment to "Completed" some time later.
1341 *
1342 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1343 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1344 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1345 *
1346 * @param array|PropertyBag $params
1347 *
1348 * @param string $component
1349 *
1350 * @return array
1351 * Result array (containing at least the key payment_status_id)
1352 *
1353 * @throws \Civi\Payment\Exception\PaymentProcessorException
1354 */
1355 public function doPayment(&$params, $component = 'contribute') {
1356 $this->_component = $component;
1357 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
1358
1359 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1360 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1361 // have an example of that at the mome.
1362 if ($params['amount'] == 0) {
1363 $result['payment_status_id'] = array_search('Completed', $statuses);
1364 return $result;
1365 }
1366
1367 if ($this->_paymentProcessor['billing_mode'] == 4) {
1368 $result = $this->doTransferCheckout($params, $component);
1369 if (is_array($result) && !isset($result['payment_status_id'])) {
1370 $result['payment_status_id'] = array_search('Pending', $statuses);
1371 }
1372 }
1373 else {
1374 $result = $this->doDirectPayment($params, $component);
1375 if (is_array($result) && !isset($result['payment_status_id'])) {
1376 if (!empty($params['is_recur'])) {
1377 // See comment block.
1378 $result['payment_status_id'] = array_search('Pending', $statuses);
1379 }
1380 else {
1381 $result['payment_status_id'] = array_search('Completed', $statuses);
1382 }
1383 }
1384 }
1385 if (is_a($result, 'CRM_Core_Error')) {
1386 CRM_Core_Error::deprecatedFunctionWarning('payment processors should throw exceptions rather than return errors');
1387 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
1388 }
1389 return $result;
1390 }
1391
1392 /**
1393 * Cancel a recurring subscription.
1394 *
1395 * Payment processor classes should override this rather than implementing cancelSubscription.
1396 *
1397 * A PaymentProcessorException should be thrown if the update of the contribution_recur
1398 * record should not proceed (in many cases this function does nothing
1399 * as the payment processor does not need to take any action & this should silently
1400 * proceed. Note the form layer will only call this after calling
1401 * $processor->supports('cancelRecurring');
1402 *
1403 * A payment processor can control whether to notify the actual payment provider or just
1404 * cancel in CiviCRM by setting the `isNotifyProcessorOnCancelRecur` property on PropertyBag.
1405 * If supportsCancelRecurringNotifyOptional() is TRUE this will be automatically set based on
1406 * the user selection on the form. If FALSE you need to set it yourself.
1407 *
1408 * @param \Civi\Payment\PropertyBag $propertyBag
1409 *
1410 * @return array
1411 *
1412 * @throws \Civi\Payment\Exception\PaymentProcessorException
1413 */
1414 public function doCancelRecurring(PropertyBag $propertyBag) {
1415 if (method_exists($this, 'cancelSubscription')
1416 && ($propertyBag->has('isNotifyProcessorOnCancelRecur') && $propertyBag->getIsNotifyProcessorOnCancelRecur())) {
1417 $message = NULL;
1418 if ($this->cancelSubscription($message, $propertyBag)) {
1419 return ['message' => $message];
1420 }
1421 throw new PaymentProcessorException($message);
1422 }
1423 return ['message' => ts('Recurring contribution cancelled')];
1424 }
1425
1426 /**
1427 * Refunds payment
1428 *
1429 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1430 *
1431 * @param array $params
1432 *
1433 * @throws \Civi\Payment\Exception\PaymentProcessorException
1434 */
1435 public function doRefund(&$params) {}
1436
1437 /**
1438 * Query payment processor for details about a transaction.
1439 *
1440 * @param array $params
1441 * Array of parameters containing one of:
1442 * - trxn_id Id of an individual transaction.
1443 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1444 *
1445 * @return array
1446 * Extra parameters retrieved.
1447 * Any parameters retrievable through this should be documented in the function comments at
1448 * CRM_Core_Payment::doQuery. Currently:
1449 * - fee_amount Amount of fee paid
1450 */
1451 public function doQuery($params) {
1452 return [];
1453 }
1454
1455 /**
1456 * This function checks to see if we have the right config values.
1457 *
1458 * @return string
1459 * the error message if any
1460 */
1461 abstract protected function checkConfig();
1462
1463 /**
1464 * Redirect for paypal.
1465 *
1466 * @todo move to paypal class or remove
1467 *
1468 * @param $paymentProcessor
1469 *
1470 * @return bool
1471 */
1472 public static function paypalRedirect(&$paymentProcessor) {
1473 if (!$paymentProcessor) {
1474 return FALSE;
1475 }
1476
1477 if (isset($_GET['payment_date']) &&
1478 isset($_GET['merchant_return_link']) &&
1479 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
1480 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1481 ) {
1482 return TRUE;
1483 }
1484
1485 return FALSE;
1486 }
1487
1488 /**
1489 * Handle incoming payment notification.
1490 *
1491 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1492 *
1493 * @todo move to0 \Civi\Payment\System factory method
1494 * Page callback for civicrm/payment/ipn
1495 */
1496 public static function handleIPN() {
1497 try {
1498 self::handlePaymentMethod(
1499 'PaymentNotification',
1500 [
1501 'processor_name' => CRM_Utils_Request::retrieveValue('processor_name', 'String'),
1502 'processor_id' => CRM_Utils_Request::retrieveValue('processor_id', 'Integer'),
1503 'mode' => CRM_Utils_Request::retrieveValue('mode', 'Alphanumeric'),
1504 ]
1505 );
1506 }
1507 catch (CRM_Core_Exception $e) {
1508 Civi::log()->error('ipn_payment_callback_exception', [
1509 'context' => [
1510 'backtrace' => $e->getTraceAsString(),
1511 'message' => $e->getMessage(),
1512 ],
1513 ]);
1514 }
1515 CRM_Utils_System::civiExit();
1516 }
1517
1518 /**
1519 * Payment callback handler.
1520 *
1521 * The processor_name or processor_id is passed in.
1522 * Note that processor_id is more reliable as one site may have more than one instance of a
1523 * processor & ideally the processor will be validating the results
1524 * Load requested payment processor and call that processor's handle<$method> method
1525 *
1526 * @todo move to \Civi\Payment\System factory method
1527 *
1528 * @param string $method
1529 * 'PaymentNotification' or 'PaymentCron'
1530 * @param array $params
1531 *
1532 * @throws \CRM_Core_Exception
1533 * @throws \Exception
1534 */
1535 public static function handlePaymentMethod($method, $params = []) {
1536 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1537 $q = explode('/', CRM_Utils_System::currentPath());
1538 $lastParam = array_pop($q);
1539 if (is_numeric($lastParam)) {
1540 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1541 }
1542 else {
1543 self::logPaymentNotification($params);
1544 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1545 }
1546 }
1547
1548 self::logPaymentNotification($params);
1549
1550 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1551 FROM civicrm_payment_processor_type ppt
1552 INNER JOIN civicrm_payment_processor pp
1553 ON pp.payment_processor_type_id = ppt.id
1554 AND pp.is_active";
1555
1556 if (isset($params['processor_id'])) {
1557 $sql .= " WHERE pp.id = %2";
1558 $args[2] = [$params['processor_id'], 'Integer'];
1559 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1560 }
1561 else {
1562 // This is called when processor_name is passed - passing processor_id instead is recommended.
1563 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1564 $args[1] = [
1565 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
1566 'Integer',
1567 ];
1568 $args[2] = [$params['processor_name'], 'String'];
1569 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1570 }
1571
1572 $dao = CRM_Core_DAO::executeQuery($sql, $args);
1573
1574 // Check whether we found anything at all.
1575 if (!$dao->N) {
1576 throw new CRM_Core_Exception($notFound);
1577 }
1578
1579 $method = 'handle' . $method;
1580 $extension_instance_found = FALSE;
1581
1582 // In all likelihood, we'll just end up with the one instance returned here. But it's
1583 // possible we may get more. Hence, iterate through all instances ..
1584
1585 while ($dao->fetch()) {
1586 // Check pp is extension - is this still required - surely the singleton below handles it.
1587 $ext = CRM_Extension_System::singleton()->getMapper();
1588 if ($ext->isExtensionKey($dao->class_name)) {
1589 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
1590 require_once $ext->classToPath($paymentClass);
1591 }
1592
1593 $processorInstance = System::singleton()->getById($dao->processor_id);
1594
1595 // Should never be empty - we already established this processor_id exists and is active.
1596 if (empty($processorInstance)) {
1597 continue;
1598 }
1599
1600 // Does PP implement this method, and can we call it?
1601 if (!method_exists($processorInstance, $method) ||
1602 !is_callable([$processorInstance, $method])
1603 ) {
1604 // on the off chance there is a double implementation of this processor we should keep looking for another
1605 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1606 continue;
1607 }
1608
1609 // Everything, it seems, is ok - execute pp callback handler
1610 $processorInstance->$method();
1611 $extension_instance_found = TRUE;
1612 }
1613
1614 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1615 $IPNParams = array_merge($_GET, $_REQUEST);
1616 CRM_Utils_Hook::postIPNProcess($IPNParams);
1617 if (!$extension_instance_found) {
1618 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1619 "%2 method is unsupported in legacy payment processors.";
1620 throw new CRM_Core_Exception(ts($message, [
1621 1 => $params['processor_name'],
1622 2 => $method,
1623 ]));
1624 }
1625 }
1626
1627 /**
1628 * Check whether a method is present ( & supported ) by the payment processor object.
1629 *
1630 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1631 *
1632 * @param string $method
1633 * Method to check for.
1634 *
1635 * @return bool
1636 */
1637 public function isSupported($method) {
1638 return method_exists(CRM_Utils_System::getClassName($this), $method);
1639 }
1640
1641 /**
1642 * Some processors replace the form submit button with their own.
1643 *
1644 * Returning false here will leave the button off front end forms.
1645 *
1646 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1647 */
1648 public function isSuppressSubmitButtons() {
1649 return FALSE;
1650 }
1651
1652 /**
1653 * Checks to see if invoice_id already exists in db.
1654 *
1655 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1656 * it is better to standardise to being here.
1657 *
1658 * @param int $invoiceId The ID to check.
1659 *
1660 * @param null $contributionID
1661 * If a contribution exists pass in the contribution ID.
1662 *
1663 * @return bool
1664 * True if invoice ID otherwise exists, else false
1665 */
1666 protected function checkDupe($invoiceId, $contributionID = NULL) {
1667 $contribution = new CRM_Contribute_DAO_Contribution();
1668 $contribution->invoice_id = $invoiceId;
1669 if ($contributionID) {
1670 $contribution->whereAdd("id <> $contributionID");
1671 }
1672 return $contribution->find();
1673 }
1674
1675 /**
1676 * Get url for users to manage this recurring contribution for this processor.
1677 *
1678 * @param int $entityID
1679 * @param null $entity
1680 * @param string $action
1681 *
1682 * @return string|null
1683 * @throws \CRM_Core_Exception
1684 */
1685 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1686 // Set URL
1687 switch ($action) {
1688 case 'cancel':
1689 if (!$this->supports('cancelRecurring')) {
1690 return NULL;
1691 }
1692 $url = 'civicrm/contribute/unsubscribe';
1693 break;
1694
1695 case 'billing':
1696 //in notify mode don't return the update billing url
1697 if (!$this->supports('updateSubscriptionBillingInfo')) {
1698 return NULL;
1699 }
1700 $url = 'civicrm/contribute/updatebilling';
1701 break;
1702
1703 case 'update':
1704 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1705 return NULL;
1706 }
1707 $url = 'civicrm/contribute/updaterecur';
1708 break;
1709 }
1710
1711 $userId = CRM_Core_Session::singleton()->get('userID');
1712 $contactID = 0;
1713 $checksumValue = '';
1714 $entityArg = '';
1715
1716 // Find related Contact
1717 if ($entityID) {
1718 switch ($entity) {
1719 case 'membership':
1720 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1721 $entityArg = 'mid';
1722 break;
1723
1724 case 'contribution':
1725 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1726 $entityArg = 'coid';
1727 break;
1728
1729 case 'recur':
1730 $sql = "
1731 SELECT DISTINCT con.contact_id
1732 FROM civicrm_contribution_recur rec
1733 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1734 WHERE rec.id = %1";
1735 $contactID = CRM_Core_DAO::singleValueQuery($sql, [
1736 1 => [
1737 $entityID,
1738 'Integer',
1739 ],
1740 ]);
1741 $entityArg = 'crid';
1742 break;
1743 }
1744 }
1745
1746 // Add entity arguments
1747 if ($entityArg != '') {
1748 // Add checksum argument
1749 if ($contactID != 0 && $userId != $contactID) {
1750 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1751 }
1752 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1753 }
1754
1755 // Else login URL
1756 if ($this->supports('accountLoginURL')) {
1757 return $this->accountLoginURL();
1758 }
1759
1760 // Else default
1761 return $this->_paymentProcessor['url_recur'] ?? '';
1762 }
1763
1764 /**
1765 * Get description of payment to pass to processor.
1766 *
1767 * This is often what people see in the interface so we want to get
1768 * as much unique information in as possible within the field length (& presumably the early part of the field)
1769 *
1770 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1771 * having field names to clarify
1772 *
1773 * @param array $params
1774 * @param int $length
1775 *
1776 * @return string
1777 */
1778 protected function getPaymentDescription($params = [], $length = 24) {
1779 $propertyBag = PropertyBag::cast($params);
1780 $parts = [
1781 $propertyBag->getter('contactID', TRUE),
1782 $propertyBag->getter('contributionID', TRUE),
1783 $propertyBag->getter('description', TRUE) ?: ($propertyBag->getter('isRecur', TRUE) ? ts('Recurring payment') : NULL),
1784 $propertyBag->getter('billing_first_name', TRUE),
1785 $propertyBag->getter('billing_last_name', TRUE),
1786 ];
1787 return substr(implode('-', array_filter($parts)), 0, $length);
1788 }
1789
1790 /**
1791 * Checks if back-office recurring edit is allowed
1792 *
1793 * @return bool
1794 */
1795 public function supportsEditRecurringContribution() {
1796 return FALSE;
1797 }
1798
1799 /**
1800 * Does this processor support changing the amount for recurring contributions through code.
1801 *
1802 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1803 * that will be updated at the payment processor.
1804 *
1805 * @return bool
1806 */
1807 protected function supportsChangeSubscriptionAmount() {
1808 return method_exists(CRM_Utils_System::getClassName($this), 'changeSubscriptionAmount');
1809 }
1810
1811 /**
1812 * Checks if payment processor supports recurring contributions
1813 *
1814 * @return bool
1815 */
1816 public function supportsRecurring() {
1817 if (!empty($this->_paymentProcessor['is_recur'])) {
1818 return TRUE;
1819 }
1820 return FALSE;
1821 }
1822
1823 /**
1824 * Checks if payment processor supports an account login URL
1825 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1826 * TODO: It is implemented by AuthorizeNET, any others?
1827 *
1828 * @return bool
1829 */
1830 protected function supportsAccountLoginURL() {
1831 return method_exists(CRM_Utils_System::getClassName($this), 'accountLoginURL');
1832 }
1833
1834 /**
1835 * Should a receipt be sent out for a pending payment.
1836 *
1837 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1838 */
1839 public function isSendReceiptForPending() {
1840 return FALSE;
1841 }
1842
1843 }