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