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