3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 use Civi\Payment\System
;
29 use Civi\Payment\Exception\PaymentProcessorException
;
32 * Class CRM_Core_Payment.
34 * This class is the main class for the payment processor subsystem.
36 * It is the parent class for payment processors. It also holds some IPN related functions
37 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
39 abstract class CRM_Core_Payment
{
42 * Component - ie. event or contribute.
44 * This is used for setting return urls.
48 protected $_component;
51 * How are we getting billing information.
53 * We are trying to completely deprecate these parameters.
55 * FORM - we collect it on the same page
56 * BUTTON - the processor collects it and sends it back to us via some protocol
59 BILLING_MODE_FORM
= 1,
60 BILLING_MODE_BUTTON
= 2,
61 BILLING_MODE_NOTIFY
= 4;
64 * Which payment type(s) are we using?
69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
72 PAYMENT_TYPE_CREDIT_CARD
= 1,
73 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
76 * Subscription / Recurring payment Status
80 RECURRING_PAYMENT_START
= 'START',
81 RECURRING_PAYMENT_END
= 'END';
86 protected $_paymentProcessor;
89 * Base url of the calling form (offsite processors).
93 protected $baseReturnUrl;
96 * Return url upon success (offsite processors).
100 protected $successUrl;
103 * Return url upon failure (offsite processors).
107 protected $cancelUrl;
110 * Processor type label.
112 * (Deprecated parameter but used in some messages).
118 public $_processorName;
121 * The profile configured to show on the billing form.
123 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
124 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
125 * requirements with the configured requirements.
127 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
130 * Note this change would probably include converting 'billing' to a reserved profile.
134 protected $billingProfile;
137 * Payment instrument ID.
139 * This is normally retrieved from the payment_processor table.
143 protected $paymentInstrumentID;
146 * Is this a back office transaction.
150 protected $backOffice = FALSE;
153 * Contribution that is being paid.
157 protected $contributionID;
160 * Contact ID for payment.
164 protected $contactID;
167 * Recurring contribution that is being paid.
171 protected $contributionRecurID;
174 * Description of purchase.
178 protected $description;
181 * CiviCRM generated Invoice ID.
185 protected $invoiceID;
188 * Is this a recurring contribution.
195 * Payment processor generated string for charging.
197 * A payment token could be a single use token (e.g generated by
198 * a client side script) or a token that permits recurring or on demand charging.
200 * The key thing is it is passed to the processor in lieu of card details to
201 * initiate a payment.
203 * Generally if a processor is going to pass in a payment token generated through
204 * javascript it would add 'payment_token' to the array it returns in it's
205 * implementation of getPaymentFormFields. This will add a hidden 'payment_token' field to
206 * the form. A good example is client side encryption where credit card details are replaced by
207 * an encrypted token using a gateway provided javascript script. In this case the javascript will
208 * remove the credit card details from the form before submitting and populate the payment_token field.
210 * A more complex example is used by paypal checkout where the payment token is generated
211 * via a pre-approval process. In that case the doPreApproval function is called on the processor
212 * class to get information to then interact with paypal via js, finally getting a payment token.
213 * (at this stage the pre-approve api is not in core but that is likely to change - we just need
214 * to think about the permissions since we don't want to expose to anonymous user without thinking
215 * through any risk of credit-card testing using it.
217 * If the token is not totally transient it would be saved to civicrm_payment_token.token.
221 protected $paymentToken;
224 * Three digit currency code.
231 * Payment processor generated string for the transaction ID.
233 * Note some gateways generate a reference for the order and one for the
234 * payment. This is for the payment reference and is saved to
235 * civicrm_financial_trxn.trxn_id.
239 protected $transactionID;
242 * Amount of money charged in fees by the payment processor.
244 * This is notified by (some) payment processers.
248 protected $feeAmount;
251 * Additional information returned by the payment processor regarding the payment outcome.
253 * This would normally be saved in civicrm_financial_trxn.trxn_result_code.
257 protected $trxnResultCode;
260 * Combined with recurFrequencyUnit this gives how often billing will take place.
262 * e.g every if this is 1 and recurFrequencyUnit is 'month' then it is every 1 month.
266 protected $recurFrequencyInterval;
269 * Combined with recurFrequencyInterval this gives how often billing will take place.
271 * e.g every if this is 'month' and recurFrequencyInterval is 1 then it is every 1 month.
276 protected $recurFrequencyUnit;
279 * Passed in parameters.
281 * Using individual getters & setters is preferred but these will be used if
282 * they are not available.
286 protected $inputParams = [];
291 public function getContactID(): int {
292 return $this->contactID ??
$this->inputParams
['contactID'];
296 * @param int $contactID
298 public function setContactID(int $contactID) {
299 $this->contactID
= $contactID;
303 * Getter for contributionRecurID.
305 * Ideally this would always be set by the calling function using the setting
306 * but we need to fall back to the historical passing on inputParams as a transition.
308 * In time we can add a notice if it's set in input params & not via a setter.
312 public function getContributionRecurID(): int {
313 return $this->contributionRecurID ??
$this->inputParams
['contributionRecurID'];
317 * @param int $contributionRecurID
319 public function setContributionRecurID(int $contributionRecurID) {
320 $this->contributionRecurID
= $contributionRecurID;
324 * Getter for Payment Token.
328 public function getPaymentToken(): string {
329 return $this->paymentToken ??
$this->inputParams
['token'];
333 * Setter for Payment Token.
335 * @param string $paymentToken
337 public function setPaymentToken(string $paymentToken) {
338 $this->paymentToken
= $paymentToken;
342 * Get gateway generated transaction ID.
346 public function getTransactionID(): string {
347 return $this->transactionID
;
351 * Set gateway generated transaction ID for the payment.
353 * Note some gateways generate a reference for the order and one for the
354 * payment. This is for the payment reference and is saved to
355 * civicrm_financial_trxn.trxn_id.
357 * @param string $transactionID
359 public function setTransactionID(string $transactionID) {
360 $this->transactionID
= $transactionID;
364 * Get additional result information received from gateway.
366 * This is saved to civicrm_financial_trxn.trxn_result_code.
370 public function getTrxnResultCode(): string {
371 return $this->trxnResultCode
;
375 * Set additional result information from gateway.
377 * This is saved to civicrm_financial_trxn.trxn_result_code.
379 * @param string $resultCode
381 public function setTrxnResultCode(string $resultCode) {
382 $this->trxnResultCode
= $resultCode;
386 * Get recurring frequency interval.
390 public function getRecurFrequencyInterval(): int {
391 return $this->recurFrequencyInterval ??
$this->inputParams
['frequency_interval'];
395 * Set recurring frequency interval.
397 * @param int $recurFrequencyInterval
399 public function setRecurFrequencyInterval(int $recurFrequencyInterval) {
400 $this->recurFrequencyInterval
= $recurFrequencyInterval;
404 * Get recurring frequency unit.
408 public function getRecurFrequencyUnit(): string {
409 return $this->recurFrequencyUnit
;
413 * Set recurring frequency unit.
415 * @param string $recurFrequencyUnit
417 public function setRecurFrequencyUnit(string $recurFrequencyUnit) {
418 $this->recurFrequencyUnit
= $recurFrequencyUnit ??
$this->inputParams
['frequency_unit'];
422 * Get invoice ID (CiviCRM generated invoice reference).
426 public function getInvoiceID(): string {
427 return $this->invoiceID ??
$this->inputParams
['invoiceID'];
431 * Set invoice ID (CiviCRM generated invoice reference).
433 * @param string $invoiceID
435 public function setInvoiceID(string $invoiceID) {
436 $this->invoiceID
= $invoiceID;
440 * Get whether the payment is recurring.
444 public function isRecur(): bool {
445 return $this->isRecur
;
449 * Set whether the payment is recurring.
451 * @param bool $isRecur
453 public function setIsRecur(bool $isRecur) {
454 $this->isRecur
= $isRecur ??
$this->inputParams
['is_recur'];
458 * Get the description.
460 * This generates a description string from params if one has been passed in but
461 * ideally calling functions would use the setDescription function.
465 public function getDescription(): string {
466 if ($this->description
) {
467 return $this->description
;
469 if (isset($this->inputParams
['description'])) {
470 $uninformativeStrings = [
471 ts('Online Event Registration: '),
472 ts('Online Contribution: '),
474 $this->description
= str_replace($uninformativeStrings, '', $this->inputParams
['description']);
476 return $this->description
;
482 * Generally this should be called when instantiating the processor to override
483 * getPaymentDescription, if desired.
485 * @param string $description
487 public function setDescription(string $description) {
488 $this->description
= $description;
492 * Get fee amount returned by processor.
496 public function getFeeAmount(): float {
497 return $this->feeAmount
;
501 * Set fee amount returned by processor.
503 * @param float $feeAmount
505 public function setFeeAmount(float $feeAmount) {
506 $this->feeAmount
= $feeAmount;
510 * Get the contribution ID.
512 * We prefer the one set by the setter but traditional forms just pass in 'contributionID'.
516 public function getContributionID(): int {
517 return $this->contributionID ??
$this->inputParams
['contributionID'];
521 * @param int $contributionID
523 public function setContributionID(int $contributionID) {
524 $this->contributionID
= $contributionID;
530 public function isBackOffice() {
531 return $this->backOffice
;
535 * Set back office property.
537 * @param bool $isBackOffice
539 public function setBackOffice($isBackOffice) {
540 $this->backOffice
= $isBackOffice;
544 * Get payment instrument id.
548 public function getPaymentInstrumentID() {
549 return $this->paymentInstrumentID ?
$this->paymentInstrumentID
: $this->_paymentProcessor
['payment_instrument_id'];
557 public function getID() {
558 return (int) $this->_paymentProcessor
['id'];
562 * Set payment Instrument id.
564 * By default we actually ignore the form value. The manual processor takes it more seriously.
566 * @param int $paymentInstrumentID
568 public function setPaymentInstrumentID($paymentInstrumentID) {
569 $this->paymentInstrumentID
= $this->_paymentProcessor
['payment_instrument_id'];
573 * Set base return path (offsite processors).
575 * This is only useful with an internal civicrm form.
578 * Internal civicrm path.
580 public function setBaseReturnUrl($url) {
581 $this->baseReturnUrl
= $url;
585 * Set success return URL (offsite processors).
587 * This overrides $baseReturnUrl
590 * Full url of site to return browser to upon success.
592 public function setSuccessUrl($url) {
593 $this->successUrl
= $url;
597 * Set cancel return URL (offsite processors).
599 * This overrides $baseReturnUrl
602 * Full url of site to return browser to upon failure.
604 public function setCancelUrl($url) {
605 $this->cancelUrl
= $url;
609 * Set the configured payment profile.
611 * @param int|string $value
613 public function setBillingProfile($value) {
614 $this->billingProfile
= $value;
618 * Opportunity for the payment processor to override the entire form build.
620 * @param CRM_Core_Form $form
623 * Should form building stop at this point?
625 public function buildForm(&$form) {
630 * Log payment notification message to forensic system log.
632 * @todo move to factory class \Civi\Payment\System (or similar)
634 * @param array $params
636 public static function logPaymentNotification($params) {
637 $message = 'payment_notification ';
638 if (!empty($params['processor_name'])) {
639 $message .= 'processor_name=' . $params['processor_name'];
641 if (!empty($params['processor_id'])) {
642 $message .= 'processor_id=' . $params['processor_id'];
645 $log = new CRM_Utils_SystemLogger();
646 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
647 $rawRequestData = file_get_contents("php://input");
648 if (CRM_Utils_JSON
::isValidJSON($rawRequestData)) {
649 $log->alert($message, json_decode($rawRequestData, TRUE));
652 $log->alert($message, $_REQUEST);
657 * Check if capability is supported.
659 * Capabilities have a one to one relationship with capability-related functions on this class.
661 * Payment processor classes should over-ride the capability-specific function rather than this one.
663 * @param string $capability
664 * E.g BackOffice, LiveMode, FutureRecurStartDate.
668 public function supports($capability) {
669 $function = 'supports' . ucfirst($capability);
670 if (method_exists($this, $function)) {
671 return $this->$function();
677 * Are back office payments supported.
679 * e.g paypal standard won't permit you to enter a credit card associated
680 * with someone else's login.
681 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
682 * reach a 'stable' point we disable.
686 protected function supportsBackOffice() {
687 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
696 * Can more than one transaction be processed at once?
698 * In general processors that process payment by server to server communication support this while others do not.
700 * In future we are likely to hit an issue where this depends on whether a token already exists.
704 protected function supportsMultipleConcurrentPayments() {
705 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
714 * Are live payments supported - e.g dummy doesn't support this.
718 protected function supportsLiveMode() {
723 * Are test payments supported.
727 protected function supportsTestMode() {
732 * Does this payment processor support refund?
736 public function supportsRefund() {
741 * Should the first payment date be configurable when setting up back office recurring payments.
743 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
747 protected function supportsFutureRecurStartDate() {
752 * Does this processor support cancelling recurring contributions through code.
754 * If the processor returns true it must be possible to take action from within CiviCRM
755 * that will result in no further payments being processed. In the case of token processors (e.g
756 * IATS, eWay) updating the contribution_recur table is probably sufficient.
760 protected function supportsCancelRecurring() {
761 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
765 * Does this processor support pre-approval.
767 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
769 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
770 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
771 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
775 protected function supportsPreApproval() {
780 * Does this processor support updating billing info for recurring contributions through code.
782 * If the processor returns true then it must be possible to update billing info from within CiviCRM
783 * that will be updated at the payment processor.
787 protected function supportsUpdateSubscriptionBillingInfo() {
788 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
792 * Can recurring contributions be set against pledges.
794 * In practice all processors that use the baseIPN function to finish transactions or
795 * call the completetransaction api support this by looking up previous contributions in the
796 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
797 * adding the new payment to the pledge.
799 * However, only enabling for processors it has been tested against.
803 protected function supportsRecurContributionsForPledges() {
808 * Function to action pre-approval if supported
810 * @param array $params
811 * Parameters from the form
813 * This function returns an array which should contain
814 * - pre_approval_parameters (this will be stored on the calling form & available later)
815 * - redirect_url (if set the browser will be redirected to this.
817 public function doPreApproval(&$params) {
821 * Get any details that may be available to the payment processor due to an approval process having happened.
823 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
826 * @param array $storedDetails
830 public function getPreApprovalDetails($storedDetails) {
835 * Default payment instrument validation.
837 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
838 * Not a static function, because I need to check for payment_type.
840 * @param array $values
841 * @param array $errors
843 public function validatePaymentInstrument($values, &$errors) {
844 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
845 if ($this->_paymentProcessor
['payment_type'] == 1) {
846 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
851 * Getter for the payment processor.
853 * The payment processor array is based on the civicrm_payment_processor table entry.
856 * Payment processor array.
858 public function getPaymentProcessor() {
859 return $this->_paymentProcessor
;
863 * Setter for the payment processor.
865 * @param array $processor
867 public function setPaymentProcessor($processor) {
868 $this->_paymentProcessor
= $processor;
872 * Setter for the payment form that wants to use the processor.
876 * @param CRM_Core_Form $paymentForm
878 public function setForm(&$paymentForm) {
879 $this->_paymentForm
= $paymentForm;
883 * Getter for payment form that is using the processor.
885 * @return CRM_Core_Form
888 public function getForm() {
889 return $this->_paymentForm
;
893 * Get help text information (help, description, etc.) about this payment,
894 * to display to the user.
896 * @param string $context
897 * Context of the text.
898 * Only explicitly supported contexts are handled without error.
899 * Currently supported:
900 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
902 * @param array $params
903 * Parameters for the field, context specific.
907 public function getText($context, $params) {
908 // I have deliberately added a noisy fail here.
909 // The function is intended to be extendable, but not by changes
910 // not documented clearly above.
912 case 'contributionPageRecurringHelp':
913 // require exactly two parameters
914 if (array_keys($params) == [
915 'is_recur_installments',
918 $gotText = ts('Your recurring contribution will be processed automatically.');
919 if ($params['is_recur_installments']) {
920 $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.');
922 if ($params['is_email_receipt']) {
923 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
928 case 'contributionPageContinueText':
929 if ($params['amount'] <= 0) {
930 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
932 if ($this->_paymentProcessor
['billing_mode'] == 4) {
933 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']]);
935 if ($params['is_payment_to_existing']) {
936 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
938 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
941 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
946 * Getter for accessing member vars.
948 * @todo believe this is unused
950 * @param string $name
954 public function getVar($name) {
955 return isset($this->$name) ?
$this->$name : NULL;
959 * Get name for the payment information type.
960 * @todo - use option group + name field (like Omnipay does)
963 public function getPaymentTypeName() {
964 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
968 * Get label for the payment information type.
969 * @todo - use option group + labels (like Omnipay does)
972 public function getPaymentTypeLabel() {
973 return $this->_paymentProcessor
['payment_type'] == 1 ?
ts('Credit Card') : ts('Direct Debit');
977 * Get array of fields that should be displayed on the payment form.
980 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
982 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
987 * Array of payment fields appropriate to the payment processor.
989 * @throws CiviCRM_API3_Exception
991 public function getPaymentFormFields() {
992 if ($this->_paymentProcessor
['billing_mode'] == 4) {
995 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
999 * Get an array of the fields that can be edited on the recurring contribution.
1001 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
1002 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
1003 * can be updated from the contribution recur edit screen.
1005 * The fields are likely to be a subset of these
1008 * - 'frequency_interval',
1009 * - 'frequency_unit',
1011 * - 'next_sched_contribution_date',
1013 * - 'failure_retry_day',
1015 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
1016 * metadata is not defined in the xml for the field it will cause an error.
1018 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
1019 * form (UpdateSubscription).
1023 public function getEditableRecurringScheduleFields() {
1024 if ($this->supports('changeSubscriptionAmount')) {
1031 * Get the help text to present on the recurring update page.
1033 * This should reflect what can or cannot be edited.
1037 public function getRecurringScheduleUpdateHelpText() {
1038 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
1039 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.');
1041 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.');
1045 * Get the metadata for all required fields.
1049 protected function getMandatoryFields() {
1050 $mandatoryFields = [];
1051 foreach ($this->getAllFields() as $field_name => $field_spec) {
1052 if (!empty($field_spec['is_required'])) {
1053 $mandatoryFields[$field_name] = $field_spec;
1056 return $mandatoryFields;
1060 * Get the metadata of all the fields configured for this processor.
1064 * @throws \CiviCRM_API3_Exception
1066 protected function getAllFields() {
1067 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
1068 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
1069 return array_merge($paymentFields, $billingFields);
1073 * Get array of fields that should be displayed on the payment form for credit cards.
1077 protected function getCreditCardFormFields() {
1080 'credit_card_number',
1082 'credit_card_exp_date',
1087 * Get array of fields that should be displayed on the payment form for direct debits.
1091 protected function getDirectDebitFormFields() {
1094 'bank_account_number',
1095 'bank_identification_number',
1101 * Return an array of all the details about the fields potentially required for payment fields.
1103 * Only those determined by getPaymentFormFields will actually be assigned to the form
1108 * @throws \Exception
1110 public function getPaymentFormFieldsMetadata() {
1111 //@todo convert credit card type into an option value
1112 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
1113 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
1114 if (!$this->isBackOffice()) {
1115 $isCVVRequired = TRUE;
1118 'credit_card_number' => [
1119 'htmlType' => 'text',
1120 'name' => 'credit_card_number',
1121 'title' => ts('Card Number'),
1125 'autocomplete' => 'off',
1126 'class' => 'creditcard',
1128 'is_required' => TRUE,
1129 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
1132 'htmlType' => 'text',
1134 'title' => ts('Security Code'),
1138 'autocomplete' => 'off',
1140 'is_required' => $isCVVRequired,
1143 '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.'),
1144 'rule_name' => 'integer',
1145 'rule_parameters' => NULL,
1149 'credit_card_exp_date' => [
1150 'htmlType' => 'date',
1151 'name' => 'credit_card_exp_date',
1152 'title' => ts('Expiration Date'),
1153 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
1154 'is_required' => TRUE,
1157 'rule_message' => ts('Card expiration date cannot be a past date.'),
1158 'rule_name' => 'currentDate',
1159 'rule_parameters' => TRUE,
1162 'extra' => ['class' => 'crm-form-select'],
1164 'credit_card_type' => [
1165 'htmlType' => 'select',
1166 'name' => 'credit_card_type',
1167 'title' => ts('Card Type'),
1168 'attributes' => $creditCardType,
1169 'is_required' => FALSE,
1171 'account_holder' => [
1172 'htmlType' => 'text',
1173 'name' => 'account_holder',
1174 'title' => ts('Account Holder'),
1178 'autocomplete' => 'on',
1180 'is_required' => TRUE,
1182 //e.g. IBAN can have maxlength of 34 digits
1183 'bank_account_number' => [
1184 'htmlType' => 'text',
1185 'name' => 'bank_account_number',
1186 'title' => ts('Bank Account Number'),
1190 'autocomplete' => 'off',
1194 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
1195 'rule_name' => 'nopunctuation',
1196 'rule_parameters' => NULL,
1199 'is_required' => TRUE,
1201 //e.g. SWIFT-BIC can have maxlength of 11 digits
1202 'bank_identification_number' => [
1203 'htmlType' => 'text',
1204 'name' => 'bank_identification_number',
1205 'title' => ts('Bank Identification Number'),
1209 'autocomplete' => 'off',
1211 'is_required' => TRUE,
1214 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
1215 'rule_name' => 'nopunctuation',
1216 'rule_parameters' => NULL,
1221 'htmlType' => 'text',
1222 'name' => 'bank_name',
1223 'title' => ts('Bank Name'),
1227 'autocomplete' => 'off',
1229 'is_required' => TRUE,
1233 'htmlType' => 'text',
1234 'name' => 'check_number',
1235 'title' => ts('Check Number'),
1236 'is_required' => FALSE,
1237 'attributes' => NULL,
1239 'pan_truncation' => [
1240 'htmlType' => 'text',
1241 'name' => 'pan_truncation',
1242 'title' => ts('Last 4 digits of the card'),
1243 'is_required' => FALSE,
1248 'autocomplete' => 'off',
1252 'rule_message' => ts('Please enter valid last 4 digit card number.'),
1253 'rule_name' => 'numeric',
1254 'rule_parameters' => NULL,
1258 'payment_token' => [
1259 'htmlType' => 'hidden',
1260 'name' => 'payment_token',
1261 'title' => ts('Authorization token'),
1262 'is_required' => FALSE,
1265 'autocomplete' => 'off',
1266 'id' => 'payment_token',
1273 * Get billing fields required for this processor.
1275 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
1278 * @param int $billingLocationID
1282 public function getBillingAddressFields($billingLocationID = NULL) {
1283 if (!$billingLocationID) {
1284 // Note that although the billing id is passed around the forms the idea that it would be anything other than
1285 // the result of the function below doesn't seem to have eventuated.
1286 // So taking this as a param is possibly something to be removed in favour of the standard default.
1287 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
1289 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
1293 'first_name' => 'billing_first_name',
1294 'middle_name' => 'billing_middle_name',
1295 'last_name' => 'billing_last_name',
1296 'street_address' => "billing_street_address-{$billingLocationID}",
1297 'city' => "billing_city-{$billingLocationID}",
1298 'country' => "billing_country_id-{$billingLocationID}",
1299 'state_province' => "billing_state_province_id-{$billingLocationID}",
1300 'postal_code' => "billing_postal_code-{$billingLocationID}",
1305 * Get form metadata for billing address fields.
1307 * @param int $billingLocationID
1310 * Array of metadata for address fields.
1312 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
1313 if (!$billingLocationID) {
1314 // Note that although the billing id is passed around the forms the idea that it would be anything other than
1315 // the result of the function below doesn't seem to have eventuated.
1316 // So taking this as a param is possibly something to be removed in favour of the standard default.
1317 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
1320 $metadata['billing_first_name'] = [
1321 'htmlType' => 'text',
1322 'name' => 'billing_first_name',
1323 'title' => ts('Billing First Name'),
1328 'autocomplete' => 'off',
1330 'is_required' => TRUE,
1333 $metadata['billing_middle_name'] = [
1334 'htmlType' => 'text',
1335 'name' => 'billing_middle_name',
1336 'title' => ts('Billing Middle Name'),
1341 'autocomplete' => 'off',
1343 'is_required' => FALSE,
1346 $metadata['billing_last_name'] = [
1347 'htmlType' => 'text',
1348 'name' => 'billing_last_name',
1349 'title' => ts('Billing Last Name'),
1354 'autocomplete' => 'off',
1356 'is_required' => TRUE,
1359 $metadata["billing_street_address-{$billingLocationID}"] = [
1360 'htmlType' => 'text',
1361 'name' => "billing_street_address-{$billingLocationID}",
1362 'title' => ts('Street Address'),
1367 'autocomplete' => 'off',
1369 'is_required' => TRUE,
1372 $metadata["billing_city-{$billingLocationID}"] = [
1373 'htmlType' => 'text',
1374 'name' => "billing_city-{$billingLocationID}",
1375 'title' => ts('City'),
1380 'autocomplete' => 'off',
1382 'is_required' => TRUE,
1385 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1386 'htmlType' => 'chainSelect',
1387 'title' => ts('State/Province'),
1388 'name' => "billing_state_province_id-{$billingLocationID}",
1390 'is_required' => TRUE,
1393 $metadata["billing_postal_code-{$billingLocationID}"] = [
1394 'htmlType' => 'text',
1395 'name' => "billing_postal_code-{$billingLocationID}",
1396 'title' => ts('Postal Code'),
1401 'autocomplete' => 'off',
1403 'is_required' => TRUE,
1406 $metadata["billing_country_id-{$billingLocationID}"] = [
1407 'htmlType' => 'select',
1408 'name' => "billing_country_id-{$billingLocationID}",
1409 'title' => ts('Country'),
1412 '' => ts('- select -'),
1413 ] + CRM_Core_PseudoConstant
::country(),
1414 'is_required' => TRUE,
1420 * Get base url dependent on component.
1422 * (or preferably set it using the setter function).
1426 protected function getBaseReturnUrl() {
1427 if ($this->baseReturnUrl
) {
1428 return $this->baseReturnUrl
;
1430 if ($this->_component
== 'event') {
1431 $baseURL = 'civicrm/event/register';
1434 $baseURL = 'civicrm/contribute/transact';
1440 * Get the currency for the transaction.
1442 * Handle any inconsistency about how it is passed in here.
1448 protected function getCurrency($params = []) {
1449 $params = array_merge($params, (array) $this->inputParams
);
1450 return $this->currency ?? CRM_Utils_Array
::value('currencyID', $params, CRM_Utils_Array
::value('currency', $params));
1454 * Get the currency for the transaction.
1456 * Handle any inconsistency about how it is passed in here.
1458 * @param array $params
1461 * @throws \CRM_Core_Exception
1463 protected function getAmount($params = []) {
1464 $amount = $this->amount ??
$params['amount'];
1465 return CRM_Utils_Money
::format($amount, NULL, NULL, TRUE);
1469 * Get url to return to after cancelled or failed transaction.
1471 * @param string $qfKey
1472 * @param int $participantID
1474 * @return string cancel url
1476 public function getCancelUrl($qfKey, $participantID) {
1477 if (isset($this->cancelUrl
)) {
1478 return $this->cancelUrl
;
1481 if ($this->_component
== 'event') {
1482 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1485 'participantId' => $participantID,
1491 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1492 '_qf_Main_display' => 1,
1501 * Get URL to return the browser to on success.
1507 protected function getReturnSuccessUrl($qfKey) {
1508 if (isset($this->successUrl
)) {
1509 return $this->successUrl
;
1512 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1513 '_qf_ThankYou_display' => 1,
1521 * Get URL to return the browser to on failure.
1523 * @param string $key
1524 * @param int $participantID
1525 * @param int $eventID
1528 * URL for a failing transactor to be redirected to.
1530 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1531 if (isset($this->cancelUrl
)) {
1532 return $this->cancelUrl
;
1535 $test = $this->_is_test ?
'&action=preview' : '';
1536 if ($this->_component
== "event") {
1537 return CRM_Utils_System
::url('civicrm/event/register',
1538 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1543 return CRM_Utils_System
::url('civicrm/contribute/transact',
1544 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1551 * Get URl for when the back button is pressed.
1555 * @return string url
1557 protected function getGoBackUrl($qfKey) {
1558 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1559 '_qf_Confirm_display' => 'true',
1567 * Get the notify (aka ipn, web hook or silent post) url.
1569 * If there is no '.' in it we assume that we are dealing with localhost or
1570 * similar and it is unreachable from the web & hence invalid.
1573 * URL to notify outcome of transaction.
1575 protected function getNotifyUrl() {
1576 $url = CRM_Utils_System
::url(
1577 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1584 return (stristr($url, '.')) ?
$url : '';
1588 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1590 * Does a server to server payment transaction.
1592 * @param array $params
1593 * Assoc array of input parameters for this transaction.
1596 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1598 protected function doDirectPayment(&$params) {
1603 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1604 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1606 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1607 * the transaction & in fact doTransferCheckout would not traditionally come back.
1608 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1610 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1611 * In some cases the IPN will set the payment to "Completed" some time later.
1613 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1614 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1615 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1617 * @param array $params
1619 * @param string $component
1622 * Result array (containing at least the key payment_status_id)
1624 * @throws \Civi\Payment\Exception\PaymentProcessorException
1626 public function doPayment(&$params, $component = 'contribute') {
1627 $this->inputParams
= $params;
1628 $this->_component
= $component;
1629 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1631 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1632 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1633 // have an example of that at the mome.
1634 if ($params['amount'] == 0) {
1635 $result['payment_status_id'] = array_search('Completed', $statuses);
1639 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1640 $result = $this->doTransferCheckout($params, $component);
1641 if (is_array($result) && !isset($result['payment_status_id'])) {
1642 $result['payment_status_id'] = array_search('Pending', $statuses);
1646 $result = $this->doDirectPayment($params, $component);
1647 if (is_array($result) && !isset($result['payment_status_id'])) {
1648 if (!empty($params['is_recur'])) {
1649 // See comment block.
1650 $result['payment_status_id'] = array_search('Pending', $statuses);
1653 $result['payment_status_id'] = array_search('Completed', $statuses);
1657 if (is_a($result, 'CRM_Core_Error')) {
1658 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1666 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1668 * @param array $params
1670 * @throws \Civi\Payment\Exception\PaymentProcessorException
1672 public function doRefund(&$params) {}
1675 * Query payment processor for details about a transaction.
1677 * @param array $params
1678 * Array of parameters containing one of:
1679 * - trxn_id Id of an individual transaction.
1680 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1683 * Extra parameters retrieved.
1684 * Any parameters retrievable through this should be documented in the function comments at
1685 * CRM_Core_Payment::doQuery. Currently:
1686 * - fee_amount Amount of fee paid
1688 public function doQuery($params) {
1693 * This function checks to see if we have the right config values.
1696 * the error message if any
1698 abstract protected function checkConfig();
1701 * Redirect for paypal.
1703 * @todo move to paypal class or remove
1705 * @param $paymentProcessor
1709 public static function paypalRedirect(&$paymentProcessor) {
1710 if (!$paymentProcessor) {
1714 if (isset($_GET['payment_date']) &&
1715 isset($_GET['merchant_return_link']) &&
1716 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1717 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1726 * Handle incoming payment notification.
1728 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1730 * @todo move to0 \Civi\Payment\System factory method
1731 * Page callback for civicrm/payment/ipn
1733 public static function handleIPN() {
1735 self
::handlePaymentMethod(
1736 'PaymentNotification',
1738 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1739 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1740 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1744 catch (CRM_Core_Exception
$e) {
1745 Civi
::log()->error('ipn_payment_callback_exception', [
1747 'backtrace' => CRM_Core_Error
::formatBacktrace(debug_backtrace()),
1751 CRM_Utils_System
::civiExit();
1755 * Payment callback handler.
1757 * The processor_name or processor_id is passed in.
1758 * Note that processor_id is more reliable as one site may have more than one instance of a
1759 * processor & ideally the processor will be validating the results
1760 * Load requested payment processor and call that processor's handle<$method> method
1762 * @todo move to \Civi\Payment\System factory method
1764 * @param string $method
1765 * 'PaymentNotification' or 'PaymentCron'
1766 * @param array $params
1768 * @throws \CRM_Core_Exception
1769 * @throws \Exception
1771 public static function handlePaymentMethod($method, $params = []) {
1772 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1773 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1774 $lastParam = array_pop($q);
1775 if (is_numeric($lastParam)) {
1776 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1779 self
::logPaymentNotification($params);
1780 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1784 self
::logPaymentNotification($params);
1786 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1787 FROM civicrm_payment_processor_type ppt
1788 INNER JOIN civicrm_payment_processor pp
1789 ON pp.payment_processor_type_id = ppt.id
1792 if (isset($params['processor_id'])) {
1793 $sql .= " WHERE pp.id = %2";
1794 $args[2] = [$params['processor_id'], 'Integer'];
1795 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1798 // This is called when processor_name is passed - passing processor_id instead is recommended.
1799 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1801 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1804 $args[2] = [$params['processor_name'], 'String'];
1805 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1808 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1810 // Check whether we found anything at all.
1812 throw new CRM_Core_Exception($notFound);
1815 $method = 'handle' . $method;
1816 $extension_instance_found = FALSE;
1818 // In all likelihood, we'll just end up with the one instance returned here. But it's
1819 // possible we may get more. Hence, iterate through all instances ..
1821 while ($dao->fetch()) {
1822 // Check pp is extension - is this still required - surely the singleton below handles it.
1823 $ext = CRM_Extension_System
::singleton()->getMapper();
1824 if ($ext->isExtensionKey($dao->class_name
)) {
1825 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1826 require_once $ext->classToPath($paymentClass);
1829 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1831 // Should never be empty - we already established this processor_id exists and is active.
1832 if (empty($processorInstance)) {
1836 // Does PP implement this method, and can we call it?
1837 if (!method_exists($processorInstance, $method) ||
1838 !is_callable([$processorInstance, $method])
1840 // on the off chance there is a double implementation of this processor we should keep looking for another
1841 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1845 // Everything, it seems, is ok - execute pp callback handler
1846 $processorInstance->$method();
1847 $extension_instance_found = TRUE;
1850 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1851 $IPNParams = array_merge($_GET, $_REQUEST);
1852 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1853 if (!$extension_instance_found) {
1854 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1855 "%2 method is unsupported in legacy payment processors.";
1856 throw new CRM_Core_Exception(ts($message, [
1857 1 => $params['processor_name'],
1864 * Check whether a method is present ( & supported ) by the payment processor object.
1866 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1868 * @param string $method
1869 * Method to check for.
1873 public function isSupported($method) {
1874 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1878 * Some processors replace the form submit button with their own.
1880 * Returning false here will leave the button off front end forms.
1882 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1884 public function isSuppressSubmitButtons() {
1889 * Checks to see if invoice_id already exists in db.
1891 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1892 * it is better to standardise to being here.
1894 * @param int $invoiceId The ID to check.
1896 * @param null $contributionID
1897 * If a contribution exists pass in the contribution ID.
1900 * True if invoice ID otherwise exists, else false
1902 protected function checkDupe($invoiceId, $contributionID = NULL) {
1903 $contribution = new CRM_Contribute_DAO_Contribution();
1904 $contribution->invoice_id
= $invoiceId;
1905 if ($contributionID) {
1906 $contribution->whereAdd("id <> $contributionID");
1908 return $contribution->find();
1912 * Get url for users to manage this recurring contribution for this processor.
1914 * @param int $entityID
1915 * @param null $entity
1916 * @param string $action
1920 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1924 if (!$this->supports('cancelRecurring')) {
1927 $url = 'civicrm/contribute/unsubscribe';
1931 //in notify mode don't return the update billing url
1932 if (!$this->supports('updateSubscriptionBillingInfo')) {
1935 $url = 'civicrm/contribute/updatebilling';
1939 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1942 $url = 'civicrm/contribute/updaterecur';
1946 $userId = CRM_Core_Session
::singleton()->get('userID');
1948 $checksumValue = '';
1951 // Find related Contact
1955 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1959 case 'contribution':
1960 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1961 $entityArg = 'coid';
1966 SELECT DISTINCT con.contact_id
1967 FROM civicrm_contribution_recur rec
1968 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1970 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1976 $entityArg = 'crid';
1981 // Add entity arguments
1982 if ($entityArg != '') {
1983 // Add checksum argument
1984 if ($contactID != 0 && $userId != $contactID) {
1985 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1987 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1991 if ($this->supports('accountLoginURL')) {
1992 return $this->accountLoginURL();
1996 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
2000 * Get description of payment to pass to processor.
2002 * This is often what people see in the interface so we want to get
2003 * as much unique information in as possible within the field length (& presumably the early part of the field)
2005 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
2006 * having field names to clarify
2008 * @param array $params
2009 * @param int $length
2013 protected function getPaymentDescription($params = [], $length = 24) {
2018 'billing_first_name',
2019 'billing_last_name',
2022 $params['description'] = $this->getDescription();
2023 foreach ($parts as $part) {
2024 if ((!empty($params[$part]))) {
2025 $validParts[] = $params[$part];
2028 return substr(implode('-', $validParts), 0, $length);
2032 * Checks if backoffice recurring edit is allowed
2036 public function supportsEditRecurringContribution() {
2041 * Does this processor support changing the amount for recurring contributions through code.
2043 * If the processor returns true then it must be possible to update the amount from within CiviCRM
2044 * that will be updated at the payment processor.
2048 protected function supportsChangeSubscriptionAmount() {
2049 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
2053 * Checks if payment processor supports recurring contributions
2057 public function supportsRecurring() {
2058 if (!empty($this->_paymentProcessor
['is_recur'])) {
2065 * Checks if payment processor supports an account login URL
2066 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
2067 * TODO: It is implemented by AuthorizeNET, any others?
2071 protected function supportsAccountLoginURL() {
2072 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
2076 * Should a receipt be sent out for a pending payment.
2078 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
2080 public function isSendReceiptForPending() {