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