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