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