3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Payment\System
;
13 use Civi\Payment\Exception\PaymentProcessorException
;
14 use Civi\Payment\PropertyBag
;
17 * Class CRM_Core_Payment.
19 * This class is the main class for the payment processor subsystem.
21 * It is the parent class for payment processors. It also holds some IPN related functions
22 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
24 abstract class CRM_Core_Payment
{
27 * Component - ie. event or contribute.
29 * This is used for setting return urls.
33 protected $_component;
36 * How are we getting billing information.
38 * We are trying to completely deprecate these parameters.
40 * FORM - we collect it on the same page
41 * BUTTON - the processor collects it and sends it back to us via some protocol
44 BILLING_MODE_FORM
= 1,
45 BILLING_MODE_BUTTON
= 2,
46 BILLING_MODE_NOTIFY
= 4;
49 * Which payment type(s) are we using?
54 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
57 PAYMENT_TYPE_CREDIT_CARD
= 1,
58 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
61 * Subscription / Recurring payment Status
65 RECURRING_PAYMENT_START
= 'START',
66 RECURRING_PAYMENT_END
= 'END';
71 protected $_paymentProcessor;
74 * Base url of the calling form (offsite processors).
78 protected $baseReturnUrl;
81 * Return url upon success (offsite processors).
85 protected $successUrl;
88 * Return url upon failure (offsite processors).
95 * Processor type label.
97 * (Deprecated parameter but used in some messages).
103 public $_processorName;
106 * The profile configured to show on the billing form.
108 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
109 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
110 * requirements with the configured requirements.
112 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
115 * Note this change would probably include converting 'billing' to a reserved profile.
119 protected $billingProfile;
122 * Payment instrument ID.
124 * This is normally retrieved from the payment_processor table.
128 protected $paymentInstrumentID;
131 * Is this a back office transaction.
135 protected $backOffice = FALSE;
138 * This is only needed during the transitional phase. In future you should
139 * pass your own PropertyBag into the method you're calling.
141 * New code should NOT use $this->propertyBag.
143 * @var Civi\Payment\PropertyBag
145 protected $propertyBag;
148 * Return the payment instrument ID to use.
151 * We normally SHOULD be returning the payment instrument of the payment processor.
152 * However there is an outstanding case where this needs overriding, which is
153 * when using CRM_Core_Payment_Manual which uses the pseudoprocessor (id = 0).
155 * i.e. If you're writing a Payment Processor you should NOT be using
156 * setPaymentInstrumentID() at all.
159 * Ideally this exception-to-the-rule should be handled outside of this class
160 * i.e. this class's getPaymentInstrumentID method should return it from the
161 * payment processor and CRM_Core_Payment_Manual could override it to provide 0.
165 public function getPaymentInstrumentID() {
166 return isset($this->paymentInstrumentID
)
167 ?
$this->paymentInstrumentID
168 : (int) ($this->_paymentProcessor
['payment_instrument_id'] ??
0);
172 * Getter for the id Payment Processor ID.
176 public function getID() {
177 return (int) $this->_paymentProcessor
['id'];
181 * @deprecated Set payment Instrument id - see note on getPaymentInstrumentID.
183 * By default we actually ignore the form value. The manual processor takes
186 * @param int $paymentInstrumentID
188 public function setPaymentInstrumentID($paymentInstrumentID) {
189 $this->paymentInstrumentID
= (int) $paymentInstrumentID;
190 // See note on getPaymentInstrumentID().
191 return $this->getPaymentInstrumentID();
197 public function isBackOffice() {
198 return $this->backOffice
;
202 * Set back office property.
204 * @param bool $isBackOffice
206 public function setBackOffice($isBackOffice) {
207 $this->backOffice
= $isBackOffice;
211 * Set base return path (offsite processors).
213 * This is only useful with an internal civicrm form.
216 * Internal civicrm path.
218 public function setBaseReturnUrl($url) {
219 $this->baseReturnUrl
= $url;
223 * Set success return URL (offsite processors).
225 * This overrides $baseReturnUrl
228 * Full url of site to return browser to upon success.
230 public function setSuccessUrl($url) {
231 $this->successUrl
= $url;
235 * Set cancel return URL (offsite processors).
237 * This overrides $baseReturnUrl
240 * Full url of site to return browser to upon failure.
242 public function setCancelUrl($url) {
243 $this->cancelUrl
= $url;
247 * Set the configured payment profile.
249 * @param int|string $value
251 public function setBillingProfile($value) {
252 $this->billingProfile
= $value;
256 * Opportunity for the payment processor to override the entire form build.
258 * @param CRM_Core_Form $form
261 * Should form building stop at this point?
263 public function buildForm(&$form) {
268 * Log payment notification message to forensic system log.
270 * @todo move to factory class \Civi\Payment\System (or similar)
272 * @param array $params
274 public static function logPaymentNotification($params) {
275 $message = 'payment_notification ';
276 if (!empty($params['processor_name'])) {
277 $message .= 'processor_name=' . $params['processor_name'];
279 if (!empty($params['processor_id'])) {
280 $message .= 'processor_id=' . $params['processor_id'];
283 $log = new CRM_Utils_SystemLogger();
284 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
285 $rawRequestData = file_get_contents("php://input");
286 if (CRM_Utils_JSON
::isValidJSON($rawRequestData)) {
287 $log->alert($message, json_decode($rawRequestData, TRUE));
290 $log->alert($message, $_REQUEST);
295 * Check if capability is supported.
297 * Capabilities have a one to one relationship with capability-related functions on this class.
299 * Payment processor classes should over-ride the capability-specific function rather than this one.
301 * @param string $capability
302 * E.g BackOffice, LiveMode, FutureRecurStartDate.
306 public function supports($capability) {
307 $function = 'supports' . ucfirst($capability);
308 if (method_exists($this, $function)) {
309 return $this->$function();
315 * Are back office payments supported.
317 * e.g paypal standard won't permit you to enter a credit card associated
318 * with someone else's login.
319 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
320 * reach a 'stable' point we disable.
324 protected function supportsBackOffice() {
325 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
334 * Can more than one transaction be processed at once?
336 * In general processors that process payment by server to server communication support this while others do not.
338 * In future we are likely to hit an issue where this depends on whether a token already exists.
342 protected function supportsMultipleConcurrentPayments() {
343 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
352 * Are live payments supported - e.g dummy doesn't support this.
356 protected function supportsLiveMode() {
357 return empty($this->_paymentProcessor
['is_test']) ?
TRUE : FALSE;
361 * Are test payments supported.
365 protected function supportsTestMode() {
366 return empty($this->_paymentProcessor
['is_test']) ?
FALSE : TRUE;
370 * Does this payment processor support refund?
374 public function supportsRefund() {
379 * Should the first payment date be configurable when setting up back office recurring payments.
381 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
385 protected function supportsFutureRecurStartDate() {
390 * Does this processor support cancelling recurring contributions through code.
392 * If the processor returns true it must be possible to take action from within CiviCRM
393 * that will result in no further payments being processed. In the case of token processors (e.g
394 * IATS, eWay) updating the contribution_recur table is probably sufficient.
398 protected function supportsCancelRecurring() {
399 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
403 * Does this processor support pre-approval.
405 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
407 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
408 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
409 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
413 protected function supportsPreApproval() {
418 * Does this processor support updating billing info for recurring contributions through code.
420 * If the processor returns true then it must be possible to update billing info from within CiviCRM
421 * that will be updated at the payment processor.
425 protected function supportsUpdateSubscriptionBillingInfo() {
426 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
430 * Can recurring contributions be set against pledges.
432 * In practice all processors that use the baseIPN function to finish transactions or
433 * call the completetransaction api support this by looking up previous contributions in the
434 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
435 * adding the new payment to the pledge.
437 * However, only enabling for processors it has been tested against.
441 protected function supportsRecurContributionsForPledges() {
446 * Does the processor work without an email address?
448 * The historic assumption is that all processors require an email address. This capability
449 * allows a processor to state it does not need to be provided with an email address.
450 * NB: when this was added (Feb 2020), the Manual processor class overrides this but
451 * the only use of the capability is in the webform_civicrm module. It is not currently
452 * used in core but may be in future.
456 protected function supportsNoEmailProvided() {
461 * Function to action pre-approval if supported
463 * @param array $params
464 * Parameters from the form
466 * This function returns an array which should contain
467 * - pre_approval_parameters (this will be stored on the calling form & available later)
468 * - redirect_url (if set the browser will be redirected to this.
470 public function doPreApproval(&$params) {
474 * Get any details that may be available to the payment processor due to an approval process having happened.
476 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
479 * @param array $storedDetails
483 public function getPreApprovalDetails($storedDetails) {
488 * Default payment instrument validation.
490 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
491 * Not a static function, because I need to check for payment_type.
493 * @param array $values
494 * @param array $errors
496 public function validatePaymentInstrument($values, &$errors) {
497 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
498 if ($this->_paymentProcessor
['payment_type'] == 1) {
499 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
504 * Getter for the payment processor.
506 * The payment processor array is based on the civicrm_payment_processor table entry.
509 * Payment processor array.
511 public function getPaymentProcessor() {
512 return $this->_paymentProcessor
;
516 * Setter for the payment processor.
518 * @param array $processor
520 public function setPaymentProcessor($processor) {
521 $this->_paymentProcessor
= $processor;
525 * Setter for the payment form that wants to use the processor.
529 * @param CRM_Core_Form $paymentForm
531 public function setForm(&$paymentForm) {
532 $this->_paymentForm
= $paymentForm;
536 * Getter for payment form that is using the processor.
538 * @return CRM_Core_Form
541 public function getForm() {
542 return $this->_paymentForm
;
546 * Get help text information (help, description, etc.) about this payment,
547 * to display to the user.
549 * @param string $context
550 * Context of the text.
551 * Only explicitly supported contexts are handled without error.
552 * Currently supported:
553 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
554 * - contributionPageContinueText (params: amount, is_payment_to_existing)
555 * - cancelRecurDetailText (params: mode, amount, currency, frequency_interval, frequency_unit, installments, {membershipType|only if mode=auto_renew})
556 * - cancelRecurNotSupportedText
558 * @param array $params
559 * Parameters for the field, context specific.
563 public function getText($context, $params) {
564 // I have deliberately added a noisy fail here.
565 // The function is intended to be extendable, but not by changes
566 // not documented clearly above.
568 case 'contributionPageRecurringHelp':
569 // require exactly two parameters
570 if (array_keys($params) == [
571 'is_recur_installments',
574 $gotText = ts('Your recurring contribution will be processed automatically.');
575 if ($params['is_recur_installments']) {
576 $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.');
578 if ($params['is_email_receipt']) {
579 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
584 case 'contributionPageContinueText':
585 if ($params['amount'] <= 0) {
586 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
588 if ($this->_paymentProcessor
['billing_mode'] == 4) {
589 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']]);
591 if ($params['is_payment_to_existing']) {
592 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
594 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
596 case 'cancelRecurDetailText':
597 if ($params['mode'] === 'auto_renew') {
598 return ts('Click the button below if you want to cancel the auto-renewal option for your %1 membership. This will not cancel your membership. However you will need to arrange payment for renewal when your membership expires.',
599 [1 => $params['membershipType']]
603 $text = ts('Recurring Contribution Details: %1 every %2 %3', [
604 1 => CRM_Utils_Money
::format($params['amount'], $params['currency']),
605 2 => $params['frequency_interval'],
606 3 => $params['frequency_unit'],
608 if (!empty($params['installments'])) {
609 $text .= ' ' . ts('for %1 installments', [1 => $params['installments']]) . '.';
611 $text = "<strong>{$text}</strong><div class='content'>";
612 $text .= ts('Click the button below to cancel this commitment and stop future transactions. This does not affect contributions which have already been completed.');
617 case 'cancelRecurNotSupportedText':
618 return ts('Automatic cancellation is not supported for this payment processor. You or the contributor will need to manually cancel this recurring contribution using the payment processor website.');
621 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
626 * Getter for accessing member vars.
628 * @todo believe this is unused
630 * @param string $name
634 public function getVar($name) {
635 return $this->$name ??
NULL;
639 * Get name for the payment information type.
640 * @todo - use option group + name field (like Omnipay does)
643 public function getPaymentTypeName() {
644 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
648 * Get label for the payment information type.
649 * @todo - use option group + labels (like Omnipay does)
652 public function getPaymentTypeLabel() {
653 return $this->_paymentProcessor
['payment_type'] == 1 ?
ts('Credit Card') : ts('Direct Debit');
657 * Get array of fields that should be displayed on the payment form.
660 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
662 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
667 * Array of payment fields appropriate to the payment processor.
669 * @throws CiviCRM_API3_Exception
671 public function getPaymentFormFields() {
672 if ($this->_paymentProcessor
['billing_mode'] == 4) {
675 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
679 * Get an array of the fields that can be edited on the recurring contribution.
681 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
682 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
683 * can be updated from the contribution recur edit screen.
685 * The fields are likely to be a subset of these
688 * - 'frequency_interval',
689 * - 'frequency_unit',
691 * - 'next_sched_contribution_date',
693 * - 'failure_retry_day',
695 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
696 * metadata is not defined in the xml for the field it will cause an error.
698 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
699 * form (UpdateSubscription).
703 public function getEditableRecurringScheduleFields() {
704 if ($this->supports('changeSubscriptionAmount')) {
711 * Get the help text to present on the recurring update page.
713 * This should reflect what can or cannot be edited.
717 public function getRecurringScheduleUpdateHelpText() {
718 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
719 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.');
721 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.');
725 * Get the metadata for all required fields.
729 protected function getMandatoryFields() {
730 $mandatoryFields = [];
731 foreach ($this->getAllFields() as $field_name => $field_spec) {
732 if (!empty($field_spec['is_required'])) {
733 $mandatoryFields[$field_name] = $field_spec;
736 return $mandatoryFields;
740 * Get the metadata of all the fields configured for this processor.
744 * @throws \CiviCRM_API3_Exception
746 protected function getAllFields() {
747 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
748 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
749 return array_merge($paymentFields, $billingFields);
753 * Get array of fields that should be displayed on the payment form for credit cards.
757 protected function getCreditCardFormFields() {
760 'credit_card_number',
762 'credit_card_exp_date',
767 * Get array of fields that should be displayed on the payment form for direct debits.
771 protected function getDirectDebitFormFields() {
774 'bank_account_number',
775 'bank_identification_number',
781 * Return an array of all the details about the fields potentially required for payment fields.
783 * Only those determined by getPaymentFormFields will actually be assigned to the form
788 public function getPaymentFormFieldsMetadata() {
789 //@todo convert credit card type into an option value
790 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
791 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
792 if (!$this->isBackOffice()) {
793 $isCVVRequired = TRUE;
796 'credit_card_number' => [
797 'htmlType' => 'text',
798 'name' => 'credit_card_number',
799 'title' => ts('Card Number'),
803 'autocomplete' => 'off',
804 'class' => 'creditcard',
806 'is_required' => TRUE,
807 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
810 'htmlType' => 'text',
812 'title' => ts('Security Code'),
816 'autocomplete' => 'off',
818 'is_required' => $isCVVRequired,
821 '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.'),
822 'rule_name' => 'integer',
823 'rule_parameters' => NULL,
827 'credit_card_exp_date' => [
828 'htmlType' => 'date',
829 'name' => 'credit_card_exp_date',
830 'title' => ts('Expiration Date'),
831 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
832 'is_required' => TRUE,
835 'rule_message' => ts('Card expiration date cannot be a past date.'),
836 'rule_name' => 'currentDate',
837 'rule_parameters' => TRUE,
840 'extra' => ['class' => 'crm-form-select'],
842 'credit_card_type' => [
843 'htmlType' => 'select',
844 'name' => 'credit_card_type',
845 'title' => ts('Card Type'),
846 'attributes' => $creditCardType,
847 'is_required' => FALSE,
849 'account_holder' => [
850 'htmlType' => 'text',
851 'name' => 'account_holder',
852 'title' => ts('Account Holder'),
856 'autocomplete' => 'on',
858 'is_required' => TRUE,
860 //e.g. IBAN can have maxlength of 34 digits
861 'bank_account_number' => [
862 'htmlType' => 'text',
863 'name' => 'bank_account_number',
864 'title' => ts('Bank Account Number'),
868 'autocomplete' => 'off',
872 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
873 'rule_name' => 'nopunctuation',
874 'rule_parameters' => NULL,
877 'is_required' => TRUE,
879 //e.g. SWIFT-BIC can have maxlength of 11 digits
880 'bank_identification_number' => [
881 'htmlType' => 'text',
882 'name' => 'bank_identification_number',
883 'title' => ts('Bank Identification Number'),
887 'autocomplete' => 'off',
889 'is_required' => TRUE,
892 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
893 'rule_name' => 'nopunctuation',
894 'rule_parameters' => NULL,
899 'htmlType' => 'text',
900 'name' => 'bank_name',
901 'title' => ts('Bank Name'),
905 'autocomplete' => 'off',
907 'is_required' => TRUE,
911 'htmlType' => 'text',
912 'name' => 'check_number',
913 'title' => ts('Check Number'),
914 'is_required' => FALSE,
915 'attributes' => NULL,
917 'pan_truncation' => [
918 'htmlType' => 'text',
919 'name' => 'pan_truncation',
920 'title' => ts('Last 4 digits of the card'),
921 'is_required' => FALSE,
926 'autocomplete' => 'off',
930 'rule_message' => ts('Please enter valid last 4 digit card number.'),
931 'rule_name' => 'numeric',
932 'rule_parameters' => NULL,
937 'htmlType' => 'hidden',
938 'name' => 'payment_token',
939 'title' => ts('Authorization token'),
940 'is_required' => FALSE,
943 'autocomplete' => 'off',
944 'id' => 'payment_token',
951 * Get billing fields required for this processor.
953 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
956 * @param int $billingLocationID
960 public function getBillingAddressFields($billingLocationID = NULL) {
961 if (!$billingLocationID) {
962 // Note that although the billing id is passed around the forms the idea that it would be anything other than
963 // the result of the function below doesn't seem to have eventuated.
964 // So taking this as a param is possibly something to be removed in favour of the standard default.
965 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
967 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
971 'first_name' => 'billing_first_name',
972 'middle_name' => 'billing_middle_name',
973 'last_name' => 'billing_last_name',
974 'street_address' => "billing_street_address-{$billingLocationID}",
975 'city' => "billing_city-{$billingLocationID}",
976 'country' => "billing_country_id-{$billingLocationID}",
977 'state_province' => "billing_state_province_id-{$billingLocationID}",
978 'postal_code' => "billing_postal_code-{$billingLocationID}",
983 * Get form metadata for billing address fields.
985 * @param int $billingLocationID
988 * Array of metadata for address fields.
990 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
991 if (!$billingLocationID) {
992 // Note that although the billing id is passed around the forms the idea that it would be anything other than
993 // the result of the function below doesn't seem to have eventuated.
994 // So taking this as a param is possibly something to be removed in favour of the standard default.
995 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
998 $metadata['billing_first_name'] = [
999 'htmlType' => 'text',
1000 'name' => 'billing_first_name',
1001 'title' => ts('Billing First Name'),
1006 'autocomplete' => 'off',
1008 'is_required' => TRUE,
1011 $metadata['billing_middle_name'] = [
1012 'htmlType' => 'text',
1013 'name' => 'billing_middle_name',
1014 'title' => ts('Billing Middle Name'),
1019 'autocomplete' => 'off',
1021 'is_required' => FALSE,
1024 $metadata['billing_last_name'] = [
1025 'htmlType' => 'text',
1026 'name' => 'billing_last_name',
1027 'title' => ts('Billing Last Name'),
1032 'autocomplete' => 'off',
1034 'is_required' => TRUE,
1037 $metadata["billing_street_address-{$billingLocationID}"] = [
1038 'htmlType' => 'text',
1039 'name' => "billing_street_address-{$billingLocationID}",
1040 'title' => ts('Street Address'),
1045 'autocomplete' => 'off',
1047 'is_required' => TRUE,
1050 $metadata["billing_city-{$billingLocationID}"] = [
1051 'htmlType' => 'text',
1052 'name' => "billing_city-{$billingLocationID}",
1053 'title' => ts('City'),
1058 'autocomplete' => 'off',
1060 'is_required' => TRUE,
1063 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1064 'htmlType' => 'chainSelect',
1065 'title' => ts('State/Province'),
1066 'name' => "billing_state_province_id-{$billingLocationID}",
1068 'is_required' => TRUE,
1071 $metadata["billing_postal_code-{$billingLocationID}"] = [
1072 'htmlType' => 'text',
1073 'name' => "billing_postal_code-{$billingLocationID}",
1074 'title' => ts('Postal Code'),
1079 'autocomplete' => 'off',
1081 'is_required' => TRUE,
1084 $metadata["billing_country_id-{$billingLocationID}"] = [
1085 'htmlType' => 'select',
1086 'name' => "billing_country_id-{$billingLocationID}",
1087 'title' => ts('Country'),
1090 '' => ts('- select -'),
1091 ] + CRM_Core_PseudoConstant
::country(),
1092 'is_required' => TRUE,
1098 * Get base url dependent on component.
1100 * (or preferably set it using the setter function).
1104 protected function getBaseReturnUrl() {
1105 if ($this->baseReturnUrl
) {
1106 return $this->baseReturnUrl
;
1108 if ($this->_component
== 'event') {
1109 $baseURL = 'civicrm/event/register';
1112 $baseURL = 'civicrm/contribute/transact';
1118 * Get the currency for the transaction from the params.
1120 * Legacy wrapper. Better for a method to work on its own PropertyBag.
1122 * This code now uses PropertyBag to allow for old inputs like currencyID.
1128 protected function getCurrency($params = []) {
1129 $localPropertyBag = new PropertyBag();
1130 $localPropertyBag->mergeLegacyInputParams($params);
1131 return $localPropertyBag->getCurrency();
1135 * Legacy. Better for a method to work on its own PropertyBag,
1136 * but also, this function does not do very much.
1138 * @param array $params
1141 * @throws \CRM_Core_Exception
1143 protected function getAmount($params = []) {
1144 return CRM_Utils_Money
::format($params['amount'], NULL, NULL, TRUE);
1148 * Get url to return to after cancelled or failed transaction.
1150 * @param string $qfKey
1151 * @param int $participantID
1153 * @return string cancel url
1155 public function getCancelUrl($qfKey, $participantID) {
1156 if (isset($this->cancelUrl
)) {
1157 return $this->cancelUrl
;
1160 if ($this->_component
== 'event') {
1161 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1164 'participantId' => $participantID,
1170 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1171 '_qf_Main_display' => 1,
1180 * Get URL to return the browser to on success.
1186 protected function getReturnSuccessUrl($qfKey) {
1187 if (isset($this->successUrl
)) {
1188 return $this->successUrl
;
1191 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1192 '_qf_ThankYou_display' => 1,
1200 * Get URL to return the browser to on failure.
1202 * @param string $key
1203 * @param int $participantID
1204 * @param int $eventID
1207 * URL for a failing transactor to be redirected to.
1209 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1210 if (isset($this->cancelUrl
)) {
1211 return $this->cancelUrl
;
1214 $test = $this->_is_test ?
'&action=preview' : '';
1215 if ($this->_component
== "event") {
1216 return CRM_Utils_System
::url('civicrm/event/register',
1217 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1222 return CRM_Utils_System
::url('civicrm/contribute/transact',
1223 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1230 * Get URl for when the back button is pressed.
1234 * @return string url
1236 protected function getGoBackUrl($qfKey) {
1237 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1238 '_qf_Confirm_display' => 'true',
1246 * Get the notify (aka ipn, web hook or silent post) url.
1248 * If there is no '.' in it we assume that we are dealing with localhost or
1249 * similar and it is unreachable from the web & hence invalid.
1252 * URL to notify outcome of transaction.
1254 protected function getNotifyUrl() {
1255 $url = CRM_Utils_System
::url(
1256 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1263 return (stristr($url, '.')) ?
$url : '';
1267 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1269 * Does a server to server payment transaction.
1271 * @param array $params
1272 * Assoc array of input parameters for this transaction.
1275 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1277 protected function doDirectPayment(&$params) {
1282 * Processors may need to inspect, validate, cast and copy data that is
1283 * specific to this Payment Processor from the input array to custom fields
1284 * on the PropertyBag.
1286 * @param Civi\Payment\PropertyBag $propertyBag
1287 * @param array $params
1288 * @param string $component
1290 * @throws \Civi\Payment\Exception\PaymentProcessorException
1292 public function extractCustomPropertiesForDoPayment(PropertyBag
$propertyBag, array $params, $component = 'contribute') {
1294 // (validation and casting goes first)
1295 // $propertyBag->setCustomProperty('myprocessor_customPropertyName', $value);
1299 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1300 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1302 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1303 * the transaction & in fact doTransferCheckout would not traditionally come back.
1304 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1306 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1307 * In some cases the IPN will set the payment to "Completed" some time later.
1309 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1310 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1311 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1313 * @param array|PropertyBag $params
1315 * @param string $component
1318 * Result array (containing at least the key payment_status_id)
1320 * @throws \Civi\Payment\Exception\PaymentProcessorException
1322 public function doPayment(&$params, $component = 'contribute') {
1323 $this->_component
= $component;
1324 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1326 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1327 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1328 // have an example of that at the mome.
1329 if ($params['amount'] == 0) {
1330 $result['payment_status_id'] = array_search('Completed', $statuses);
1334 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1335 $result = $this->doTransferCheckout($params, $component);
1336 if (is_array($result) && !isset($result['payment_status_id'])) {
1337 $result['payment_status_id'] = array_search('Pending', $statuses);
1341 $result = $this->doDirectPayment($params, $component);
1342 if (is_array($result) && !isset($result['payment_status_id'])) {
1343 if (!empty($params['is_recur'])) {
1344 // See comment block.
1345 $result['payment_status_id'] = array_search('Pending', $statuses);
1348 $result['payment_status_id'] = array_search('Completed', $statuses);
1352 if (is_a($result, 'CRM_Core_Error')) {
1353 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1359 * Cancel a recurring subscription.
1361 * Payment processor classes should override this rather than implementing cancelSubscription.
1363 * A PaymentProcessorException should be thrown if the update of the contribution_recur
1364 * record should not proceed (in many cases this function does nothing
1365 * as the payment processor does not need to take any action & this should silently
1366 * proceed. Note the form layer will only call this after calling
1367 * $processor->supports('cancelRecurring');
1369 * @param \Civi\Payment\PropertyBag $propertyBag
1373 * @throws \Civi\Payment\Exception\PaymentProcessorException
1375 public function doCancelRecurring(PropertyBag
$propertyBag) {
1376 if (method_exists($this, 'cancelSubscription')) {
1378 if ($this->cancelSubscription($message, $propertyBag)) {
1379 return ['message' => $message];
1381 throw new PaymentProcessorException($message);
1383 return ['message' => ts('Recurring contribution cancelled')];
1389 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1391 * @param array $params
1393 * @throws \Civi\Payment\Exception\PaymentProcessorException
1395 public function doRefund(&$params) {}
1398 * Query payment processor for details about a transaction.
1400 * @param array $params
1401 * Array of parameters containing one of:
1402 * - trxn_id Id of an individual transaction.
1403 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1406 * Extra parameters retrieved.
1407 * Any parameters retrievable through this should be documented in the function comments at
1408 * CRM_Core_Payment::doQuery. Currently:
1409 * - fee_amount Amount of fee paid
1411 public function doQuery($params) {
1416 * This function checks to see if we have the right config values.
1419 * the error message if any
1421 abstract protected function checkConfig();
1424 * Redirect for paypal.
1426 * @todo move to paypal class or remove
1428 * @param $paymentProcessor
1432 public static function paypalRedirect(&$paymentProcessor) {
1433 if (!$paymentProcessor) {
1437 if (isset($_GET['payment_date']) &&
1438 isset($_GET['merchant_return_link']) &&
1439 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1440 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1449 * Handle incoming payment notification.
1451 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1453 * @todo move to0 \Civi\Payment\System factory method
1454 * Page callback for civicrm/payment/ipn
1456 public static function handleIPN() {
1458 self
::handlePaymentMethod(
1459 'PaymentNotification',
1461 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1462 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1463 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1467 catch (CRM_Core_Exception
$e) {
1468 Civi
::log()->error('ipn_payment_callback_exception', [
1470 'backtrace' => CRM_Core_Error
::formatBacktrace(debug_backtrace()),
1474 CRM_Utils_System
::civiExit();
1478 * Payment callback handler.
1480 * The processor_name or processor_id is passed in.
1481 * Note that processor_id is more reliable as one site may have more than one instance of a
1482 * processor & ideally the processor will be validating the results
1483 * Load requested payment processor and call that processor's handle<$method> method
1485 * @todo move to \Civi\Payment\System factory method
1487 * @param string $method
1488 * 'PaymentNotification' or 'PaymentCron'
1489 * @param array $params
1491 * @throws \CRM_Core_Exception
1492 * @throws \Exception
1494 public static function handlePaymentMethod($method, $params = []) {
1495 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1496 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1497 $lastParam = array_pop($q);
1498 if (is_numeric($lastParam)) {
1499 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1502 self
::logPaymentNotification($params);
1503 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1507 self
::logPaymentNotification($params);
1509 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1510 FROM civicrm_payment_processor_type ppt
1511 INNER JOIN civicrm_payment_processor pp
1512 ON pp.payment_processor_type_id = ppt.id
1515 if (isset($params['processor_id'])) {
1516 $sql .= " WHERE pp.id = %2";
1517 $args[2] = [$params['processor_id'], 'Integer'];
1518 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1521 // This is called when processor_name is passed - passing processor_id instead is recommended.
1522 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1524 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1527 $args[2] = [$params['processor_name'], 'String'];
1528 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1531 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1533 // Check whether we found anything at all.
1535 throw new CRM_Core_Exception($notFound);
1538 $method = 'handle' . $method;
1539 $extension_instance_found = FALSE;
1541 // In all likelihood, we'll just end up with the one instance returned here. But it's
1542 // possible we may get more. Hence, iterate through all instances ..
1544 while ($dao->fetch()) {
1545 // Check pp is extension - is this still required - surely the singleton below handles it.
1546 $ext = CRM_Extension_System
::singleton()->getMapper();
1547 if ($ext->isExtensionKey($dao->class_name
)) {
1548 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1549 require_once $ext->classToPath($paymentClass);
1552 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1554 // Should never be empty - we already established this processor_id exists and is active.
1555 if (empty($processorInstance)) {
1559 // Does PP implement this method, and can we call it?
1560 if (!method_exists($processorInstance, $method) ||
1561 !is_callable([$processorInstance, $method])
1563 // on the off chance there is a double implementation of this processor we should keep looking for another
1564 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1568 // Everything, it seems, is ok - execute pp callback handler
1569 $processorInstance->$method();
1570 $extension_instance_found = TRUE;
1573 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1574 $IPNParams = array_merge($_GET, $_REQUEST);
1575 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1576 if (!$extension_instance_found) {
1577 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1578 "%2 method is unsupported in legacy payment processors.";
1579 throw new CRM_Core_Exception(ts($message, [
1580 1 => $params['processor_name'],
1587 * Check whether a method is present ( & supported ) by the payment processor object.
1589 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1591 * @param string $method
1592 * Method to check for.
1596 public function isSupported($method) {
1597 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1601 * Some processors replace the form submit button with their own.
1603 * Returning false here will leave the button off front end forms.
1605 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1607 public function isSuppressSubmitButtons() {
1612 * Checks to see if invoice_id already exists in db.
1614 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1615 * it is better to standardise to being here.
1617 * @param int $invoiceId The ID to check.
1619 * @param null $contributionID
1620 * If a contribution exists pass in the contribution ID.
1623 * True if invoice ID otherwise exists, else false
1625 protected function checkDupe($invoiceId, $contributionID = NULL) {
1626 $contribution = new CRM_Contribute_DAO_Contribution();
1627 $contribution->invoice_id
= $invoiceId;
1628 if ($contributionID) {
1629 $contribution->whereAdd("id <> $contributionID");
1631 return $contribution->find();
1635 * Get url for users to manage this recurring contribution for this processor.
1637 * @param int $entityID
1638 * @param null $entity
1639 * @param string $action
1643 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1647 if (!$this->supports('cancelRecurring')) {
1650 $url = 'civicrm/contribute/unsubscribe';
1654 //in notify mode don't return the update billing url
1655 if (!$this->supports('updateSubscriptionBillingInfo')) {
1658 $url = 'civicrm/contribute/updatebilling';
1662 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1665 $url = 'civicrm/contribute/updaterecur';
1669 $userId = CRM_Core_Session
::singleton()->get('userID');
1671 $checksumValue = '';
1674 // Find related Contact
1678 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1682 case 'contribution':
1683 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1684 $entityArg = 'coid';
1689 SELECT DISTINCT con.contact_id
1690 FROM civicrm_contribution_recur rec
1691 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1693 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1699 $entityArg = 'crid';
1704 // Add entity arguments
1705 if ($entityArg != '') {
1706 // Add checksum argument
1707 if ($contactID != 0 && $userId != $contactID) {
1708 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1710 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1714 if ($this->supports('accountLoginURL')) {
1715 return $this->accountLoginURL();
1719 return $this->_paymentProcessor
['url_recur'] ??
'';
1723 * Get description of payment to pass to processor.
1725 * This is often what people see in the interface so we want to get
1726 * as much unique information in as possible within the field length (& presumably the early part of the field)
1728 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1729 * having field names to clarify
1731 * @param array $params
1732 * @param int $length
1736 protected function getPaymentDescription($params = [], $length = 24) {
1737 $propertyBag = PropertyBag
::cast($params);
1739 $propertyBag->getter('contactID', TRUE),
1740 $propertyBag->getter('contributionID', TRUE),
1741 $propertyBag->getter('description', TRUE) ?
: ($propertyBag->getter('isRecur', TRUE) ?
ts('Recurring payment') : NULL),
1742 $propertyBag->getter('billing_first_name', TRUE),
1743 $propertyBag->getter('billing_last_name', TRUE),
1745 return substr(implode('-', array_filter($parts)), 0, $length);
1749 * Checks if back-office recurring edit is allowed
1753 public function supportsEditRecurringContribution() {
1758 * Does this processor support changing the amount for recurring contributions through code.
1760 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1761 * that will be updated at the payment processor.
1765 protected function supportsChangeSubscriptionAmount() {
1766 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
1770 * Checks if payment processor supports recurring contributions
1774 public function supportsRecurring() {
1775 if (!empty($this->_paymentProcessor
['is_recur'])) {
1782 * Checks if payment processor supports an account login URL
1783 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1784 * TODO: It is implemented by AuthorizeNET, any others?
1788 protected function supportsAccountLoginURL() {
1789 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
1793 * Should a receipt be sent out for a pending payment.
1795 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1797 public function isSendReceiptForPending() {