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';
83 protected $_paymentProcessor;
86 * Base url of the calling form (offsite processors).
90 protected $baseReturnUrl;
93 * Return url upon success (offsite processors).
97 protected $successUrl;
100 * Return url upon failure (offsite processors).
104 protected $cancelUrl;
107 * Processor type label.
109 * (Deprecated parameter but used in some messages).
115 public $_processorName;
118 * The profile configured to show on the billing form.
120 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
121 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
122 * requirements with the configured requirements.
124 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
127 * Note this change would probably include converting 'billing' to a reserved profile.
131 protected $billingProfile;
134 * Payment instrument ID.
136 * This is normally retrieved from the payment_processor table.
140 protected $paymentInstrumentID;
143 * Is this a back office transaction.
147 protected $backOffice = FALSE;
152 public function isBackOffice() {
153 return $this->backOffice
;
157 * Set back office property.
159 * @param bool $isBackOffice
161 public function setBackOffice($isBackOffice) {
162 $this->backOffice
= $isBackOffice;
166 * Get payment instrument id.
170 public function getPaymentInstrumentID() {
171 return $this->paymentInstrumentID ?
$this->paymentInstrumentID
: $this->_paymentProcessor
['payment_instrument_id'];
175 * Set payment Instrument id.
177 * By default we actually ignore the form value. The manual processor takes it more seriously.
179 * @param int $paymentInstrumentID
181 public function setPaymentInstrumentID($paymentInstrumentID) {
182 $this->paymentInstrumentID
= $this->_paymentProcessor
['payment_instrument_id'];
186 * Set base return path (offsite processors).
188 * This is only useful with an internal civicrm form.
191 * Internal civicrm path.
193 public function setBaseReturnUrl($url) {
194 $this->baseReturnUrl
= $url;
198 * Set success return URL (offsite processors).
200 * This overrides $baseReturnUrl
203 * Full url of site to return browser to upon success.
205 public function setSuccessUrl($url) {
206 $this->successUrl
= $url;
210 * Set cancel return URL (offsite processors).
212 * This overrides $baseReturnUrl
215 * Full url of site to return browser to upon failure.
217 public function setCancelUrl($url) {
218 $this->cancelUrl
= $url;
222 * Set the configured payment profile.
224 * @param int|string $value
226 public function setBillingProfile($value) {
227 $this->billingProfile
= $value;
231 * Opportunity for the payment processor to override the entire form build.
233 * @param CRM_Core_Form $form
236 * Should form building stop at this point?
238 public function buildForm(&$form) {
243 * Log payment notification message to forensic system log.
245 * @todo move to factory class \Civi\Payment\System (or similar)
247 * @param array $params
251 public static function logPaymentNotification($params) {
252 $message = 'payment_notification ';
253 if (!empty($params['processor_name'])) {
254 $message .= 'processor_name=' . $params['processor_name'];
256 if (!empty($params['processor_id'])) {
257 $message .= 'processor_id=' . $params['processor_id'];
260 $log = new CRM_Utils_SystemLogger();
261 $log->alert($message, $_REQUEST);
265 * Check if capability is supported.
267 * Capabilities have a one to one relationship with capability-related functions on this class.
269 * Payment processor classes should over-ride the capability-specific function rather than this one.
271 * @param string $capability
272 * E.g BackOffice, LiveMode, FutureRecurStartDate.
276 public function supports($capability) {
277 $function = 'supports' . ucfirst($capability);
278 if (method_exists($this, $function)) {
279 return $this->$function();
285 * Are back office payments supported.
287 * e.g paypal standard won't permit you to enter a credit card associated
288 * with someone else's login.
289 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
290 * reach a 'stable' point we disable.
294 protected function supportsBackOffice() {
295 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
304 * Can more than one transaction be processed at once?
306 * In general processors that process payment by server to server communication support this while others do not.
308 * In future we are likely to hit an issue where this depends on whether a token already exists.
312 protected function supportsMultipleConcurrentPayments() {
313 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
322 * Are live payments supported - e.g dummy doesn't support this.
326 protected function supportsLiveMode() {
331 * Are test payments supported.
335 protected function supportsTestMode() {
340 * Does this payment processor support refund?
344 public function supportsRefund() {
349 * Should the first payment date be configurable when setting up back office recurring payments.
351 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
355 protected function supportsFutureRecurStartDate() {
360 * Does this processor support cancelling recurring contributions through code.
362 * If the processor returns true it must be possible to take action from within CiviCRM
363 * that will result in no further payments being processed. In the case of token processors (e.g
364 * IATS, eWay) updating the contribution_recur table is probably sufficient.
368 protected function supportsCancelRecurring() {
369 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
373 * Does this processor support pre-approval.
375 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
377 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
378 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
379 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
383 protected function supportsPreApproval() {
388 * Does this processor support updating billing info for recurring contributions through code.
390 * If the processor returns true then it must be possible to update billing info from within CiviCRM
391 * that will be updated at the payment processor.
395 protected function supportsUpdateSubscriptionBillingInfo() {
396 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
400 * Can recurring contributions be set against pledges.
402 * In practice all processors that use the baseIPN function to finish transactions or
403 * call the completetransaction api support this by looking up previous contributions in the
404 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
405 * adding the new payment to the pledge.
407 * However, only enabling for processors it has been tested against.
411 protected function supportsRecurContributionsForPledges() {
416 * Function to action pre-approval if supported
418 * @param array $params
419 * Parameters from the form
421 * This function returns an array which should contain
422 * - pre_approval_parameters (this will be stored on the calling form & available later)
423 * - redirect_url (if set the browser will be redirected to this.
425 public function doPreApproval(&$params) {
429 * Get any details that may be available to the payment processor due to an approval process having happened.
431 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
434 * @param array $storedDetails
438 public function getPreApprovalDetails($storedDetails) {
443 * Default payment instrument validation.
445 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
446 * Not a static function, because I need to check for payment_type.
448 * @param array $values
449 * @param array $errors
451 public function validatePaymentInstrument($values, &$errors) {
452 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
453 if ($this->_paymentProcessor
['payment_type'] == 1) {
454 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
459 * Getter for the payment processor.
461 * The payment processor array is based on the civicrm_payment_processor table entry.
464 * Payment processor array.
466 public function getPaymentProcessor() {
467 return $this->_paymentProcessor
;
471 * Setter for the payment processor.
473 * @param array $processor
475 public function setPaymentProcessor($processor) {
476 $this->_paymentProcessor
= $processor;
480 * Setter for the payment form that wants to use the processor.
484 * @param CRM_Core_Form $paymentForm
486 public function setForm(&$paymentForm) {
487 $this->_paymentForm
= $paymentForm;
491 * Getter for payment form that is using the processor.
493 * @return CRM_Core_Form
496 public function getForm() {
497 return $this->_paymentForm
;
501 * Get help text information (help, description, etc.) about this payment,
502 * to display to the user.
504 * @param string $context
505 * Context of the text.
506 * Only explicitly supported contexts are handled without error.
507 * Currently supported:
508 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
510 * @param array $params
511 * Parameters for the field, context specific.
515 public function getText($context, $params) {
516 // I have deliberately added a noisy fail here.
517 // The function is intended to be extendable, but not by changes
518 // not documented clearly above.
520 case 'contributionPageRecurringHelp':
521 // require exactly two parameters
522 if (array_keys($params) == [
523 'is_recur_installments',
526 $gotText = ts('Your recurring contribution will be processed automatically.');
527 if ($params['is_recur_installments']) {
528 $gotText .= ' ' . ts('You can specify the number of installments, or you can leave the number of installments blank if you want to make an open-ended commitment. In either case, you can choose to cancel at any time.');
530 if ($params['is_email_receipt']) {
531 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
536 case 'contributionPageContinueText':
537 if ($params['amount'] <= 0) {
538 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
540 if ($this->_paymentProcessor
['billing_mode'] == 4) {
541 return ts('Click the <strong>Continue</strong> button to go to %1, where you will select your payment method and complete the contribution.', [$this->_paymentProcessor
['payment_processor_type']]);
543 if ($params['is_payment_to_existing']) {
544 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
546 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
549 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
554 * Getter for accessing member vars.
556 * @todo believe this is unused
558 * @param string $name
562 public function getVar($name) {
563 return isset($this->$name) ?
$this->$name : NULL;
567 * Get name for the payment information type.
568 * @todo - use option group + name field (like Omnipay does)
571 public function getPaymentTypeName() {
572 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
576 * Get label for the payment information type.
577 * @todo - use option group + labels (like Omnipay does)
580 public function getPaymentTypeLabel() {
581 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
585 * Get array of fields that should be displayed on the payment form.
588 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
590 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
595 * Array of payment fields appropriate to the payment processor.
597 * @throws CiviCRM_API3_Exception
599 public function getPaymentFormFields() {
600 if ($this->_paymentProcessor
['billing_mode'] == 4) {
603 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
607 * Get an array of the fields that can be edited on the recurring contribution.
609 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
610 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
611 * can be updated from the contribution recur edit screen.
613 * The fields are likely to be a subset of these
616 * - 'frequency_interval',
617 * - 'frequency_unit',
619 * - 'next_sched_contribution_date',
621 * - 'failure_retry_day',
623 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
624 * metadata is not defined in the xml for the field it will cause an error.
626 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
627 * form (UpdateSubscription).
631 public function getEditableRecurringScheduleFields() {
632 if ($this->supports('changeSubscriptionAmount')) {
638 * Get the help text to present on the recurring update page.
640 * This should reflect what can or cannot be edited.
644 public function getRecurringScheduleUpdateHelpText() {
645 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
646 return ts('Updates made using this form will change the recurring contribution information stored in your CiviCRM database, but will NOT be sent to the payment processor. You must enter the same changes using the payment processor web site.');
648 return ts('Use this form to change the amount or number of installments for this recurring contribution. Changes will be automatically sent to the payment processor. You can not change the contribution frequency.');
652 * Get the metadata for all required fields.
656 protected function getMandatoryFields() {
657 $mandatoryFields = [];
658 foreach ($this->getAllFields() as $field_name => $field_spec) {
659 if (!empty($field_spec['is_required'])) {
660 $mandatoryFields[$field_name] = $field_spec;
663 return $mandatoryFields;
667 * Get the metadata of all the fields configured for this processor.
671 protected function getAllFields() {
672 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
673 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
674 return array_merge($paymentFields, $billingFields);
678 * Get array of fields that should be displayed on the payment form for credit cards.
682 protected function getCreditCardFormFields() {
685 'credit_card_number',
687 'credit_card_exp_date',
692 * Get array of fields that should be displayed on the payment form for direct debits.
696 protected function getDirectDebitFormFields() {
699 'bank_account_number',
700 'bank_identification_number',
706 * Return an array of all the details about the fields potentially required for payment fields.
708 * Only those determined by getPaymentFormFields will actually be assigned to the form
713 public function getPaymentFormFieldsMetadata() {
714 //@todo convert credit card type into an option value
715 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
716 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
717 if (!$this->isBackOffice()) {
718 $isCVVRequired = TRUE;
721 'credit_card_number' => [
722 'htmlType' => 'text',
723 'name' => 'credit_card_number',
724 'title' => ts('Card Number'),
728 'autocomplete' => 'off',
729 'class' => 'creditcard',
731 'is_required' => TRUE,
732 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
735 'htmlType' => 'text',
737 'title' => ts('Security Code'),
741 'autocomplete' => 'off',
743 'is_required' => $isCVVRequired,
746 'rule_message' => ts('Please enter a valid value for your card security code. This is usually the last 3-4 digits on the card\'s signature panel.'),
747 'rule_name' => 'integer',
748 'rule_parameters' => NULL,
752 'credit_card_exp_date' => [
753 'htmlType' => 'date',
754 'name' => 'credit_card_exp_date',
755 'title' => ts('Expiration Date'),
756 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
757 'is_required' => TRUE,
760 'rule_message' => ts('Card expiration date cannot be a past date.'),
761 'rule_name' => 'currentDate',
762 'rule_parameters' => TRUE,
765 'extra' => ['class' => 'crm-form-select'],
767 'credit_card_type' => [
768 'htmlType' => 'select',
769 'name' => 'credit_card_type',
770 'title' => ts('Card Type'),
771 'attributes' => $creditCardType,
772 'is_required' => FALSE,
774 'account_holder' => [
775 'htmlType' => 'text',
776 'name' => 'account_holder',
777 'title' => ts('Account Holder'),
781 'autocomplete' => 'on',
783 'is_required' => TRUE,
785 //e.g. IBAN can have maxlength of 34 digits
786 'bank_account_number' => [
787 'htmlType' => 'text',
788 'name' => 'bank_account_number',
789 'title' => ts('Bank Account Number'),
793 'autocomplete' => 'off',
797 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
798 'rule_name' => 'nopunctuation',
799 'rule_parameters' => NULL,
802 'is_required' => TRUE,
804 //e.g. SWIFT-BIC can have maxlength of 11 digits
805 'bank_identification_number' => [
806 'htmlType' => 'text',
807 'name' => 'bank_identification_number',
808 'title' => ts('Bank Identification Number'),
812 'autocomplete' => 'off',
814 'is_required' => TRUE,
817 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
818 'rule_name' => 'nopunctuation',
819 'rule_parameters' => NULL,
824 'htmlType' => 'text',
825 'name' => 'bank_name',
826 'title' => ts('Bank Name'),
830 'autocomplete' => 'off',
832 'is_required' => TRUE,
836 'htmlType' => 'text',
837 'name' => 'check_number',
838 'title' => ts('Check Number'),
839 'is_required' => FALSE,
840 'attributes' => NULL,
842 'pan_truncation' => [
843 'htmlType' => 'text',
844 'name' => 'pan_truncation',
845 'title' => ts('Last 4 digits of the card'),
846 'is_required' => FALSE,
851 'autocomplete' => 'off',
855 'rule_message' => ts('Please enter valid last 4 digit card number.'),
856 'rule_name' => 'numeric',
857 'rule_parameters' => NULL,
862 'htmlType' => 'hidden',
863 'name' => 'payment_token',
864 'title' => ts('Authorization token'),
865 'is_required' => FALSE,
868 'autocomplete' => 'off',
869 'id' => 'payment_token',
876 * Get billing fields required for this processor.
878 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
881 * @param int $billingLocationID
885 public function getBillingAddressFields($billingLocationID = NULL) {
886 if (!$billingLocationID) {
887 // Note that although the billing id is passed around the forms the idea that it would be anything other than
888 // the result of the function below doesn't seem to have eventuated.
889 // So taking this as a param is possibly something to be removed in favour of the standard default.
890 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
892 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
896 'first_name' => 'billing_first_name',
897 'middle_name' => 'billing_middle_name',
898 'last_name' => 'billing_last_name',
899 'street_address' => "billing_street_address-{$billingLocationID}",
900 'city' => "billing_city-{$billingLocationID}",
901 'country' => "billing_country_id-{$billingLocationID}",
902 'state_province' => "billing_state_province_id-{$billingLocationID}",
903 'postal_code' => "billing_postal_code-{$billingLocationID}",
908 * Get form metadata for billing address fields.
910 * @param int $billingLocationID
913 * Array of metadata for address fields.
915 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
916 if (!$billingLocationID) {
917 // Note that although the billing id is passed around the forms the idea that it would be anything other than
918 // the result of the function below doesn't seem to have eventuated.
919 // So taking this as a param is possibly something to be removed in favour of the standard default.
920 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
923 $metadata['billing_first_name'] = [
924 'htmlType' => 'text',
925 'name' => 'billing_first_name',
926 'title' => ts('Billing First Name'),
931 'autocomplete' => 'off',
933 'is_required' => TRUE,
936 $metadata['billing_middle_name'] = [
937 'htmlType' => 'text',
938 'name' => 'billing_middle_name',
939 'title' => ts('Billing Middle Name'),
944 'autocomplete' => 'off',
946 'is_required' => FALSE,
949 $metadata['billing_last_name'] = [
950 'htmlType' => 'text',
951 'name' => 'billing_last_name',
952 'title' => ts('Billing Last Name'),
957 'autocomplete' => 'off',
959 'is_required' => TRUE,
962 $metadata["billing_street_address-{$billingLocationID}"] = [
963 'htmlType' => 'text',
964 'name' => "billing_street_address-{$billingLocationID}",
965 'title' => ts('Street Address'),
970 'autocomplete' => 'off',
972 'is_required' => TRUE,
975 $metadata["billing_city-{$billingLocationID}"] = [
976 'htmlType' => 'text',
977 'name' => "billing_city-{$billingLocationID}",
978 'title' => ts('City'),
983 'autocomplete' => 'off',
985 'is_required' => TRUE,
988 $metadata["billing_state_province_id-{$billingLocationID}"] = [
989 'htmlType' => 'chainSelect',
990 'title' => ts('State/Province'),
991 'name' => "billing_state_province_id-{$billingLocationID}",
993 'is_required' => TRUE,
996 $metadata["billing_postal_code-{$billingLocationID}"] = [
997 'htmlType' => 'text',
998 'name' => "billing_postal_code-{$billingLocationID}",
999 'title' => ts('Postal Code'),
1004 'autocomplete' => 'off',
1006 'is_required' => TRUE,
1009 $metadata["billing_country_id-{$billingLocationID}"] = [
1010 'htmlType' => 'select',
1011 'name' => "billing_country_id-{$billingLocationID}",
1012 'title' => ts('Country'),
1015 '' => ts('- select -'),
1016 ] + CRM_Core_PseudoConstant
::country(),
1017 'is_required' => TRUE,
1023 * Get base url dependent on component.
1025 * (or preferably set it using the setter function).
1029 protected function getBaseReturnUrl() {
1030 if ($this->baseReturnUrl
) {
1031 return $this->baseReturnUrl
;
1033 if ($this->_component
== 'event') {
1034 $baseURL = 'civicrm/event/register';
1037 $baseURL = 'civicrm/contribute/transact';
1043 * Get the currency for the transaction.
1045 * Handle any inconsistency about how it is passed in here.
1051 protected function getCurrency($params) {
1052 return CRM_Utils_Array
::value('currencyID', $params, CRM_Utils_Array
::value('currency', $params));
1056 * Get the currency for the transaction.
1058 * Handle any inconsistency about how it is passed in here.
1064 protected function getAmount($params) {
1065 return CRM_Utils_Money
::format($params['amount'], NULL, NULL, TRUE);
1069 * Get url to return to after cancelled or failed transaction.
1071 * @param string $qfKey
1072 * @param int $participantID
1074 * @return string cancel url
1076 public function getCancelUrl($qfKey, $participantID) {
1077 if (isset($this->cancelUrl
)) {
1078 return $this->cancelUrl
;
1081 if ($this->_component
== 'event') {
1082 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1085 'participantId' => $participantID,
1091 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1092 '_qf_Main_display' => 1,
1101 * Get URL to return the browser to on success.
1107 protected function getReturnSuccessUrl($qfKey) {
1108 if (isset($this->successUrl
)) {
1109 return $this->successUrl
;
1112 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1113 '_qf_ThankYou_display' => 1,
1121 * Get URL to return the browser to on failure.
1123 * @param string $key
1124 * @param int $participantID
1125 * @param int $eventID
1128 * URL for a failing transactor to be redirected to.
1130 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1131 if (isset($this->cancelUrl
)) {
1132 return $this->cancelUrl
;
1135 $test = $this->_is_test ?
'&action=preview' : '';
1136 if ($this->_component
== "event") {
1137 return CRM_Utils_System
::url('civicrm/event/register',
1138 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1143 return CRM_Utils_System
::url('civicrm/contribute/transact',
1144 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1151 * Get URl for when the back button is pressed.
1155 * @return string url
1157 protected function getGoBackUrl($qfKey) {
1158 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1159 '_qf_Confirm_display' => 'true',
1167 * Get the notify (aka ipn, web hook or silent post) url.
1169 * If there is no '.' in it we assume that we are dealing with localhost or
1170 * similar and it is unreachable from the web & hence invalid.
1173 * URL to notify outcome of transaction.
1175 protected function getNotifyUrl() {
1176 $url = CRM_Utils_System
::url(
1177 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1184 return (stristr($url, '.')) ?
$url : '';
1188 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1190 * Does a server to server payment transaction.
1192 * @param array $params
1193 * Assoc array of input parameters for this transaction.
1196 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1198 protected function doDirectPayment(&$params) {
1203 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1205 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
1208 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
1209 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
1210 * doTransferCheckout would not traditionally come back.
1212 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
1215 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
1216 * return Error objects
1219 * Payment processors should override this function directly instead of using doDirectPayment/doTransferCheckout which are deprecated.
1220 * Payment processors should set and return payment_status_id (Pending if the IPN will complete it, Completed if successful).
1221 * @fixme For the contribution workflow we have a contributionID, but for the event and membership workflow the contribution has not yet been created
1222 * so we can't update params directly on the contribution. However if you return trxn_id, fee_amount, net_amount they will be set on the contribution
1223 * by those workflows. Ideally all workflows would create a pending contribution BEFORE calling doPayment (eg. https://github.com/civicrm/civicrm-core/pull/13763 for events)
1225 * @param array $params
1227 * @param string $component
1232 * @throws \Civi\Payment\Exception\PaymentProcessorException
1234 public function doPayment(&$params, $component = 'contribute') {
1235 $this->_component
= $component;
1236 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1238 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1239 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1240 // have an example of that at the mome.
1241 if ($params['amount'] == 0) {
1242 $result['payment_status_id'] = array_search('Completed', $statuses);
1246 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1247 $result = $this->doTransferCheckout($params, $component);
1248 if (is_array($result) && !isset($result['payment_status_id'])) {
1249 $result['payment_status_id'] = array_search('Pending', $statuses);
1253 $result = $this->doDirectPayment($params, $component);
1254 if (is_array($result) && !isset($result['payment_status_id'])) {
1255 if (!empty($params['is_recur'])) {
1256 // See comment block.
1257 $result['payment_status_id'] = array_search('Pending', $statuses);
1260 $result['payment_status_id'] = array_search('Completed', $statuses);
1264 if (is_a($result, 'CRM_Core_Error')) {
1265 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1273 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1275 * @param array $params
1277 * @throws \Civi\Payment\Exception\PaymentProcessorException
1279 public function doRefund(&$params) {}
1282 * Query payment processor for details about a transaction.
1284 * @param array $params
1285 * Array of parameters containing one of:
1286 * - trxn_id Id of an individual transaction.
1287 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1290 * Extra parameters retrieved.
1291 * Any parameters retrievable through this should be documented in the function comments at
1292 * CRM_Core_Payment::doQuery. Currently:
1293 * - fee_amount Amount of fee paid
1295 public function doQuery($params) {
1300 * This function checks to see if we have the right config values.
1303 * the error message if any
1305 abstract protected function checkConfig();
1308 * Redirect for paypal.
1310 * @todo move to paypal class or remove
1312 * @param $paymentProcessor
1316 public static function paypalRedirect(&$paymentProcessor) {
1317 if (!$paymentProcessor) {
1321 if (isset($_GET['payment_date']) &&
1322 isset($_GET['merchant_return_link']) &&
1323 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1324 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1333 * Handle incoming payment notification.
1335 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1337 * @todo move to0 \Civi\Payment\System factory method
1338 * Page callback for civicrm/payment/ipn
1340 public static function handleIPN() {
1342 self
::handlePaymentMethod(
1343 'PaymentNotification',
1345 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1346 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1347 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1351 catch (CRM_Core_Exception
$e) {
1352 Civi
::log()->error('ipn_payment_callback_exception', [
1354 'backtrace' => CRM_Core_Error
::formatBacktrace(debug_backtrace()),
1358 CRM_Utils_System
::civiExit();
1362 * Payment callback handler.
1364 * The processor_name or processor_id is passed in.
1365 * Note that processor_id is more reliable as one site may have more than one instance of a
1366 * processor & ideally the processor will be validating the results
1367 * Load requested payment processor and call that processor's handle<$method> method
1369 * @todo move to \Civi\Payment\System factory method
1371 * @param string $method
1372 * 'PaymentNotification' or 'PaymentCron'
1373 * @param array $params
1375 * @throws \CRM_Core_Exception
1376 * @throws \Exception
1378 public static function handlePaymentMethod($method, $params = []) {
1379 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1380 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1381 $lastParam = array_pop($q);
1382 if (is_numeric($lastParam)) {
1383 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1386 self
::logPaymentNotification($params);
1387 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1391 self
::logPaymentNotification($params);
1393 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1394 FROM civicrm_payment_processor_type ppt
1395 INNER JOIN civicrm_payment_processor pp
1396 ON pp.payment_processor_type_id = ppt.id
1399 if (isset($params['processor_id'])) {
1400 $sql .= " WHERE pp.id = %2";
1401 $args[2] = [$params['processor_id'], 'Integer'];
1402 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1405 // This is called when processor_name is passed - passing processor_id instead is recommended.
1406 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1408 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1411 $args[2] = [$params['processor_name'], 'String'];
1412 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1415 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1417 // Check whether we found anything at all.
1419 throw new CRM_Core_Exception($notFound);
1422 $method = 'handle' . $method;
1423 $extension_instance_found = FALSE;
1425 // In all likelihood, we'll just end up with the one instance returned here. But it's
1426 // possible we may get more. Hence, iterate through all instances ..
1428 while ($dao->fetch()) {
1429 // Check pp is extension - is this still required - surely the singleton below handles it.
1430 $ext = CRM_Extension_System
::singleton()->getMapper();
1431 if ($ext->isExtensionKey($dao->class_name
)) {
1432 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1433 require_once $ext->classToPath($paymentClass);
1436 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1438 // Should never be empty - we already established this processor_id exists and is active.
1439 if (empty($processorInstance)) {
1443 // Does PP implement this method, and can we call it?
1444 if (!method_exists($processorInstance, $method) ||
1445 !is_callable([$processorInstance, $method])
1447 // on the off chance there is a double implementation of this processor we should keep looking for another
1448 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1452 // Everything, it seems, is ok - execute pp callback handler
1453 $processorInstance->$method();
1454 $extension_instance_found = TRUE;
1457 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1458 $IPNParams = array_merge($_GET, $_REQUEST);
1459 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1460 if (!$extension_instance_found) {
1461 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1462 "%2 method is unsupported in legacy payment processors.";
1463 throw new CRM_Core_Exception(ts($message, [
1464 1 => $params['processor_name'],
1471 * Check whether a method is present ( & supported ) by the payment processor object.
1473 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1475 * @param string $method
1476 * Method to check for.
1480 public function isSupported($method) {
1481 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1485 * Some processors replace the form submit button with their own.
1487 * Returning false here will leave the button off front end forms.
1489 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1491 public function isSuppressSubmitButtons() {
1496 * Checks to see if invoice_id already exists in db.
1498 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1499 * it is better to standardise to being here.
1501 * @param int $invoiceId The ID to check.
1503 * @param null $contributionID
1504 * If a contribution exists pass in the contribution ID.
1507 * True if invoice ID otherwise exists, else false
1509 protected function checkDupe($invoiceId, $contributionID = NULL) {
1510 $contribution = new CRM_Contribute_DAO_Contribution();
1511 $contribution->invoice_id
= $invoiceId;
1512 if ($contributionID) {
1513 $contribution->whereAdd("id <> $contributionID");
1515 return $contribution->find();
1519 * Get url for users to manage this recurring contribution for this processor.
1521 * @param int $entityID
1522 * @param null $entity
1523 * @param string $action
1527 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1531 if (!$this->supports('cancelRecurring')) {
1534 $url = 'civicrm/contribute/unsubscribe';
1538 //in notify mode don't return the update billing url
1539 if (!$this->supports('updateSubscriptionBillingInfo')) {
1542 $url = 'civicrm/contribute/updatebilling';
1546 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1549 $url = 'civicrm/contribute/updaterecur';
1553 $userId = CRM_Core_Session
::singleton()->get('userID');
1555 $checksumValue = '';
1558 // Find related Contact
1562 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1566 case 'contribution':
1567 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1568 $entityArg = 'coid';
1573 SELECT DISTINCT con.contact_id
1574 FROM civicrm_contribution_recur rec
1575 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1577 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1583 $entityArg = 'crid';
1588 // Add entity arguments
1589 if ($entityArg != '') {
1590 // Add checksum argument
1591 if ($contactID != 0 && $userId != $contactID) {
1592 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1594 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1598 if ($this->supports('accountLoginURL')) {
1599 return $this->accountLoginURL();
1603 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1607 * Get description of payment to pass to processor.
1609 * This is often what people see in the interface so we want to get
1610 * as much unique information in as possible within the field length (& presumably the early part of the field)
1612 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1613 * having field names to clarify
1615 * @param array $params
1616 * @param int $length
1620 protected function getPaymentDescription($params, $length = 24) {
1625 'billing_first_name',
1626 'billing_last_name',
1629 if (isset($params['description'])) {
1630 $uninformativeStrings = [
1631 ts('Online Event Registration: '),
1632 ts('Online Contribution: '),
1634 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1636 foreach ($parts as $part) {
1637 if ((!empty($params[$part]))) {
1638 $validParts[] = $params[$part];
1641 return substr(implode('-', $validParts), 0, $length);
1645 * Checks if backoffice recurring edit is allowed
1649 public function supportsEditRecurringContribution() {
1654 * Does this processor support changing the amount for recurring contributions through code.
1656 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1657 * that will be updated at the payment processor.
1661 protected function supportsChangeSubscriptionAmount() {
1662 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
1666 * Checks if payment processor supports recurring contributions
1670 public function supportsRecurring() {
1671 if (!empty($this->_paymentProcessor
['is_recur'])) {
1678 * Checks if payment processor supports an account login URL
1679 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1680 * TODO: It is implemented by AuthorizeNET, any others?
1684 protected function supportsAccountLoginURL() {
1685 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
1689 * Should a receipt be sent out for a pending payment.
1691 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1693 public function isSendReceiptForPending() {