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 unused parameter).
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']);
361 * Are test payments supported.
365 protected function supportsTestMode() {
366 return !empty($this->_paymentProcessor
['is_test']);
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 the processor support the user having a choice as to whether to cancel the recurring with the processor?
405 * If this returns TRUE then there will be an option to send a cancellation request in the cancellation form.
407 * This would normally be false for processors where CiviCRM maintains the schedule.
411 protected function supportsCancelRecurringNotifyOptional() {
412 return $this->supportsCancelRecurring();
416 * Does this processor support pre-approval.
418 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
420 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
421 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
422 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
426 protected function supportsPreApproval() {
431 * Does this processor support updating billing info for recurring contributions through code.
433 * If the processor returns true then it must be possible to update billing info from within CiviCRM
434 * that will be updated at the payment processor.
438 protected function supportsUpdateSubscriptionBillingInfo() {
439 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
443 * Can recurring contributions be set against pledges.
445 * In practice all processors that use the baseIPN function to finish transactions or
446 * call the completetransaction api support this by looking up previous contributions in the
447 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
448 * adding the new payment to the pledge.
450 * However, only enabling for processors it has been tested against.
454 protected function supportsRecurContributionsForPledges() {
459 * Does the processor work without an email address?
461 * The historic assumption is that all processors require an email address. This capability
462 * allows a processor to state it does not need to be provided with an email address.
463 * NB: when this was added (Feb 2020), the Manual processor class overrides this but
464 * the only use of the capability is in the webform_civicrm module. It is not currently
465 * used in core but may be in future.
469 protected function supportsNoEmailProvided() {
474 * Function to action pre-approval if supported
476 * @param array $params
477 * Parameters from the form
479 * This function returns an array which should contain
480 * - pre_approval_parameters (this will be stored on the calling form & available later)
481 * - redirect_url (if set the browser will be redirected to this.
483 public function doPreApproval(&$params) {
487 * Get any details that may be available to the payment processor due to an approval process having happened.
489 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
492 * @param array $storedDetails
496 public function getPreApprovalDetails($storedDetails) {
501 * Default payment instrument validation.
503 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
504 * Not a static function, because I need to check for payment_type.
506 * @param array $values
507 * @param array $errors
509 public function validatePaymentInstrument($values, &$errors) {
510 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
511 if ($this->_paymentProcessor
['payment_type'] == 1) {
512 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
517 * Getter for the payment processor.
519 * The payment processor array is based on the civicrm_payment_processor table entry.
522 * Payment processor array.
524 public function getPaymentProcessor() {
525 return $this->_paymentProcessor
;
529 * Setter for the payment processor.
531 * @param array $processor
533 public function setPaymentProcessor($processor) {
534 $this->_paymentProcessor
= $processor;
538 * Setter for the payment form that wants to use the processor.
542 * @param CRM_Core_Form $paymentForm
544 public function setForm(&$paymentForm) {
545 $this->_paymentForm
= $paymentForm;
549 * Getter for payment form that is using the processor.
551 * @return CRM_Core_Form
554 public function getForm() {
555 return $this->_paymentForm
;
559 * Get help text information (help, description, etc.) about this payment,
560 * to display to the user.
562 * @param string $context
563 * Context of the text.
564 * Only explicitly supported contexts are handled without error.
565 * Currently supported:
566 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
567 * - contributionPageContinueText (params: amount, is_payment_to_existing)
568 * - cancelRecurDetailText:
570 * mode, amount, currency, frequency_interval, frequency_unit,
571 * installments, {membershipType|only if mode=auto_renew},
572 * selfService (bool) - TRUE if user doesn't have "edit contributions" permission.
573 * ie. they are accessing via a "self-service" link from an email receipt or similar.
574 * - cancelRecurNotSupportedText
576 * @param array $params
577 * Parameters for the field, context specific.
581 public function getText($context, $params) {
582 // I have deliberately added a noisy fail here.
583 // The function is intended to be extendable, but not by changes
584 // not documented clearly above.
586 case 'contributionPageRecurringHelp':
587 if ($params['is_recur_installments']) {
588 return 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.');
592 case 'contributionPageContinueText':
593 return ts('Click the <strong>Continue</strong> button to proceed with the payment.');
595 case 'cancelRecurDetailText':
596 if ($params['mode'] === 'auto_renew') {
597 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.',
598 [1 => $params['membershipType']]
602 $text = ts('Recurring Contribution Details: %1 every %2 %3', [
603 1 => CRM_Utils_Money
::format($params['amount'], $params['currency']),
604 2 => $params['frequency_interval'],
605 3 => $params['frequency_unit'],
607 if (!empty($params['installments'])) {
608 $text .= ' ' . ts('for %1 installments', [1 => $params['installments']]) . '.';
610 $text = "<strong>{$text}</strong><div class='content'>";
611 $text .= ts('Click the button below to cancel this commitment and stop future transactions. This does not affect contributions which have already been completed.');
616 case 'cancelRecurNotSupportedText':
617 if (!$this->supportsCancelRecurring()) {
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.');
623 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
628 * Get the title of the payment processor to display to the user
632 public function getTitle() {
633 return $this->getPaymentProcessor()['title'] ??
$this->getPaymentProcessor()['name'];
637 * Getter for accessing member vars.
639 * @todo believe this is unused
641 * @param string $name
645 public function getVar($name) {
646 return $this->$name ??
NULL;
650 * Get name for the payment information type.
651 * @todo - use option group + name field (like Omnipay does)
654 public function getPaymentTypeName() {
655 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
659 * Get label for the payment information type.
660 * @todo - use option group + labels (like Omnipay does)
663 public function getPaymentTypeLabel() {
664 return $this->_paymentProcessor
['payment_type'] == 1 ?
ts('Credit Card') : ts('Direct Debit');
668 * Get array of fields that should be displayed on the payment form.
671 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
673 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
678 * Array of payment fields appropriate to the payment processor.
680 * @throws CiviCRM_API3_Exception
682 public function getPaymentFormFields() {
683 if ($this->_paymentProcessor
['billing_mode'] == 4) {
686 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
690 * Get an array of the fields that can be edited on the recurring contribution.
692 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
693 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
694 * can be updated from the contribution recur edit screen.
696 * The fields are likely to be a subset of these
699 * - 'frequency_interval',
700 * - 'frequency_unit',
702 * - 'next_sched_contribution_date',
704 * - 'failure_retry_day',
706 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
707 * metadata is not defined in the xml for the field it will cause an error.
709 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
710 * form (UpdateSubscription).
714 public function getEditableRecurringScheduleFields() {
715 if ($this->supports('changeSubscriptionAmount')) {
722 * Get the help text to present on the recurring update page.
724 * This should reflect what can or cannot be edited.
728 public function getRecurringScheduleUpdateHelpText() {
729 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
730 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.');
732 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.');
736 * Get the metadata for all required fields.
740 protected function getMandatoryFields() {
741 $mandatoryFields = [];
742 foreach ($this->getAllFields() as $field_name => $field_spec) {
743 if (!empty($field_spec['is_required'])) {
744 $mandatoryFields[$field_name] = $field_spec;
747 return $mandatoryFields;
751 * Get the metadata of all the fields configured for this processor.
755 * @throws \CiviCRM_API3_Exception
757 protected function getAllFields() {
758 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
759 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
760 return array_merge($paymentFields, $billingFields);
764 * Get array of fields that should be displayed on the payment form for credit cards.
768 protected function getCreditCardFormFields() {
771 'credit_card_number',
773 'credit_card_exp_date',
778 * Get array of fields that should be displayed on the payment form for direct debits.
782 protected function getDirectDebitFormFields() {
785 'bank_account_number',
786 'bank_identification_number',
792 * Return an array of all the details about the fields potentially required for payment fields.
794 * Only those determined by getPaymentFormFields will actually be assigned to the form
799 public function getPaymentFormFieldsMetadata() {
800 //@todo convert credit card type into an option value
801 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
802 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
803 if (!$this->isBackOffice()) {
804 $isCVVRequired = TRUE;
807 'credit_card_number' => [
808 'htmlType' => 'text',
809 'name' => 'credit_card_number',
810 'title' => ts('Card Number'),
814 'autocomplete' => 'off',
815 'class' => 'creditcard required',
817 'is_required' => TRUE,
818 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
821 'htmlType' => 'text',
823 'title' => ts('Security Code'),
827 'autocomplete' => 'off',
828 'class' => ($isCVVRequired ?
'required' : ''),
830 'is_required' => $isCVVRequired,
833 '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.'),
834 'rule_name' => 'integer',
835 'rule_parameters' => NULL,
839 'credit_card_exp_date' => [
840 'htmlType' => 'date',
841 'name' => 'credit_card_exp_date',
842 'title' => ts('Expiration Date'),
843 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
844 'is_required' => TRUE,
847 'rule_message' => ts('Card expiration date cannot be a past date.'),
848 'rule_name' => 'currentDate',
849 'rule_parameters' => TRUE,
852 'extra' => ['class' => 'crm-form-select required'],
854 'credit_card_type' => [
855 'htmlType' => 'select',
856 'name' => 'credit_card_type',
857 'title' => ts('Card Type'),
858 'attributes' => $creditCardType,
859 'is_required' => FALSE,
861 'account_holder' => [
862 'htmlType' => 'text',
863 'name' => 'account_holder',
864 'title' => ts('Account Holder'),
868 'autocomplete' => 'on',
869 'class' => 'required',
871 'is_required' => TRUE,
873 //e.g. IBAN can have maxlength of 34 digits
874 'bank_account_number' => [
875 'htmlType' => 'text',
876 'name' => 'bank_account_number',
877 'title' => ts('Bank Account Number'),
881 'autocomplete' => 'off',
882 'class' => 'required',
886 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
887 'rule_name' => 'nopunctuation',
888 'rule_parameters' => NULL,
891 'is_required' => TRUE,
893 //e.g. SWIFT-BIC can have maxlength of 11 digits
894 'bank_identification_number' => [
895 'htmlType' => 'text',
896 'name' => 'bank_identification_number',
897 'title' => ts('Bank Identification Number'),
901 'autocomplete' => 'off',
902 'class' => 'required',
904 'is_required' => TRUE,
907 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
908 'rule_name' => 'nopunctuation',
909 'rule_parameters' => NULL,
914 'htmlType' => 'text',
915 'name' => 'bank_name',
916 'title' => ts('Bank Name'),
920 'autocomplete' => 'off',
921 'class' => 'required',
923 'is_required' => TRUE,
927 'htmlType' => 'text',
928 'name' => 'check_number',
929 'title' => ts('Check Number'),
930 'is_required' => FALSE,
931 'attributes' => NULL,
933 'pan_truncation' => [
934 'htmlType' => 'text',
935 'name' => 'pan_truncation',
936 'title' => ts('Last 4 digits of the card'),
937 'is_required' => FALSE,
942 'autocomplete' => 'off',
946 'rule_message' => ts('Please enter valid last 4 digit card number.'),
947 'rule_name' => 'numeric',
948 'rule_parameters' => NULL,
953 'htmlType' => 'hidden',
954 'name' => 'payment_token',
955 'title' => ts('Authorization token'),
956 'is_required' => FALSE,
959 'autocomplete' => 'off',
960 'id' => 'payment_token',
967 * Get billing fields required for this processor.
969 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
972 * @param int $billingLocationID
976 public function getBillingAddressFields($billingLocationID = NULL) {
977 if (!$billingLocationID) {
978 // Note that although the billing id is passed around the forms the idea that it would be anything other than
979 // the result of the function below doesn't seem to have eventuated.
980 // So taking this as a param is possibly something to be removed in favour of the standard default.
981 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
983 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
987 'first_name' => 'billing_first_name',
988 'middle_name' => 'billing_middle_name',
989 'last_name' => 'billing_last_name',
990 'street_address' => "billing_street_address-{$billingLocationID}",
991 'city' => "billing_city-{$billingLocationID}",
992 'country' => "billing_country_id-{$billingLocationID}",
993 'state_province' => "billing_state_province_id-{$billingLocationID}",
994 'postal_code' => "billing_postal_code-{$billingLocationID}",
999 * Get form metadata for billing address fields.
1001 * @param int $billingLocationID
1004 * Array of metadata for address fields.
1006 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
1007 if (!$billingLocationID) {
1008 // Note that although the billing id is passed around the forms the idea that it would be anything other than
1009 // the result of the function below doesn't seem to have eventuated.
1010 // So taking this as a param is possibly something to be removed in favour of the standard default.
1011 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
1014 $metadata['billing_first_name'] = [
1015 'htmlType' => 'text',
1016 'name' => 'billing_first_name',
1017 'title' => ts('Billing First Name'),
1022 'autocomplete' => 'off',
1023 'class' => 'required',
1025 'is_required' => TRUE,
1028 $metadata['billing_middle_name'] = [
1029 'htmlType' => 'text',
1030 'name' => 'billing_middle_name',
1031 'title' => ts('Billing Middle Name'),
1036 'autocomplete' => 'off',
1038 'is_required' => FALSE,
1041 $metadata['billing_last_name'] = [
1042 'htmlType' => 'text',
1043 'name' => 'billing_last_name',
1044 'title' => ts('Billing Last Name'),
1049 'autocomplete' => 'off',
1050 'class' => 'required',
1052 'is_required' => TRUE,
1055 $metadata["billing_street_address-{$billingLocationID}"] = [
1056 'htmlType' => 'text',
1057 'name' => "billing_street_address-{$billingLocationID}",
1058 'title' => ts('Street Address'),
1063 'autocomplete' => 'off',
1064 'class' => 'required',
1066 'is_required' => TRUE,
1069 $metadata["billing_city-{$billingLocationID}"] = [
1070 'htmlType' => 'text',
1071 'name' => "billing_city-{$billingLocationID}",
1072 'title' => ts('City'),
1077 'autocomplete' => 'off',
1078 'class' => 'required',
1080 'is_required' => TRUE,
1083 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1084 'htmlType' => 'chainSelect',
1085 'title' => ts('State/Province'),
1086 'name' => "billing_state_province_id-{$billingLocationID}",
1088 'is_required' => TRUE,
1089 'extra' => ['class' => 'required'],
1092 $metadata["billing_postal_code-{$billingLocationID}"] = [
1093 'htmlType' => 'text',
1094 'name' => "billing_postal_code-{$billingLocationID}",
1095 'title' => ts('Postal Code'),
1100 'autocomplete' => 'off',
1101 'class' => 'required',
1103 'is_required' => TRUE,
1106 $metadata["billing_country_id-{$billingLocationID}"] = [
1107 'htmlType' => 'select',
1108 'name' => "billing_country_id-{$billingLocationID}",
1109 'title' => ts('Country'),
1112 '' => ts('- select -'),
1113 ] + CRM_Core_PseudoConstant
::country(),
1114 'is_required' => TRUE,
1115 'extra' => ['class' => 'required crm-form-select2 crm-select2'],
1121 * Get base url dependent on component.
1123 * (or preferably set it using the setter function).
1127 protected function getBaseReturnUrl() {
1128 if ($this->baseReturnUrl
) {
1129 return $this->baseReturnUrl
;
1131 if ($this->_component
== 'event') {
1132 $baseURL = 'civicrm/event/register';
1135 $baseURL = 'civicrm/contribute/transact';
1141 * Get the currency for the transaction from the params.
1143 * Legacy wrapper. Better for a method to work on its own PropertyBag.
1145 * This code now uses PropertyBag to allow for old inputs like currencyID.
1151 protected function getCurrency($params = []) {
1152 $localPropertyBag = new PropertyBag();
1153 $localPropertyBag->mergeLegacyInputParams($params);
1154 return $localPropertyBag->getCurrency();
1158 * Legacy. Better for a method to work on its own PropertyBag,
1159 * but also, this function does not do very much.
1161 * @param array $params
1164 * @throws \CRM_Core_Exception
1166 protected function getAmount($params = []) {
1167 if (!CRM_Utils_Rule
::numeric($params['amount'])) {
1168 CRM_Core_Error
::deprecatedWarning('Passing Amount value that is not numeric is deprecated please report this in gitlab');
1169 return CRM_Utils_Money
::formatUSLocaleNumericRounded(filter_var($params['amount'], FILTER_SANITIZE_NUMBER_FLOAT
, FILTER_FLAG_ALLOW_FRACTION
), 2);
1171 return CRM_Utils_Money
::formatUSLocaleNumericRounded($params['amount'], 2);
1175 * Get url to return to after cancelled or failed transaction.
1177 * @param string $qfKey
1178 * @param int $participantID
1180 * @return string cancel url
1182 public function getCancelUrl($qfKey, $participantID) {
1183 if (isset($this->cancelUrl
)) {
1184 return $this->cancelUrl
;
1187 if ($this->_component
== 'event') {
1188 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1191 'participantId' => $participantID,
1197 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1198 '_qf_Main_display' => 1,
1207 * Get URL to return the browser to on success.
1209 * @param string $qfKey
1213 protected function getReturnSuccessUrl($qfKey) {
1214 if (isset($this->successUrl
)) {
1215 return $this->successUrl
;
1218 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1219 '_qf_ThankYou_display' => 1,
1227 * Get URL to return the browser to on failure.
1229 * @param string $key
1230 * @param int $participantID
1231 * @param int $eventID
1234 * URL for a failing transactor to be redirected to.
1236 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1237 if (isset($this->cancelUrl
)) {
1238 return $this->cancelUrl
;
1241 $test = $this->_is_test ?
'&action=preview' : '';
1242 if ($this->_component
== "event") {
1243 return CRM_Utils_System
::url('civicrm/event/register',
1244 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1249 return CRM_Utils_System
::url('civicrm/contribute/transact',
1250 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1257 * Get URl for when the back button is pressed.
1261 * @return string url
1263 protected function getGoBackUrl($qfKey) {
1264 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1265 '_qf_Confirm_display' => 'true',
1273 * Get the notify (aka ipn, web hook or silent post) url.
1275 * If there is no '.' in it we assume that we are dealing with localhost or
1276 * similar and it is unreachable from the web & hence invalid.
1279 * URL to notify outcome of transaction.
1281 protected function getNotifyUrl() {
1282 $url = CRM_Utils_System
::getNotifyUrl(
1283 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1290 return (stristr($url, '.')) ?
$url : '';
1294 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1296 * Does a server to server payment transaction.
1298 * @param array $params
1299 * Assoc array of input parameters for this transaction.
1302 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1304 protected function doDirectPayment(&$params) {
1305 CRM_Core_Error
::deprecatedFunctionWarning('doPayment');
1310 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1313 * @param array $params
1314 * Assoc array of input parameters for this transaction.
1315 * @param string $component
1318 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1320 protected function doTransferCheckout(&$params, $component = 'contribute') {
1321 CRM_Core_Error
::deprecatedFunctionWarning('doPayment');
1326 * Processors may need to inspect, validate, cast and copy data that is
1327 * specific to this Payment Processor from the input array to custom fields
1328 * on the PropertyBag.
1330 * @param Civi\Payment\PropertyBag $propertyBag
1331 * @param array $params
1332 * @param string $component
1334 * @throws \Civi\Payment\Exception\PaymentProcessorException
1336 public function extractCustomPropertiesForDoPayment(PropertyBag
$propertyBag, array $params, $component = 'contribute') {
1338 // (validation and casting goes first)
1339 // $propertyBag->setCustomProperty('myprocessor_customPropertyName', $value);
1343 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1344 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1346 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1347 * the transaction & in fact doTransferCheckout would not traditionally come back.
1348 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1350 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1351 * In some cases the IPN will set the payment to "Completed" some time later.
1353 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1354 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1355 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1357 * @param array|PropertyBag $params
1359 * @param string $component
1362 * Result array (containing at least the key payment_status_id)
1364 * @throws \Civi\Payment\Exception\PaymentProcessorException
1366 public function doPayment(&$params, $component = 'contribute') {
1367 $propertyBag = \Civi\Payment\PropertyBag
::cast($params);
1368 $this->_component
= $component;
1369 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1371 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1372 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1373 // have an example of that at the moment.
1374 if ($propertyBag->getAmount() == 0) {
1375 $result['payment_status_id'] = array_search('Completed', $statuses);
1376 $result['payment_status'] = 'Completed';
1380 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1381 CRM_Core_Error
::deprecatedFunctionWarning('doPayment', 'doTransferCheckout');
1382 $result = $this->doTransferCheckout($params, $component);
1383 if (is_array($result) && !isset($result['payment_status_id'])) {
1384 $result['payment_status_id'] = array_search('Pending', $statuses);
1385 $result['payment_status'] = 'Pending';
1389 CRM_Core_Error
::deprecatedFunctionWarning('doPayment', 'doDirectPayment');
1390 $result = $this->doDirectPayment($params, $component);
1391 if (is_array($result) && !isset($result['payment_status_id'])) {
1392 if (!empty($params['is_recur'])) {
1393 // See comment block.
1394 $result['payment_status_id'] = array_search('Pending', $statuses);
1395 $result['payment_status'] = 'Pending';
1398 $result['payment_status_id'] = array_search('Completed', $statuses);
1399 $result['payment_status'] = 'Completed';
1403 if (is_a($result, 'CRM_Core_Error')) {
1404 CRM_Core_Error
::deprecatedFunctionWarning('payment processors should throw exceptions rather than return errors');
1405 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1411 * Cancel a recurring subscription.
1413 * Payment processor classes should override this rather than implementing cancelSubscription.
1415 * A PaymentProcessorException should be thrown if the update of the contribution_recur
1416 * record should not proceed (in many cases this function does nothing
1417 * as the payment processor does not need to take any action & this should silently
1418 * proceed. Note the form layer will only call this after calling
1419 * $processor->supports('cancelRecurring');
1421 * A payment processor can control whether to notify the actual payment provider or just
1422 * cancel in CiviCRM by setting the `isNotifyProcessorOnCancelRecur` property on PropertyBag.
1423 * If supportsCancelRecurringNotifyOptional() is TRUE this will be automatically set based on
1424 * the user selection on the form. If FALSE you need to set it yourself.
1426 * @param \Civi\Payment\PropertyBag $propertyBag
1430 * @throws \Civi\Payment\Exception\PaymentProcessorException
1432 public function doCancelRecurring(PropertyBag
$propertyBag) {
1433 if (method_exists($this, 'cancelSubscription')
1434 && ($propertyBag->has('isNotifyProcessorOnCancelRecur') && $propertyBag->getIsNotifyProcessorOnCancelRecur())) {
1436 if ($this->cancelSubscription($message, $propertyBag)) {
1437 return ['message' => $message];
1439 throw new PaymentProcessorException($message);
1441 return ['message' => ts('Recurring contribution cancelled')];
1447 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1449 * @param array $params
1451 * @throws \Civi\Payment\Exception\PaymentProcessorException
1453 public function doRefund(&$params) {}
1456 * Query payment processor for details about a transaction.
1458 * @param array $params
1459 * Array of parameters containing one of:
1460 * - trxn_id Id of an individual transaction.
1461 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1464 * Extra parameters retrieved.
1465 * Any parameters retrievable through this should be documented in the function comments at
1466 * CRM_Core_Payment::doQuery. Currently:
1467 * - fee_amount Amount of fee paid
1469 public function doQuery($params) {
1474 * This function checks to see if we have the right config values.
1477 * the error message if any
1479 abstract protected function checkConfig();
1482 * Redirect for paypal.
1484 * @todo move to paypal class or remove
1486 * @param $paymentProcessor
1490 public static function paypalRedirect(&$paymentProcessor) {
1491 if (!$paymentProcessor) {
1495 if (isset($_GET['payment_date']) &&
1496 isset($_GET['merchant_return_link']) &&
1497 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1498 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1507 * Handle incoming payment notification.
1509 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1511 * @todo move to0 \Civi\Payment\System factory method
1512 * Page callback for civicrm/payment/ipn
1514 public static function handleIPN() {
1516 self
::handlePaymentMethod(
1517 'PaymentNotification',
1519 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1520 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1521 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1525 catch (CRM_Core_Exception
$e) {
1526 Civi
::log()->error('ipn_payment_callback_exception', [
1528 'backtrace' => $e->getTraceAsString(),
1529 'message' => $e->getMessage(),
1533 CRM_Utils_System
::civiExit();
1537 * Payment callback handler.
1539 * The processor_name or processor_id is passed in.
1540 * Note that processor_id is more reliable as one site may have more than one instance of a
1541 * processor & ideally the processor will be validating the results
1542 * Load requested payment processor and call that processor's handle<$method> method
1544 * @todo move to \Civi\Payment\System factory method
1546 * @param string $method
1547 * 'PaymentNotification' or 'PaymentCron'
1548 * @param array $params
1550 * @throws \CRM_Core_Exception
1551 * @throws \Exception
1553 public static function handlePaymentMethod($method, $params = []) {
1554 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1555 $q = explode('/', CRM_Utils_System
::currentPath());
1556 $lastParam = array_pop($q);
1557 if (is_numeric($lastParam)) {
1558 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1561 self
::logPaymentNotification($params);
1562 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1566 self
::logPaymentNotification($params);
1568 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1569 FROM civicrm_payment_processor_type ppt
1570 INNER JOIN civicrm_payment_processor pp
1571 ON pp.payment_processor_type_id = ppt.id
1574 if (isset($params['processor_id'])) {
1575 $sql .= " WHERE pp.id = %2";
1576 $args[2] = [$params['processor_id'], 'Integer'];
1577 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1580 // This is called when processor_name is passed - passing processor_id instead is recommended.
1581 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1583 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1586 $args[2] = [$params['processor_name'], 'String'];
1587 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1590 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1592 // Check whether we found anything at all.
1594 throw new CRM_Core_Exception($notFound);
1597 $method = 'handle' . $method;
1598 $extension_instance_found = FALSE;
1600 // In all likelihood, we'll just end up with the one instance returned here. But it's
1601 // possible we may get more. Hence, iterate through all instances ..
1603 while ($dao->fetch()) {
1604 // Check pp is extension - is this still required - surely the singleton below handles it.
1605 $ext = CRM_Extension_System
::singleton()->getMapper();
1606 if ($ext->isExtensionKey($dao->class_name
)) {
1607 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1608 require_once $ext->classToPath($paymentClass);
1611 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1613 // Should never be empty - we already established this processor_id exists and is active.
1614 if (empty($processorInstance)) {
1618 // Does PP implement this method, and can we call it?
1619 if (!method_exists($processorInstance, $method) ||
1620 !is_callable([$processorInstance, $method])
1622 // on the off chance there is a double implementation of this processor we should keep looking for another
1623 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1627 // Everything, it seems, is ok - execute pp callback handler
1628 $processorInstance->$method();
1629 $extension_instance_found = TRUE;
1632 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1633 $IPNParams = array_merge($_GET, $_REQUEST);
1634 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1635 if (!$extension_instance_found) {
1636 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1637 "%2 method is unsupported in legacy payment processors.";
1638 throw new CRM_Core_Exception(ts($message, [
1639 1 => $params['processor_name'],
1646 * Check whether a method is present ( & supported ) by the payment processor object.
1648 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1650 * @param string $method
1651 * Method to check for.
1655 public function isSupported($method) {
1656 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1660 * Some processors replace the form submit button with their own.
1662 * Returning false here will leave the button off front end forms.
1664 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1666 public function isSuppressSubmitButtons() {
1671 * Checks to see if invoice_id already exists in db.
1673 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1674 * it is better to standardise to being here.
1676 * @param int $invoiceId The ID to check.
1678 * @param null $contributionID
1679 * If a contribution exists pass in the contribution ID.
1682 * True if invoice ID otherwise exists, else false
1684 protected function checkDupe($invoiceId, $contributionID = NULL) {
1685 $contribution = new CRM_Contribute_DAO_Contribution();
1686 $contribution->invoice_id
= $invoiceId;
1687 if ($contributionID) {
1688 $contribution->whereAdd("id <> $contributionID");
1690 return $contribution->find();
1694 * Get url for users to manage this recurring contribution for this processor.
1696 * @param int $entityID
1697 * @param null $entity
1698 * @param string $action
1700 * @return string|null
1701 * @throws \CRM_Core_Exception
1703 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1707 if (!$this->supports('cancelRecurring')) {
1710 $url = 'civicrm/contribute/unsubscribe';
1714 //in notify mode don't return the update billing url
1715 if (!$this->supports('updateSubscriptionBillingInfo')) {
1718 $url = 'civicrm/contribute/updatebilling';
1722 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1725 $url = 'civicrm/contribute/updaterecur';
1729 $userId = CRM_Core_Session
::singleton()->get('userID');
1731 $checksumValue = '';
1734 // Find related Contact
1738 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1742 case 'contribution':
1743 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1744 $entityArg = 'coid';
1749 SELECT DISTINCT con.contact_id
1750 FROM civicrm_contribution_recur rec
1751 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1753 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1759 $entityArg = 'crid';
1764 // Add entity arguments
1765 if ($entityArg != '') {
1766 // Add checksum argument
1767 if ($contactID != 0 && $userId != $contactID) {
1768 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1770 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1774 if ($this->supports('accountLoginURL')) {
1775 return $this->accountLoginURL();
1779 return $this->_paymentProcessor
['url_recur'] ??
'';
1783 * Get description of payment to pass to processor.
1785 * This is often what people see in the interface so we want to get
1786 * as much unique information in as possible within the field length (& presumably the early part of the field)
1788 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1789 * having field names to clarify
1791 * @param array $params
1792 * @param int $length
1796 protected function getPaymentDescription($params = [], $length = 24) {
1797 $propertyBag = PropertyBag
::cast($params);
1799 $propertyBag->getter('contactID', TRUE),
1800 $propertyBag->getter('contributionID', TRUE),
1801 $propertyBag->getter('description', TRUE) ?
: ($propertyBag->getter('isRecur', TRUE) ?
ts('Recurring payment') : NULL),
1802 $propertyBag->getter('billing_first_name', TRUE),
1803 $propertyBag->getter('billing_last_name', TRUE),
1805 return substr(implode('-', array_filter($parts)), 0, $length);
1809 * Checks if back-office recurring edit is allowed
1813 public function supportsEditRecurringContribution() {
1818 * Does this processor support changing the amount for recurring contributions through code.
1820 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1821 * that will be updated at the payment processor.
1825 protected function supportsChangeSubscriptionAmount() {
1826 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
1830 * Checks if payment processor supports recurring contributions
1834 public function supportsRecurring() {
1835 if (!empty($this->_paymentProcessor
['is_recur'])) {
1842 * Checks if payment processor supports an account login URL
1843 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1844 * TODO: It is implemented by AuthorizeNET, any others?
1848 protected function supportsAccountLoginURL() {
1849 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
1853 * Should a receipt be sent out for a pending payment.
1855 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1857 public function isSendReceiptForPending() {