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;
155 public function isBackOffice() {
156 return $this->backOffice
;
160 * Set back office property.
162 * @param bool $isBackOffice
164 public function setBackOffice($isBackOffice) {
165 $this->backOffice
= $isBackOffice;
169 * Get payment instrument id.
173 public function getPaymentInstrumentID() {
174 return $this->paymentInstrumentID ?
$this->paymentInstrumentID
: $this->_paymentProcessor
['payment_instrument_id'];
178 * Set payment Instrument id.
180 * By default we actually ignore the form value. The manual processor takes it more seriously.
182 * @param int $paymentInstrumentID
184 public function setPaymentInstrumentID($paymentInstrumentID) {
185 $this->paymentInstrumentID
= $this->_paymentProcessor
['payment_instrument_id'];
189 * Set base return path (offsite processors).
191 * This is only useful with an internal civicrm form.
194 * Internal civicrm path.
196 public function setBaseReturnUrl($url) {
197 $this->baseReturnUrl
= $url;
201 * Set success return URL (offsite processors).
203 * This overrides $baseReturnUrl
206 * Full url of site to return browser to upon success.
208 public function setSuccessUrl($url) {
209 $this->successUrl
= $url;
213 * Set cancel return URL (offsite processors).
215 * This overrides $baseReturnUrl
218 * Full url of site to return browser to upon failure.
220 public function setCancelUrl($url) {
221 $this->cancelUrl
= $url;
225 * Set the configured payment profile.
227 * @param int|string $value
229 public function setBillingProfile($value) {
230 $this->billingProfile
= $value;
234 * Opportunity for the payment processor to override the entire form build.
236 * @param CRM_Core_Form $form
239 * Should form building stop at this point?
241 public function buildForm(&$form) {
246 * Log payment notification message to forensic system log.
248 * @todo move to factory class \Civi\Payment\System (or similar)
250 * @param array $params
254 public static function logPaymentNotification($params) {
255 $message = 'payment_notification ';
256 if (!empty($params['processor_name'])) {
257 $message .= 'processor_name=' . $params['processor_name'];
259 if (!empty($params['processor_id'])) {
260 $message .= 'processor_id=' . $params['processor_id'];
263 $log = new CRM_Utils_SystemLogger();
264 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
265 $rawRequestData = file_get_contents("php://input");
266 if (CRM_Utils_JSON
::isValidJSON($rawRequestData)) {
267 $log->alert($message, json_decode($rawRequestData, TRUE));
270 $log->alert($message, $_REQUEST);
275 * Check if capability is supported.
277 * Capabilities have a one to one relationship with capability-related functions on this class.
279 * Payment processor classes should over-ride the capability-specific function rather than this one.
281 * @param string $capability
282 * E.g BackOffice, LiveMode, FutureRecurStartDate.
286 public function supports($capability) {
287 $function = 'supports' . ucfirst($capability);
288 if (method_exists($this, $function)) {
289 return $this->$function();
295 * Are back office payments supported.
297 * e.g paypal standard won't permit you to enter a credit card associated
298 * with someone else's login.
299 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
300 * reach a 'stable' point we disable.
304 protected function supportsBackOffice() {
305 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
314 * Can more than one transaction be processed at once?
316 * In general processors that process payment by server to server communication support this while others do not.
318 * In future we are likely to hit an issue where this depends on whether a token already exists.
322 protected function supportsMultipleConcurrentPayments() {
323 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
332 * Are live payments supported - e.g dummy doesn't support this.
336 protected function supportsLiveMode() {
341 * Are test payments supported.
345 protected function supportsTestMode() {
350 * Does this payment processor support refund?
354 public function supportsRefund() {
359 * Should the first payment date be configurable when setting up back office recurring payments.
361 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
365 protected function supportsFutureRecurStartDate() {
370 * Does this processor support cancelling recurring contributions through code.
372 * If the processor returns true it must be possible to take action from within CiviCRM
373 * that will result in no further payments being processed. In the case of token processors (e.g
374 * IATS, eWay) updating the contribution_recur table is probably sufficient.
378 protected function supportsCancelRecurring() {
379 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
383 * Does this processor support pre-approval.
385 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
387 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
388 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
389 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
393 protected function supportsPreApproval() {
398 * Does this processor support updating billing info for recurring contributions through code.
400 * If the processor returns true then it must be possible to update billing info from within CiviCRM
401 * that will be updated at the payment processor.
405 protected function supportsUpdateSubscriptionBillingInfo() {
406 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
410 * Can recurring contributions be set against pledges.
412 * In practice all processors that use the baseIPN function to finish transactions or
413 * call the completetransaction api support this by looking up previous contributions in the
414 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
415 * adding the new payment to the pledge.
417 * However, only enabling for processors it has been tested against.
421 protected function supportsRecurContributionsForPledges() {
426 * Function to action pre-approval if supported
428 * @param array $params
429 * Parameters from the form
431 * This function returns an array which should contain
432 * - pre_approval_parameters (this will be stored on the calling form & available later)
433 * - redirect_url (if set the browser will be redirected to this.
435 public function doPreApproval(&$params) {
439 * Get any details that may be available to the payment processor due to an approval process having happened.
441 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
444 * @param array $storedDetails
448 public function getPreApprovalDetails($storedDetails) {
453 * Default payment instrument validation.
455 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
456 * Not a static function, because I need to check for payment_type.
458 * @param array $values
459 * @param array $errors
461 public function validatePaymentInstrument($values, &$errors) {
462 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
463 if ($this->_paymentProcessor
['payment_type'] == 1) {
464 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
469 * Getter for the payment processor.
471 * The payment processor array is based on the civicrm_payment_processor table entry.
474 * Payment processor array.
476 public function getPaymentProcessor() {
477 return $this->_paymentProcessor
;
481 * Setter for the payment processor.
483 * @param array $processor
485 public function setPaymentProcessor($processor) {
486 $this->_paymentProcessor
= $processor;
490 * Setter for the payment form that wants to use the processor.
494 * @param CRM_Core_Form $paymentForm
496 public function setForm(&$paymentForm) {
497 $this->_paymentForm
= $paymentForm;
501 * Getter for payment form that is using the processor.
503 * @return CRM_Core_Form
506 public function getForm() {
507 return $this->_paymentForm
;
511 * Get help text information (help, description, etc.) about this payment,
512 * to display to the user.
514 * @param string $context
515 * Context of the text.
516 * Only explicitly supported contexts are handled without error.
517 * Currently supported:
518 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
520 * @param array $params
521 * Parameters for the field, context specific.
525 public function getText($context, $params) {
526 // I have deliberately added a noisy fail here.
527 // The function is intended to be extendable, but not by changes
528 // not documented clearly above.
530 case 'contributionPageRecurringHelp':
531 // require exactly two parameters
532 if (array_keys($params) == [
533 'is_recur_installments',
536 $gotText = ts('Your recurring contribution will be processed automatically.');
537 if ($params['is_recur_installments']) {
538 $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.');
540 if ($params['is_email_receipt']) {
541 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
546 case 'contributionPageContinueText':
547 if ($params['amount'] <= 0) {
548 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
550 if ($this->_paymentProcessor
['billing_mode'] == 4) {
551 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']]);
553 if ($params['is_payment_to_existing']) {
554 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
556 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
559 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
564 * Getter for accessing member vars.
566 * @todo believe this is unused
568 * @param string $name
572 public function getVar($name) {
573 return isset($this->$name) ?
$this->$name : NULL;
577 * Get name for the payment information type.
578 * @todo - use option group + name field (like Omnipay does)
581 public function getPaymentTypeName() {
582 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
586 * Get label for the payment information type.
587 * @todo - use option group + labels (like Omnipay does)
590 public function getPaymentTypeLabel() {
591 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
595 * Get array of fields that should be displayed on the payment form.
598 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
600 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
605 * Array of payment fields appropriate to the payment processor.
607 * @throws CiviCRM_API3_Exception
609 public function getPaymentFormFields() {
610 if ($this->_paymentProcessor
['billing_mode'] == 4) {
613 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
617 * Get an array of the fields that can be edited on the recurring contribution.
619 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
620 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
621 * can be updated from the contribution recur edit screen.
623 * The fields are likely to be a subset of these
626 * - 'frequency_interval',
627 * - 'frequency_unit',
629 * - 'next_sched_contribution_date',
631 * - 'failure_retry_day',
633 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
634 * metadata is not defined in the xml for the field it will cause an error.
636 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
637 * form (UpdateSubscription).
641 public function getEditableRecurringScheduleFields() {
642 if ($this->supports('changeSubscriptionAmount')) {
649 * Get the help text to present on the recurring update page.
651 * This should reflect what can or cannot be edited.
655 public function getRecurringScheduleUpdateHelpText() {
656 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
657 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.');
659 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.');
663 * Get the metadata for all required fields.
667 protected function getMandatoryFields() {
668 $mandatoryFields = [];
669 foreach ($this->getAllFields() as $field_name => $field_spec) {
670 if (!empty($field_spec['is_required'])) {
671 $mandatoryFields[$field_name] = $field_spec;
674 return $mandatoryFields;
678 * Get the metadata of all the fields configured for this processor.
682 protected function getAllFields() {
683 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
684 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
685 return array_merge($paymentFields, $billingFields);
689 * Get array of fields that should be displayed on the payment form for credit cards.
693 protected function getCreditCardFormFields() {
696 'credit_card_number',
698 'credit_card_exp_date',
703 * Get array of fields that should be displayed on the payment form for direct debits.
707 protected function getDirectDebitFormFields() {
710 'bank_account_number',
711 'bank_identification_number',
717 * Return an array of all the details about the fields potentially required for payment fields.
719 * Only those determined by getPaymentFormFields will actually be assigned to the form
724 public function getPaymentFormFieldsMetadata() {
725 //@todo convert credit card type into an option value
726 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
727 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
728 if (!$this->isBackOffice()) {
729 $isCVVRequired = TRUE;
732 'credit_card_number' => [
733 'htmlType' => 'text',
734 'name' => 'credit_card_number',
735 'title' => ts('Card Number'),
739 'autocomplete' => 'off',
740 'class' => 'creditcard',
742 'is_required' => TRUE,
743 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
746 'htmlType' => 'text',
748 'title' => ts('Security Code'),
752 'autocomplete' => 'off',
754 'is_required' => $isCVVRequired,
757 '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.'),
758 'rule_name' => 'integer',
759 'rule_parameters' => NULL,
763 'credit_card_exp_date' => [
764 'htmlType' => 'date',
765 'name' => 'credit_card_exp_date',
766 'title' => ts('Expiration Date'),
767 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
768 'is_required' => TRUE,
771 'rule_message' => ts('Card expiration date cannot be a past date.'),
772 'rule_name' => 'currentDate',
773 'rule_parameters' => TRUE,
776 'extra' => ['class' => 'crm-form-select'],
778 'credit_card_type' => [
779 'htmlType' => 'select',
780 'name' => 'credit_card_type',
781 'title' => ts('Card Type'),
782 'attributes' => $creditCardType,
783 'is_required' => FALSE,
785 'account_holder' => [
786 'htmlType' => 'text',
787 'name' => 'account_holder',
788 'title' => ts('Account Holder'),
792 'autocomplete' => 'on',
794 'is_required' => TRUE,
796 //e.g. IBAN can have maxlength of 34 digits
797 'bank_account_number' => [
798 'htmlType' => 'text',
799 'name' => 'bank_account_number',
800 'title' => ts('Bank Account Number'),
804 'autocomplete' => 'off',
808 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
809 'rule_name' => 'nopunctuation',
810 'rule_parameters' => NULL,
813 'is_required' => TRUE,
815 //e.g. SWIFT-BIC can have maxlength of 11 digits
816 'bank_identification_number' => [
817 'htmlType' => 'text',
818 'name' => 'bank_identification_number',
819 'title' => ts('Bank Identification Number'),
823 'autocomplete' => 'off',
825 'is_required' => TRUE,
828 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
829 'rule_name' => 'nopunctuation',
830 'rule_parameters' => NULL,
835 'htmlType' => 'text',
836 'name' => 'bank_name',
837 'title' => ts('Bank Name'),
841 'autocomplete' => 'off',
843 'is_required' => TRUE,
847 'htmlType' => 'text',
848 'name' => 'check_number',
849 'title' => ts('Check Number'),
850 'is_required' => FALSE,
851 'attributes' => NULL,
853 'pan_truncation' => [
854 'htmlType' => 'text',
855 'name' => 'pan_truncation',
856 'title' => ts('Last 4 digits of the card'),
857 'is_required' => FALSE,
862 'autocomplete' => 'off',
866 'rule_message' => ts('Please enter valid last 4 digit card number.'),
867 'rule_name' => 'numeric',
868 'rule_parameters' => NULL,
873 'htmlType' => 'hidden',
874 'name' => 'payment_token',
875 'title' => ts('Authorization token'),
876 'is_required' => FALSE,
879 'autocomplete' => 'off',
880 'id' => 'payment_token',
887 * Get billing fields required for this processor.
889 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
892 * @param int $billingLocationID
896 public function getBillingAddressFields($billingLocationID = NULL) {
897 if (!$billingLocationID) {
898 // Note that although the billing id is passed around the forms the idea that it would be anything other than
899 // the result of the function below doesn't seem to have eventuated.
900 // So taking this as a param is possibly something to be removed in favour of the standard default.
901 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
903 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
907 'first_name' => 'billing_first_name',
908 'middle_name' => 'billing_middle_name',
909 'last_name' => 'billing_last_name',
910 'street_address' => "billing_street_address-{$billingLocationID}",
911 'city' => "billing_city-{$billingLocationID}",
912 'country' => "billing_country_id-{$billingLocationID}",
913 'state_province' => "billing_state_province_id-{$billingLocationID}",
914 'postal_code' => "billing_postal_code-{$billingLocationID}",
919 * Get form metadata for billing address fields.
921 * @param int $billingLocationID
924 * Array of metadata for address fields.
926 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
927 if (!$billingLocationID) {
928 // Note that although the billing id is passed around the forms the idea that it would be anything other than
929 // the result of the function below doesn't seem to have eventuated.
930 // So taking this as a param is possibly something to be removed in favour of the standard default.
931 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
934 $metadata['billing_first_name'] = [
935 'htmlType' => 'text',
936 'name' => 'billing_first_name',
937 'title' => ts('Billing First Name'),
942 'autocomplete' => 'off',
944 'is_required' => TRUE,
947 $metadata['billing_middle_name'] = [
948 'htmlType' => 'text',
949 'name' => 'billing_middle_name',
950 'title' => ts('Billing Middle Name'),
955 'autocomplete' => 'off',
957 'is_required' => FALSE,
960 $metadata['billing_last_name'] = [
961 'htmlType' => 'text',
962 'name' => 'billing_last_name',
963 'title' => ts('Billing Last Name'),
968 'autocomplete' => 'off',
970 'is_required' => TRUE,
973 $metadata["billing_street_address-{$billingLocationID}"] = [
974 'htmlType' => 'text',
975 'name' => "billing_street_address-{$billingLocationID}",
976 'title' => ts('Street Address'),
981 'autocomplete' => 'off',
983 'is_required' => TRUE,
986 $metadata["billing_city-{$billingLocationID}"] = [
987 'htmlType' => 'text',
988 'name' => "billing_city-{$billingLocationID}",
989 'title' => ts('City'),
994 'autocomplete' => 'off',
996 'is_required' => TRUE,
999 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1000 'htmlType' => 'chainSelect',
1001 'title' => ts('State/Province'),
1002 'name' => "billing_state_province_id-{$billingLocationID}",
1004 'is_required' => TRUE,
1007 $metadata["billing_postal_code-{$billingLocationID}"] = [
1008 'htmlType' => 'text',
1009 'name' => "billing_postal_code-{$billingLocationID}",
1010 'title' => ts('Postal Code'),
1015 'autocomplete' => 'off',
1017 'is_required' => TRUE,
1020 $metadata["billing_country_id-{$billingLocationID}"] = [
1021 'htmlType' => 'select',
1022 'name' => "billing_country_id-{$billingLocationID}",
1023 'title' => ts('Country'),
1026 '' => ts('- select -'),
1027 ] + CRM_Core_PseudoConstant
::country(),
1028 'is_required' => TRUE,
1034 * Get base url dependent on component.
1036 * (or preferably set it using the setter function).
1040 protected function getBaseReturnUrl() {
1041 if ($this->baseReturnUrl
) {
1042 return $this->baseReturnUrl
;
1044 if ($this->_component
== 'event') {
1045 $baseURL = 'civicrm/event/register';
1048 $baseURL = 'civicrm/contribute/transact';
1054 * Get the currency for the transaction.
1056 * Handle any inconsistency about how it is passed in here.
1062 protected function getCurrency($params) {
1063 return CRM_Utils_Array
::value('currencyID', $params, CRM_Utils_Array
::value('currency', $params));
1067 * Get the currency for the transaction.
1069 * Handle any inconsistency about how it is passed in here.
1075 protected function getAmount($params) {
1076 return CRM_Utils_Money
::format($params['amount'], NULL, NULL, TRUE);
1080 * Get url to return to after cancelled or failed transaction.
1082 * @param string $qfKey
1083 * @param int $participantID
1085 * @return string cancel url
1087 public function getCancelUrl($qfKey, $participantID) {
1088 if (isset($this->cancelUrl
)) {
1089 return $this->cancelUrl
;
1092 if ($this->_component
== 'event') {
1093 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1096 'participantId' => $participantID,
1102 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1103 '_qf_Main_display' => 1,
1112 * Get URL to return the browser to on success.
1118 protected function getReturnSuccessUrl($qfKey) {
1119 if (isset($this->successUrl
)) {
1120 return $this->successUrl
;
1123 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1124 '_qf_ThankYou_display' => 1,
1132 * Get URL to return the browser to on failure.
1134 * @param string $key
1135 * @param int $participantID
1136 * @param int $eventID
1139 * URL for a failing transactor to be redirected to.
1141 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1142 if (isset($this->cancelUrl
)) {
1143 return $this->cancelUrl
;
1146 $test = $this->_is_test ?
'&action=preview' : '';
1147 if ($this->_component
== "event") {
1148 return CRM_Utils_System
::url('civicrm/event/register',
1149 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1154 return CRM_Utils_System
::url('civicrm/contribute/transact',
1155 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1162 * Get URl for when the back button is pressed.
1166 * @return string url
1168 protected function getGoBackUrl($qfKey) {
1169 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1170 '_qf_Confirm_display' => 'true',
1178 * Get the notify (aka ipn, web hook or silent post) url.
1180 * If there is no '.' in it we assume that we are dealing with localhost or
1181 * similar and it is unreachable from the web & hence invalid.
1184 * URL to notify outcome of transaction.
1186 protected function getNotifyUrl() {
1187 $url = CRM_Utils_System
::url(
1188 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1195 return (stristr($url, '.')) ?
$url : '';
1199 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1201 * Does a server to server payment transaction.
1203 * @param array $params
1204 * Assoc array of input parameters for this transaction.
1207 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1209 protected function doDirectPayment(&$params) {
1214 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1215 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1217 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1218 * the transaction & in fact doTransferCheckout would not traditionally come back.
1219 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1221 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1222 * In some cases the IPN will set the payment to "Completed" some time later.
1224 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1225 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1226 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1228 * @param array $params
1230 * @param string $component
1233 * Result array (containing at least the key payment_status_id)
1235 * @throws \Civi\Payment\Exception\PaymentProcessorException
1237 public function doPayment(&$params, $component = 'contribute') {
1238 $this->_component
= $component;
1239 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1241 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1242 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1243 // have an example of that at the mome.
1244 if ($params['amount'] == 0) {
1245 $result['payment_status_id'] = array_search('Completed', $statuses);
1249 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1250 $result = $this->doTransferCheckout($params, $component);
1251 if (is_array($result) && !isset($result['payment_status_id'])) {
1252 $result['payment_status_id'] = array_search('Pending', $statuses);
1256 $result = $this->doDirectPayment($params, $component);
1257 if (is_array($result) && !isset($result['payment_status_id'])) {
1258 if (!empty($params['is_recur'])) {
1259 // See comment block.
1260 $result['payment_status_id'] = array_search('Pending', $statuses);
1263 $result['payment_status_id'] = array_search('Completed', $statuses);
1267 if (is_a($result, 'CRM_Core_Error')) {
1268 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1276 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1278 * @param array $params
1280 * @throws \Civi\Payment\Exception\PaymentProcessorException
1282 public function doRefund(&$params) {}
1285 * Query payment processor for details about a transaction.
1287 * @param array $params
1288 * Array of parameters containing one of:
1289 * - trxn_id Id of an individual transaction.
1290 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1293 * Extra parameters retrieved.
1294 * Any parameters retrievable through this should be documented in the function comments at
1295 * CRM_Core_Payment::doQuery. Currently:
1296 * - fee_amount Amount of fee paid
1298 public function doQuery($params) {
1303 * This function checks to see if we have the right config values.
1306 * the error message if any
1308 abstract protected function checkConfig();
1311 * Redirect for paypal.
1313 * @todo move to paypal class or remove
1315 * @param $paymentProcessor
1319 public static function paypalRedirect(&$paymentProcessor) {
1320 if (!$paymentProcessor) {
1324 if (isset($_GET['payment_date']) &&
1325 isset($_GET['merchant_return_link']) &&
1326 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1327 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1336 * Handle incoming payment notification.
1338 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1340 * @todo move to0 \Civi\Payment\System factory method
1341 * Page callback for civicrm/payment/ipn
1343 public static function handleIPN() {
1345 self
::handlePaymentMethod(
1346 'PaymentNotification',
1348 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1349 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1350 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1354 catch (CRM_Core_Exception
$e) {
1355 Civi
::log()->error('ipn_payment_callback_exception', [
1357 'backtrace' => CRM_Core_Error
::formatBacktrace(debug_backtrace()),
1361 CRM_Utils_System
::civiExit();
1365 * Payment callback handler.
1367 * The processor_name or processor_id is passed in.
1368 * Note that processor_id is more reliable as one site may have more than one instance of a
1369 * processor & ideally the processor will be validating the results
1370 * Load requested payment processor and call that processor's handle<$method> method
1372 * @todo move to \Civi\Payment\System factory method
1374 * @param string $method
1375 * 'PaymentNotification' or 'PaymentCron'
1376 * @param array $params
1378 * @throws \CRM_Core_Exception
1379 * @throws \Exception
1381 public static function handlePaymentMethod($method, $params = []) {
1382 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1383 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1384 $lastParam = array_pop($q);
1385 if (is_numeric($lastParam)) {
1386 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1389 self
::logPaymentNotification($params);
1390 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1394 self
::logPaymentNotification($params);
1396 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1397 FROM civicrm_payment_processor_type ppt
1398 INNER JOIN civicrm_payment_processor pp
1399 ON pp.payment_processor_type_id = ppt.id
1402 if (isset($params['processor_id'])) {
1403 $sql .= " WHERE pp.id = %2";
1404 $args[2] = [$params['processor_id'], 'Integer'];
1405 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1408 // This is called when processor_name is passed - passing processor_id instead is recommended.
1409 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1411 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1414 $args[2] = [$params['processor_name'], 'String'];
1415 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1418 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1420 // Check whether we found anything at all.
1422 throw new CRM_Core_Exception($notFound);
1425 $method = 'handle' . $method;
1426 $extension_instance_found = FALSE;
1428 // In all likelihood, we'll just end up with the one instance returned here. But it's
1429 // possible we may get more. Hence, iterate through all instances ..
1431 while ($dao->fetch()) {
1432 // Check pp is extension - is this still required - surely the singleton below handles it.
1433 $ext = CRM_Extension_System
::singleton()->getMapper();
1434 if ($ext->isExtensionKey($dao->class_name
)) {
1435 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1436 require_once $ext->classToPath($paymentClass);
1439 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1441 // Should never be empty - we already established this processor_id exists and is active.
1442 if (empty($processorInstance)) {
1446 // Does PP implement this method, and can we call it?
1447 if (!method_exists($processorInstance, $method) ||
1448 !is_callable([$processorInstance, $method])
1450 // on the off chance there is a double implementation of this processor we should keep looking for another
1451 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1455 // Everything, it seems, is ok - execute pp callback handler
1456 $processorInstance->$method();
1457 $extension_instance_found = TRUE;
1460 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1461 $IPNParams = array_merge($_GET, $_REQUEST);
1462 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1463 if (!$extension_instance_found) {
1464 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1465 "%2 method is unsupported in legacy payment processors.";
1466 throw new CRM_Core_Exception(ts($message, [
1467 1 => $params['processor_name'],
1474 * Check whether a method is present ( & supported ) by the payment processor object.
1476 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1478 * @param string $method
1479 * Method to check for.
1483 public function isSupported($method) {
1484 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1488 * Some processors replace the form submit button with their own.
1490 * Returning false here will leave the button off front end forms.
1492 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1494 public function isSuppressSubmitButtons() {
1499 * Checks to see if invoice_id already exists in db.
1501 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1502 * it is better to standardise to being here.
1504 * @param int $invoiceId The ID to check.
1506 * @param null $contributionID
1507 * If a contribution exists pass in the contribution ID.
1510 * True if invoice ID otherwise exists, else false
1512 protected function checkDupe($invoiceId, $contributionID = NULL) {
1513 $contribution = new CRM_Contribute_DAO_Contribution();
1514 $contribution->invoice_id
= $invoiceId;
1515 if ($contributionID) {
1516 $contribution->whereAdd("id <> $contributionID");
1518 return $contribution->find();
1522 * Get url for users to manage this recurring contribution for this processor.
1524 * @param int $entityID
1525 * @param null $entity
1526 * @param string $action
1530 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1534 if (!$this->supports('cancelRecurring')) {
1537 $url = 'civicrm/contribute/unsubscribe';
1541 //in notify mode don't return the update billing url
1542 if (!$this->supports('updateSubscriptionBillingInfo')) {
1545 $url = 'civicrm/contribute/updatebilling';
1549 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1552 $url = 'civicrm/contribute/updaterecur';
1556 $userId = CRM_Core_Session
::singleton()->get('userID');
1558 $checksumValue = '';
1561 // Find related Contact
1565 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1569 case 'contribution':
1570 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1571 $entityArg = 'coid';
1576 SELECT DISTINCT con.contact_id
1577 FROM civicrm_contribution_recur rec
1578 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1580 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1586 $entityArg = 'crid';
1591 // Add entity arguments
1592 if ($entityArg != '') {
1593 // Add checksum argument
1594 if ($contactID != 0 && $userId != $contactID) {
1595 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1597 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1601 if ($this->supports('accountLoginURL')) {
1602 return $this->accountLoginURL();
1606 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1610 * Get description of payment to pass to processor.
1612 * This is often what people see in the interface so we want to get
1613 * as much unique information in as possible within the field length (& presumably the early part of the field)
1615 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1616 * having field names to clarify
1618 * @param array $params
1619 * @param int $length
1623 protected function getPaymentDescription($params, $length = 24) {
1628 'billing_first_name',
1629 'billing_last_name',
1632 if (isset($params['description'])) {
1633 $uninformativeStrings = [
1634 ts('Online Event Registration: '),
1635 ts('Online Contribution: '),
1637 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1639 foreach ($parts as $part) {
1640 if ((!empty($params[$part]))) {
1641 $validParts[] = $params[$part];
1644 return substr(implode('-', $validParts), 0, $length);
1648 * Checks if backoffice recurring edit is allowed
1652 public function supportsEditRecurringContribution() {
1657 * Does this processor support changing the amount for recurring contributions through code.
1659 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1660 * that will be updated at the payment processor.
1664 protected function supportsChangeSubscriptionAmount() {
1665 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
1669 * Checks if payment processor supports recurring contributions
1673 public function supportsRecurring() {
1674 if (!empty($this->_paymentProcessor
['is_recur'])) {
1681 * Checks if payment processor supports an account login URL
1682 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1683 * TODO: It is implemented by AuthorizeNET, any others?
1687 protected function supportsAccountLoginURL() {
1688 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
1692 * Should a receipt be sent out for a pending payment.
1694 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1696 public function isSendReceiptForPending() {