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