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'];
182 public function getID() {
183 return (int) $this->_paymentProcessor
['id'];
187 * Set payment Instrument id.
189 * By default we actually ignore the form value. The manual processor takes it more seriously.
191 * @param int $paymentInstrumentID
193 public function setPaymentInstrumentID($paymentInstrumentID) {
194 $this->paymentInstrumentID
= $this->_paymentProcessor
['payment_instrument_id'];
198 * Set base return path (offsite processors).
200 * This is only useful with an internal civicrm form.
203 * Internal civicrm path.
205 public function setBaseReturnUrl($url) {
206 $this->baseReturnUrl
= $url;
210 * Set success return URL (offsite processors).
212 * This overrides $baseReturnUrl
215 * Full url of site to return browser to upon success.
217 public function setSuccessUrl($url) {
218 $this->successUrl
= $url;
222 * Set cancel return URL (offsite processors).
224 * This overrides $baseReturnUrl
227 * Full url of site to return browser to upon failure.
229 public function setCancelUrl($url) {
230 $this->cancelUrl
= $url;
234 * Set the configured payment profile.
236 * @param int|string $value
238 public function setBillingProfile($value) {
239 $this->billingProfile
= $value;
243 * Opportunity for the payment processor to override the entire form build.
245 * @param CRM_Core_Form $form
248 * Should form building stop at this point?
250 public function buildForm(&$form) {
255 * Log payment notification message to forensic system log.
257 * @todo move to factory class \Civi\Payment\System (or similar)
259 * @param array $params
261 public static function logPaymentNotification($params) {
262 $message = 'payment_notification ';
263 if (!empty($params['processor_name'])) {
264 $message .= 'processor_name=' . $params['processor_name'];
266 if (!empty($params['processor_id'])) {
267 $message .= 'processor_id=' . $params['processor_id'];
270 $log = new CRM_Utils_SystemLogger();
271 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
272 $rawRequestData = file_get_contents("php://input");
273 if (CRM_Utils_JSON
::isValidJSON($rawRequestData)) {
274 $log->alert($message, json_decode($rawRequestData, TRUE));
277 $log->alert($message, $_REQUEST);
282 * Check if capability is supported.
284 * Capabilities have a one to one relationship with capability-related functions on this class.
286 * Payment processor classes should over-ride the capability-specific function rather than this one.
288 * @param string $capability
289 * E.g BackOffice, LiveMode, FutureRecurStartDate.
293 public function supports($capability) {
294 $function = 'supports' . ucfirst($capability);
295 if (method_exists($this, $function)) {
296 return $this->$function();
302 * Are back office payments supported.
304 * e.g paypal standard won't permit you to enter a credit card associated
305 * with someone else's login.
306 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
307 * reach a 'stable' point we disable.
311 protected function supportsBackOffice() {
312 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
321 * Can more than one transaction be processed at once?
323 * In general processors that process payment by server to server communication support this while others do not.
325 * In future we are likely to hit an issue where this depends on whether a token already exists.
329 protected function supportsMultipleConcurrentPayments() {
330 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
339 * Are live payments supported - e.g dummy doesn't support this.
343 protected function supportsLiveMode() {
348 * Are test payments supported.
352 protected function supportsTestMode() {
357 * Does this payment processor support refund?
361 public function supportsRefund() {
366 * Should the first payment date be configurable when setting up back office recurring payments.
368 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
372 protected function supportsFutureRecurStartDate() {
377 * Does this processor support cancelling recurring contributions through code.
379 * If the processor returns true it must be possible to take action from within CiviCRM
380 * that will result in no further payments being processed. In the case of token processors (e.g
381 * IATS, eWay) updating the contribution_recur table is probably sufficient.
385 protected function supportsCancelRecurring() {
386 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
390 * Does this processor support pre-approval.
392 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
394 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
395 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
396 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
400 protected function supportsPreApproval() {
405 * Does this processor support updating billing info for recurring contributions through code.
407 * If the processor returns true then it must be possible to update billing info from within CiviCRM
408 * that will be updated at the payment processor.
412 protected function supportsUpdateSubscriptionBillingInfo() {
413 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
417 * Can recurring contributions be set against pledges.
419 * In practice all processors that use the baseIPN function to finish transactions or
420 * call the completetransaction api support this by looking up previous contributions in the
421 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
422 * adding the new payment to the pledge.
424 * However, only enabling for processors it has been tested against.
428 protected function supportsRecurContributionsForPledges() {
433 * Function to action pre-approval if supported
435 * @param array $params
436 * Parameters from the form
438 * This function returns an array which should contain
439 * - pre_approval_parameters (this will be stored on the calling form & available later)
440 * - redirect_url (if set the browser will be redirected to this.
442 public function doPreApproval(&$params) {
446 * Get any details that may be available to the payment processor due to an approval process having happened.
448 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
451 * @param array $storedDetails
455 public function getPreApprovalDetails($storedDetails) {
460 * Default payment instrument validation.
462 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
463 * Not a static function, because I need to check for payment_type.
465 * @param array $values
466 * @param array $errors
468 public function validatePaymentInstrument($values, &$errors) {
469 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
470 if ($this->_paymentProcessor
['payment_type'] == 1) {
471 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
476 * Getter for the payment processor.
478 * The payment processor array is based on the civicrm_payment_processor table entry.
481 * Payment processor array.
483 public function getPaymentProcessor() {
484 return $this->_paymentProcessor
;
488 * Setter for the payment processor.
490 * @param array $processor
492 public function setPaymentProcessor($processor) {
493 $this->_paymentProcessor
= $processor;
497 * Setter for the payment form that wants to use the processor.
501 * @param CRM_Core_Form $paymentForm
503 public function setForm(&$paymentForm) {
504 $this->_paymentForm
= $paymentForm;
508 * Getter for payment form that is using the processor.
510 * @return CRM_Core_Form
513 public function getForm() {
514 return $this->_paymentForm
;
518 * Get help text information (help, description, etc.) about this payment,
519 * to display to the user.
521 * @param string $context
522 * Context of the text.
523 * Only explicitly supported contexts are handled without error.
524 * Currently supported:
525 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
527 * @param array $params
528 * Parameters for the field, context specific.
532 public function getText($context, $params) {
533 // I have deliberately added a noisy fail here.
534 // The function is intended to be extendable, but not by changes
535 // not documented clearly above.
537 case 'contributionPageRecurringHelp':
538 // require exactly two parameters
539 if (array_keys($params) == [
540 'is_recur_installments',
543 $gotText = ts('Your recurring contribution will be processed automatically.');
544 if ($params['is_recur_installments']) {
545 $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.');
547 if ($params['is_email_receipt']) {
548 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
553 case 'contributionPageContinueText':
554 if ($params['amount'] <= 0) {
555 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
557 if ($this->_paymentProcessor
['billing_mode'] == 4) {
558 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']]);
560 if ($params['is_payment_to_existing']) {
561 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
563 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
566 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
571 * Getter for accessing member vars.
573 * @todo believe this is unused
575 * @param string $name
579 public function getVar($name) {
580 return isset($this->$name) ?
$this->$name : NULL;
584 * Get name for the payment information type.
585 * @todo - use option group + name field (like Omnipay does)
588 public function getPaymentTypeName() {
589 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
593 * Get label for the payment information type.
594 * @todo - use option group + labels (like Omnipay does)
597 public function getPaymentTypeLabel() {
598 return $this->_paymentProcessor
['payment_type'] == 1 ?
ts('Credit Card') : ts('Direct Debit');
602 * Get array of fields that should be displayed on the payment form.
605 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
607 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
612 * Array of payment fields appropriate to the payment processor.
614 * @throws CiviCRM_API3_Exception
616 public function getPaymentFormFields() {
617 if ($this->_paymentProcessor
['billing_mode'] == 4) {
620 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
624 * Get an array of the fields that can be edited on the recurring contribution.
626 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
627 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
628 * can be updated from the contribution recur edit screen.
630 * The fields are likely to be a subset of these
633 * - 'frequency_interval',
634 * - 'frequency_unit',
636 * - 'next_sched_contribution_date',
638 * - 'failure_retry_day',
640 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
641 * metadata is not defined in the xml for the field it will cause an error.
643 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
644 * form (UpdateSubscription).
648 public function getEditableRecurringScheduleFields() {
649 if ($this->supports('changeSubscriptionAmount')) {
656 * Get the help text to present on the recurring update page.
658 * This should reflect what can or cannot be edited.
662 public function getRecurringScheduleUpdateHelpText() {
663 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
664 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.');
666 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.');
670 * Get the metadata for all required fields.
674 protected function getMandatoryFields() {
675 $mandatoryFields = [];
676 foreach ($this->getAllFields() as $field_name => $field_spec) {
677 if (!empty($field_spec['is_required'])) {
678 $mandatoryFields[$field_name] = $field_spec;
681 return $mandatoryFields;
685 * Get the metadata of all the fields configured for this processor.
689 protected function getAllFields() {
690 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
691 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
692 return array_merge($paymentFields, $billingFields);
696 * Get array of fields that should be displayed on the payment form for credit cards.
700 protected function getCreditCardFormFields() {
703 'credit_card_number',
705 'credit_card_exp_date',
710 * Get array of fields that should be displayed on the payment form for direct debits.
714 protected function getDirectDebitFormFields() {
717 'bank_account_number',
718 'bank_identification_number',
724 * Return an array of all the details about the fields potentially required for payment fields.
726 * Only those determined by getPaymentFormFields will actually be assigned to the form
731 public function getPaymentFormFieldsMetadata() {
732 //@todo convert credit card type into an option value
733 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
734 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
735 if (!$this->isBackOffice()) {
736 $isCVVRequired = TRUE;
739 'credit_card_number' => [
740 'htmlType' => 'text',
741 'name' => 'credit_card_number',
742 'title' => ts('Card Number'),
746 'autocomplete' => 'off',
747 'class' => 'creditcard',
749 'is_required' => TRUE,
750 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
753 'htmlType' => 'text',
755 'title' => ts('Security Code'),
759 'autocomplete' => 'off',
761 'is_required' => $isCVVRequired,
764 '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.'),
765 'rule_name' => 'integer',
766 'rule_parameters' => NULL,
770 'credit_card_exp_date' => [
771 'htmlType' => 'date',
772 'name' => 'credit_card_exp_date',
773 'title' => ts('Expiration Date'),
774 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
775 'is_required' => TRUE,
778 'rule_message' => ts('Card expiration date cannot be a past date.'),
779 'rule_name' => 'currentDate',
780 'rule_parameters' => TRUE,
783 'extra' => ['class' => 'crm-form-select'],
785 'credit_card_type' => [
786 'htmlType' => 'select',
787 'name' => 'credit_card_type',
788 'title' => ts('Card Type'),
789 'attributes' => $creditCardType,
790 'is_required' => FALSE,
792 'account_holder' => [
793 'htmlType' => 'text',
794 'name' => 'account_holder',
795 'title' => ts('Account Holder'),
799 'autocomplete' => 'on',
801 'is_required' => TRUE,
803 //e.g. IBAN can have maxlength of 34 digits
804 'bank_account_number' => [
805 'htmlType' => 'text',
806 'name' => 'bank_account_number',
807 'title' => ts('Bank Account Number'),
811 'autocomplete' => 'off',
815 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
816 'rule_name' => 'nopunctuation',
817 'rule_parameters' => NULL,
820 'is_required' => TRUE,
822 //e.g. SWIFT-BIC can have maxlength of 11 digits
823 'bank_identification_number' => [
824 'htmlType' => 'text',
825 'name' => 'bank_identification_number',
826 'title' => ts('Bank Identification Number'),
830 'autocomplete' => 'off',
832 'is_required' => TRUE,
835 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
836 'rule_name' => 'nopunctuation',
837 'rule_parameters' => NULL,
842 'htmlType' => 'text',
843 'name' => 'bank_name',
844 'title' => ts('Bank Name'),
848 'autocomplete' => 'off',
850 'is_required' => TRUE,
854 'htmlType' => 'text',
855 'name' => 'check_number',
856 'title' => ts('Check Number'),
857 'is_required' => FALSE,
858 'attributes' => NULL,
860 'pan_truncation' => [
861 'htmlType' => 'text',
862 'name' => 'pan_truncation',
863 'title' => ts('Last 4 digits of the card'),
864 'is_required' => FALSE,
869 'autocomplete' => 'off',
873 'rule_message' => ts('Please enter valid last 4 digit card number.'),
874 'rule_name' => 'numeric',
875 'rule_parameters' => NULL,
880 'htmlType' => 'hidden',
881 'name' => 'payment_token',
882 'title' => ts('Authorization token'),
883 'is_required' => FALSE,
886 'autocomplete' => 'off',
887 'id' => 'payment_token',
894 * Get billing fields required for this processor.
896 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
899 * @param int $billingLocationID
903 public function getBillingAddressFields($billingLocationID = NULL) {
904 if (!$billingLocationID) {
905 // Note that although the billing id is passed around the forms the idea that it would be anything other than
906 // the result of the function below doesn't seem to have eventuated.
907 // So taking this as a param is possibly something to be removed in favour of the standard default.
908 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
910 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
914 'first_name' => 'billing_first_name',
915 'middle_name' => 'billing_middle_name',
916 'last_name' => 'billing_last_name',
917 'street_address' => "billing_street_address-{$billingLocationID}",
918 'city' => "billing_city-{$billingLocationID}",
919 'country' => "billing_country_id-{$billingLocationID}",
920 'state_province' => "billing_state_province_id-{$billingLocationID}",
921 'postal_code' => "billing_postal_code-{$billingLocationID}",
926 * Get form metadata for billing address fields.
928 * @param int $billingLocationID
931 * Array of metadata for address fields.
933 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
934 if (!$billingLocationID) {
935 // Note that although the billing id is passed around the forms the idea that it would be anything other than
936 // the result of the function below doesn't seem to have eventuated.
937 // So taking this as a param is possibly something to be removed in favour of the standard default.
938 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
941 $metadata['billing_first_name'] = [
942 'htmlType' => 'text',
943 'name' => 'billing_first_name',
944 'title' => ts('Billing First Name'),
949 'autocomplete' => 'off',
951 'is_required' => TRUE,
954 $metadata['billing_middle_name'] = [
955 'htmlType' => 'text',
956 'name' => 'billing_middle_name',
957 'title' => ts('Billing Middle Name'),
962 'autocomplete' => 'off',
964 'is_required' => FALSE,
967 $metadata['billing_last_name'] = [
968 'htmlType' => 'text',
969 'name' => 'billing_last_name',
970 'title' => ts('Billing Last Name'),
975 'autocomplete' => 'off',
977 'is_required' => TRUE,
980 $metadata["billing_street_address-{$billingLocationID}"] = [
981 'htmlType' => 'text',
982 'name' => "billing_street_address-{$billingLocationID}",
983 'title' => ts('Street Address'),
988 'autocomplete' => 'off',
990 'is_required' => TRUE,
993 $metadata["billing_city-{$billingLocationID}"] = [
994 'htmlType' => 'text',
995 'name' => "billing_city-{$billingLocationID}",
996 'title' => ts('City'),
1001 'autocomplete' => 'off',
1003 'is_required' => TRUE,
1006 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1007 'htmlType' => 'chainSelect',
1008 'title' => ts('State/Province'),
1009 'name' => "billing_state_province_id-{$billingLocationID}",
1011 'is_required' => TRUE,
1014 $metadata["billing_postal_code-{$billingLocationID}"] = [
1015 'htmlType' => 'text',
1016 'name' => "billing_postal_code-{$billingLocationID}",
1017 'title' => ts('Postal Code'),
1022 'autocomplete' => 'off',
1024 'is_required' => TRUE,
1027 $metadata["billing_country_id-{$billingLocationID}"] = [
1028 'htmlType' => 'select',
1029 'name' => "billing_country_id-{$billingLocationID}",
1030 'title' => ts('Country'),
1033 '' => ts('- select -'),
1034 ] + CRM_Core_PseudoConstant
::country(),
1035 'is_required' => TRUE,
1041 * Get base url dependent on component.
1043 * (or preferably set it using the setter function).
1047 protected function getBaseReturnUrl() {
1048 if ($this->baseReturnUrl
) {
1049 return $this->baseReturnUrl
;
1051 if ($this->_component
== 'event') {
1052 $baseURL = 'civicrm/event/register';
1055 $baseURL = 'civicrm/contribute/transact';
1061 * Get the currency for the transaction.
1063 * Handle any inconsistency about how it is passed in here.
1069 protected function getCurrency($params) {
1070 return CRM_Utils_Array
::value('currencyID', $params, CRM_Utils_Array
::value('currency', $params));
1074 * Get the currency for the transaction.
1076 * Handle any inconsistency about how it is passed in here.
1082 protected function getAmount($params) {
1083 return CRM_Utils_Money
::format($params['amount'], NULL, NULL, TRUE);
1087 * Get url to return to after cancelled or failed transaction.
1089 * @param string $qfKey
1090 * @param int $participantID
1092 * @return string cancel url
1094 public function getCancelUrl($qfKey, $participantID) {
1095 if (isset($this->cancelUrl
)) {
1096 return $this->cancelUrl
;
1099 if ($this->_component
== 'event') {
1100 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1103 'participantId' => $participantID,
1109 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1110 '_qf_Main_display' => 1,
1119 * Get URL to return the browser to on success.
1125 protected function getReturnSuccessUrl($qfKey) {
1126 if (isset($this->successUrl
)) {
1127 return $this->successUrl
;
1130 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1131 '_qf_ThankYou_display' => 1,
1139 * Get URL to return the browser to on failure.
1141 * @param string $key
1142 * @param int $participantID
1143 * @param int $eventID
1146 * URL for a failing transactor to be redirected to.
1148 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1149 if (isset($this->cancelUrl
)) {
1150 return $this->cancelUrl
;
1153 $test = $this->_is_test ?
'&action=preview' : '';
1154 if ($this->_component
== "event") {
1155 return CRM_Utils_System
::url('civicrm/event/register',
1156 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1161 return CRM_Utils_System
::url('civicrm/contribute/transact',
1162 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1169 * Get URl for when the back button is pressed.
1173 * @return string url
1175 protected function getGoBackUrl($qfKey) {
1176 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1177 '_qf_Confirm_display' => 'true',
1185 * Get the notify (aka ipn, web hook or silent post) url.
1187 * If there is no '.' in it we assume that we are dealing with localhost or
1188 * similar and it is unreachable from the web & hence invalid.
1191 * URL to notify outcome of transaction.
1193 protected function getNotifyUrl() {
1194 $url = CRM_Utils_System
::url(
1195 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1202 return (stristr($url, '.')) ?
$url : '';
1206 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1208 * Does a server to server payment transaction.
1210 * @param array $params
1211 * Assoc array of input parameters for this transaction.
1214 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1216 protected function doDirectPayment(&$params) {
1221 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1222 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1224 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1225 * the transaction & in fact doTransferCheckout would not traditionally come back.
1226 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1228 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1229 * In some cases the IPN will set the payment to "Completed" some time later.
1231 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1232 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1233 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1235 * @param array $params
1237 * @param string $component
1240 * Result array (containing at least the key payment_status_id)
1242 * @throws \Civi\Payment\Exception\PaymentProcessorException
1244 public function doPayment(&$params, $component = 'contribute') {
1245 $this->_component
= $component;
1246 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1248 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1249 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1250 // have an example of that at the mome.
1251 if ($params['amount'] == 0) {
1252 $result['payment_status_id'] = array_search('Completed', $statuses);
1256 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1257 $result = $this->doTransferCheckout($params, $component);
1258 if (is_array($result) && !isset($result['payment_status_id'])) {
1259 $result['payment_status_id'] = array_search('Pending', $statuses);
1263 $result = $this->doDirectPayment($params, $component);
1264 if (is_array($result) && !isset($result['payment_status_id'])) {
1265 if (!empty($params['is_recur'])) {
1266 // See comment block.
1267 $result['payment_status_id'] = array_search('Pending', $statuses);
1270 $result['payment_status_id'] = array_search('Completed', $statuses);
1274 if (is_a($result, 'CRM_Core_Error')) {
1275 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1283 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1285 * @param array $params
1287 * @throws \Civi\Payment\Exception\PaymentProcessorException
1289 public function doRefund(&$params) {}
1292 * Query payment processor for details about a transaction.
1294 * @param array $params
1295 * Array of parameters containing one of:
1296 * - trxn_id Id of an individual transaction.
1297 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1300 * Extra parameters retrieved.
1301 * Any parameters retrievable through this should be documented in the function comments at
1302 * CRM_Core_Payment::doQuery. Currently:
1303 * - fee_amount Amount of fee paid
1305 public function doQuery($params) {
1310 * This function checks to see if we have the right config values.
1313 * the error message if any
1315 abstract protected function checkConfig();
1318 * Redirect for paypal.
1320 * @todo move to paypal class or remove
1322 * @param $paymentProcessor
1326 public static function paypalRedirect(&$paymentProcessor) {
1327 if (!$paymentProcessor) {
1331 if (isset($_GET['payment_date']) &&
1332 isset($_GET['merchant_return_link']) &&
1333 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1334 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1343 * Handle incoming payment notification.
1345 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1347 * @todo move to0 \Civi\Payment\System factory method
1348 * Page callback for civicrm/payment/ipn
1350 public static function handleIPN() {
1352 self
::handlePaymentMethod(
1353 'PaymentNotification',
1355 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1356 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1357 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1361 catch (CRM_Core_Exception
$e) {
1362 Civi
::log()->error('ipn_payment_callback_exception', [
1364 'backtrace' => CRM_Core_Error
::formatBacktrace(debug_backtrace()),
1368 CRM_Utils_System
::civiExit();
1372 * Payment callback handler.
1374 * The processor_name or processor_id is passed in.
1375 * Note that processor_id is more reliable as one site may have more than one instance of a
1376 * processor & ideally the processor will be validating the results
1377 * Load requested payment processor and call that processor's handle<$method> method
1379 * @todo move to \Civi\Payment\System factory method
1381 * @param string $method
1382 * 'PaymentNotification' or 'PaymentCron'
1383 * @param array $params
1385 * @throws \CRM_Core_Exception
1386 * @throws \Exception
1388 public static function handlePaymentMethod($method, $params = []) {
1389 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1390 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1391 $lastParam = array_pop($q);
1392 if (is_numeric($lastParam)) {
1393 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1396 self
::logPaymentNotification($params);
1397 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1401 self
::logPaymentNotification($params);
1403 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1404 FROM civicrm_payment_processor_type ppt
1405 INNER JOIN civicrm_payment_processor pp
1406 ON pp.payment_processor_type_id = ppt.id
1409 if (isset($params['processor_id'])) {
1410 $sql .= " WHERE pp.id = %2";
1411 $args[2] = [$params['processor_id'], 'Integer'];
1412 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1415 // This is called when processor_name is passed - passing processor_id instead is recommended.
1416 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1418 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1421 $args[2] = [$params['processor_name'], 'String'];
1422 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1425 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1427 // Check whether we found anything at all.
1429 throw new CRM_Core_Exception($notFound);
1432 $method = 'handle' . $method;
1433 $extension_instance_found = FALSE;
1435 // In all likelihood, we'll just end up with the one instance returned here. But it's
1436 // possible we may get more. Hence, iterate through all instances ..
1438 while ($dao->fetch()) {
1439 // Check pp is extension - is this still required - surely the singleton below handles it.
1440 $ext = CRM_Extension_System
::singleton()->getMapper();
1441 if ($ext->isExtensionKey($dao->class_name
)) {
1442 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1443 require_once $ext->classToPath($paymentClass);
1446 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1448 // Should never be empty - we already established this processor_id exists and is active.
1449 if (empty($processorInstance)) {
1453 // Does PP implement this method, and can we call it?
1454 if (!method_exists($processorInstance, $method) ||
1455 !is_callable([$processorInstance, $method])
1457 // on the off chance there is a double implementation of this processor we should keep looking for another
1458 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1462 // Everything, it seems, is ok - execute pp callback handler
1463 $processorInstance->$method();
1464 $extension_instance_found = TRUE;
1467 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1468 $IPNParams = array_merge($_GET, $_REQUEST);
1469 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1470 if (!$extension_instance_found) {
1471 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1472 "%2 method is unsupported in legacy payment processors.";
1473 throw new CRM_Core_Exception(ts($message, [
1474 1 => $params['processor_name'],
1481 * Check whether a method is present ( & supported ) by the payment processor object.
1483 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1485 * @param string $method
1486 * Method to check for.
1490 public function isSupported($method) {
1491 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1495 * Some processors replace the form submit button with their own.
1497 * Returning false here will leave the button off front end forms.
1499 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1501 public function isSuppressSubmitButtons() {
1506 * Checks to see if invoice_id already exists in db.
1508 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1509 * it is better to standardise to being here.
1511 * @param int $invoiceId The ID to check.
1513 * @param null $contributionID
1514 * If a contribution exists pass in the contribution ID.
1517 * True if invoice ID otherwise exists, else false
1519 protected function checkDupe($invoiceId, $contributionID = NULL) {
1520 $contribution = new CRM_Contribute_DAO_Contribution();
1521 $contribution->invoice_id
= $invoiceId;
1522 if ($contributionID) {
1523 $contribution->whereAdd("id <> $contributionID");
1525 return $contribution->find();
1529 * Get url for users to manage this recurring contribution for this processor.
1531 * @param int $entityID
1532 * @param null $entity
1533 * @param string $action
1537 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1541 if (!$this->supports('cancelRecurring')) {
1544 $url = 'civicrm/contribute/unsubscribe';
1548 //in notify mode don't return the update billing url
1549 if (!$this->supports('updateSubscriptionBillingInfo')) {
1552 $url = 'civicrm/contribute/updatebilling';
1556 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1559 $url = 'civicrm/contribute/updaterecur';
1563 $userId = CRM_Core_Session
::singleton()->get('userID');
1565 $checksumValue = '';
1568 // Find related Contact
1572 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1576 case 'contribution':
1577 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1578 $entityArg = 'coid';
1583 SELECT DISTINCT con.contact_id
1584 FROM civicrm_contribution_recur rec
1585 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1587 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1593 $entityArg = 'crid';
1598 // Add entity arguments
1599 if ($entityArg != '') {
1600 // Add checksum argument
1601 if ($contactID != 0 && $userId != $contactID) {
1602 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1604 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1608 if ($this->supports('accountLoginURL')) {
1609 return $this->accountLoginURL();
1613 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1617 * Get description of payment to pass to processor.
1619 * This is often what people see in the interface so we want to get
1620 * as much unique information in as possible within the field length (& presumably the early part of the field)
1622 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1623 * having field names to clarify
1625 * @param array $params
1626 * @param int $length
1630 protected function getPaymentDescription($params, $length = 24) {
1635 'billing_first_name',
1636 'billing_last_name',
1639 if (isset($params['description'])) {
1640 $uninformativeStrings = [
1641 ts('Online Event Registration: '),
1642 ts('Online Contribution: '),
1644 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1646 foreach ($parts as $part) {
1647 if ((!empty($params[$part]))) {
1648 $validParts[] = $params[$part];
1651 return substr(implode('-', $validParts), 0, $length);
1655 * Checks if backoffice recurring edit is allowed
1659 public function supportsEditRecurringContribution() {
1664 * Does this processor support changing the amount for recurring contributions through code.
1666 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1667 * that will be updated at the payment processor.
1671 protected function supportsChangeSubscriptionAmount() {
1672 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
1676 * Checks if payment processor supports recurring contributions
1680 public function supportsRecurring() {
1681 if (!empty($this->_paymentProcessor
['is_recur'])) {
1688 * Checks if payment processor supports an account login URL
1689 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1690 * TODO: It is implemented by AuthorizeNET, any others?
1694 protected function supportsAccountLoginURL() {
1695 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
1699 * Should a receipt be sent out for a pending payment.
1701 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1703 public function isSendReceiptForPending() {