3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Payment\System
;
13 use Civi\Payment\Exception\PaymentProcessorException
;
16 * Class CRM_Core_Payment.
18 * This class is the main class for the payment processor subsystem.
20 * It is the parent class for payment processors. It also holds some IPN related functions
21 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
23 abstract class CRM_Core_Payment
{
26 * Component - ie. event or contribute.
28 * This is used for setting return urls.
32 protected $_component;
35 * How are we getting billing information.
37 * We are trying to completely deprecate these parameters.
39 * FORM - we collect it on the same page
40 * BUTTON - the processor collects it and sends it back to us via some protocol
43 BILLING_MODE_FORM
= 1,
44 BILLING_MODE_BUTTON
= 2,
45 BILLING_MODE_NOTIFY
= 4;
48 * Which payment type(s) are we using?
53 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
56 PAYMENT_TYPE_CREDIT_CARD
= 1,
57 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
60 * Subscription / Recurring payment Status
64 RECURRING_PAYMENT_START
= 'START',
65 RECURRING_PAYMENT_END
= 'END';
70 protected $_paymentProcessor;
73 * Base url of the calling form (offsite processors).
77 protected $baseReturnUrl;
80 * Return url upon success (offsite processors).
84 protected $successUrl;
87 * Return url upon failure (offsite processors).
94 * Processor type label.
96 * (Deprecated parameter but used in some messages).
102 public $_processorName;
105 * The profile configured to show on the billing form.
107 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
108 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
109 * requirements with the configured requirements.
111 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
114 * Note this change would probably include converting 'billing' to a reserved profile.
118 protected $billingProfile;
121 * Payment instrument ID.
123 * This is normally retrieved from the payment_processor table.
127 protected $paymentInstrumentID;
130 * Is this a back office transaction.
134 protected $backOffice = FALSE;
139 public function isBackOffice() {
140 return $this->backOffice
;
144 * Set back office property.
146 * @param bool $isBackOffice
148 public function setBackOffice($isBackOffice) {
149 $this->backOffice
= $isBackOffice;
153 * Get payment instrument id.
157 public function getPaymentInstrumentID() {
158 return $this->paymentInstrumentID ?
$this->paymentInstrumentID
: $this->_paymentProcessor
['payment_instrument_id'];
166 public function getID() {
167 return (int) $this->_paymentProcessor
['id'];
171 * Set payment Instrument id.
173 * By default we actually ignore the form value. The manual processor takes it more seriously.
175 * @param int $paymentInstrumentID
177 public function setPaymentInstrumentID($paymentInstrumentID) {
178 $this->paymentInstrumentID
= $this->_paymentProcessor
['payment_instrument_id'];
182 * Set base return path (offsite processors).
184 * This is only useful with an internal civicrm form.
187 * Internal civicrm path.
189 public function setBaseReturnUrl($url) {
190 $this->baseReturnUrl
= $url;
194 * Set success return URL (offsite processors).
196 * This overrides $baseReturnUrl
199 * Full url of site to return browser to upon success.
201 public function setSuccessUrl($url) {
202 $this->successUrl
= $url;
206 * Set cancel return URL (offsite processors).
208 * This overrides $baseReturnUrl
211 * Full url of site to return browser to upon failure.
213 public function setCancelUrl($url) {
214 $this->cancelUrl
= $url;
218 * Set the configured payment profile.
220 * @param int|string $value
222 public function setBillingProfile($value) {
223 $this->billingProfile
= $value;
227 * Opportunity for the payment processor to override the entire form build.
229 * @param CRM_Core_Form $form
232 * Should form building stop at this point?
234 public function buildForm(&$form) {
239 * Log payment notification message to forensic system log.
241 * @todo move to factory class \Civi\Payment\System (or similar)
243 * @param array $params
245 public static function logPaymentNotification($params) {
246 $message = 'payment_notification ';
247 if (!empty($params['processor_name'])) {
248 $message .= 'processor_name=' . $params['processor_name'];
250 if (!empty($params['processor_id'])) {
251 $message .= 'processor_id=' . $params['processor_id'];
254 $log = new CRM_Utils_SystemLogger();
255 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
256 $rawRequestData = file_get_contents("php://input");
257 if (CRM_Utils_JSON
::isValidJSON($rawRequestData)) {
258 $log->alert($message, json_decode($rawRequestData, TRUE));
261 $log->alert($message, $_REQUEST);
266 * Check if capability is supported.
268 * Capabilities have a one to one relationship with capability-related functions on this class.
270 * Payment processor classes should over-ride the capability-specific function rather than this one.
272 * @param string $capability
273 * E.g BackOffice, LiveMode, FutureRecurStartDate.
277 public function supports($capability) {
278 $function = 'supports' . ucfirst($capability);
279 if (method_exists($this, $function)) {
280 return $this->$function();
286 * Are back office payments supported.
288 * e.g paypal standard won't permit you to enter a credit card associated
289 * with someone else's login.
290 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
291 * reach a 'stable' point we disable.
295 protected function supportsBackOffice() {
296 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
305 * Can more than one transaction be processed at once?
307 * In general processors that process payment by server to server communication support this while others do not.
309 * In future we are likely to hit an issue where this depends on whether a token already exists.
313 protected function supportsMultipleConcurrentPayments() {
314 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
323 * Are live payments supported - e.g dummy doesn't support this.
327 protected function supportsLiveMode() {
332 * Are test payments supported.
336 protected function supportsTestMode() {
341 * Does this payment processor support refund?
345 public function supportsRefund() {
350 * Should the first payment date be configurable when setting up back office recurring payments.
352 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
356 protected function supportsFutureRecurStartDate() {
361 * Does this processor support cancelling recurring contributions through code.
363 * If the processor returns true it must be possible to take action from within CiviCRM
364 * that will result in no further payments being processed. In the case of token processors (e.g
365 * IATS, eWay) updating the contribution_recur table is probably sufficient.
369 protected function supportsCancelRecurring() {
370 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
374 * Does this processor support pre-approval.
376 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
378 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
379 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
380 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
384 protected function supportsPreApproval() {
389 * Does this processor support updating billing info for recurring contributions through code.
391 * If the processor returns true then it must be possible to update billing info from within CiviCRM
392 * that will be updated at the payment processor.
396 protected function supportsUpdateSubscriptionBillingInfo() {
397 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
401 * Can recurring contributions be set against pledges.
403 * In practice all processors that use the baseIPN function to finish transactions or
404 * call the completetransaction api support this by looking up previous contributions in the
405 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
406 * adding the new payment to the pledge.
408 * However, only enabling for processors it has been tested against.
412 protected function supportsRecurContributionsForPledges() {
417 * Function to action pre-approval if supported
419 * @param array $params
420 * Parameters from the form
422 * This function returns an array which should contain
423 * - pre_approval_parameters (this will be stored on the calling form & available later)
424 * - redirect_url (if set the browser will be redirected to this.
426 public function doPreApproval(&$params) {
430 * Get any details that may be available to the payment processor due to an approval process having happened.
432 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
435 * @param array $storedDetails
439 public function getPreApprovalDetails($storedDetails) {
444 * Default payment instrument validation.
446 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
447 * Not a static function, because I need to check for payment_type.
449 * @param array $values
450 * @param array $errors
452 public function validatePaymentInstrument($values, &$errors) {
453 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
454 if ($this->_paymentProcessor
['payment_type'] == 1) {
455 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
460 * Getter for the payment processor.
462 * The payment processor array is based on the civicrm_payment_processor table entry.
465 * Payment processor array.
467 public function getPaymentProcessor() {
468 return $this->_paymentProcessor
;
472 * Setter for the payment processor.
474 * @param array $processor
476 public function setPaymentProcessor($processor) {
477 $this->_paymentProcessor
= $processor;
481 * Setter for the payment form that wants to use the processor.
485 * @param CRM_Core_Form $paymentForm
487 public function setForm(&$paymentForm) {
488 $this->_paymentForm
= $paymentForm;
492 * Getter for payment form that is using the processor.
494 * @return CRM_Core_Form
497 public function getForm() {
498 return $this->_paymentForm
;
502 * Get help text information (help, description, etc.) about this payment,
503 * to display to the user.
505 * @param string $context
506 * Context of the text.
507 * Only explicitly supported contexts are handled without error.
508 * Currently supported:
509 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
511 * @param array $params
512 * Parameters for the field, context specific.
516 public function getText($context, $params) {
517 // I have deliberately added a noisy fail here.
518 // The function is intended to be extendable, but not by changes
519 // not documented clearly above.
521 case 'contributionPageRecurringHelp':
522 // require exactly two parameters
523 if (array_keys($params) == [
524 'is_recur_installments',
527 $gotText = ts('Your recurring contribution will be processed automatically.');
528 if ($params['is_recur_installments']) {
529 $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.');
531 if ($params['is_email_receipt']) {
532 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
537 case 'contributionPageContinueText':
538 if ($params['amount'] <= 0) {
539 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
541 if ($this->_paymentProcessor
['billing_mode'] == 4) {
542 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']]);
544 if ($params['is_payment_to_existing']) {
545 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
547 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
550 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
555 * Getter for accessing member vars.
557 * @todo believe this is unused
559 * @param string $name
563 public function getVar($name) {
564 return isset($this->$name) ?
$this->$name : NULL;
568 * Get name for the payment information type.
569 * @todo - use option group + name field (like Omnipay does)
572 public function getPaymentTypeName() {
573 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
577 * Get label for the payment information type.
578 * @todo - use option group + labels (like Omnipay does)
581 public function getPaymentTypeLabel() {
582 return $this->_paymentProcessor
['payment_type'] == 1 ?
ts('Credit Card') : ts('Direct Debit');
586 * Get array of fields that should be displayed on the payment form.
589 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
591 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
596 * Array of payment fields appropriate to the payment processor.
598 * @throws CiviCRM_API3_Exception
600 public function getPaymentFormFields() {
601 if ($this->_paymentProcessor
['billing_mode'] == 4) {
604 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
608 * Get an array of the fields that can be edited on the recurring contribution.
610 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
611 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
612 * can be updated from the contribution recur edit screen.
614 * The fields are likely to be a subset of these
617 * - 'frequency_interval',
618 * - 'frequency_unit',
620 * - 'next_sched_contribution_date',
622 * - 'failure_retry_day',
624 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
625 * metadata is not defined in the xml for the field it will cause an error.
627 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
628 * form (UpdateSubscription).
632 public function getEditableRecurringScheduleFields() {
633 if ($this->supports('changeSubscriptionAmount')) {
640 * Get the help text to present on the recurring update page.
642 * This should reflect what can or cannot be edited.
646 public function getRecurringScheduleUpdateHelpText() {
647 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
648 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.');
650 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.');
654 * Get the metadata for all required fields.
658 protected function getMandatoryFields() {
659 $mandatoryFields = [];
660 foreach ($this->getAllFields() as $field_name => $field_spec) {
661 if (!empty($field_spec['is_required'])) {
662 $mandatoryFields[$field_name] = $field_spec;
665 return $mandatoryFields;
669 * Get the metadata of all the fields configured for this processor.
673 protected function getAllFields() {
674 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
675 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
676 return array_merge($paymentFields, $billingFields);
680 * Get array of fields that should be displayed on the payment form for credit cards.
684 protected function getCreditCardFormFields() {
687 'credit_card_number',
689 'credit_card_exp_date',
694 * Get array of fields that should be displayed on the payment form for direct debits.
698 protected function getDirectDebitFormFields() {
701 'bank_account_number',
702 'bank_identification_number',
708 * Return an array of all the details about the fields potentially required for payment fields.
710 * Only those determined by getPaymentFormFields will actually be assigned to the form
715 public function getPaymentFormFieldsMetadata() {
716 //@todo convert credit card type into an option value
717 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
718 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
719 if (!$this->isBackOffice()) {
720 $isCVVRequired = TRUE;
723 'credit_card_number' => [
724 'htmlType' => 'text',
725 'name' => 'credit_card_number',
726 'title' => ts('Card Number'),
730 'autocomplete' => 'off',
731 'class' => 'creditcard',
733 'is_required' => TRUE,
734 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
737 'htmlType' => 'text',
739 'title' => ts('Security Code'),
743 'autocomplete' => 'off',
745 'is_required' => $isCVVRequired,
748 '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.'),
749 'rule_name' => 'integer',
750 'rule_parameters' => NULL,
754 'credit_card_exp_date' => [
755 'htmlType' => 'date',
756 'name' => 'credit_card_exp_date',
757 'title' => ts('Expiration Date'),
758 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
759 'is_required' => TRUE,
762 'rule_message' => ts('Card expiration date cannot be a past date.'),
763 'rule_name' => 'currentDate',
764 'rule_parameters' => TRUE,
767 'extra' => ['class' => 'crm-form-select'],
769 'credit_card_type' => [
770 'htmlType' => 'select',
771 'name' => 'credit_card_type',
772 'title' => ts('Card Type'),
773 'attributes' => $creditCardType,
774 'is_required' => FALSE,
776 'account_holder' => [
777 'htmlType' => 'text',
778 'name' => 'account_holder',
779 'title' => ts('Account Holder'),
783 'autocomplete' => 'on',
785 'is_required' => TRUE,
787 //e.g. IBAN can have maxlength of 34 digits
788 'bank_account_number' => [
789 'htmlType' => 'text',
790 'name' => 'bank_account_number',
791 'title' => ts('Bank Account Number'),
795 'autocomplete' => 'off',
799 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
800 'rule_name' => 'nopunctuation',
801 'rule_parameters' => NULL,
804 'is_required' => TRUE,
806 //e.g. SWIFT-BIC can have maxlength of 11 digits
807 'bank_identification_number' => [
808 'htmlType' => 'text',
809 'name' => 'bank_identification_number',
810 'title' => ts('Bank Identification Number'),
814 'autocomplete' => 'off',
816 'is_required' => TRUE,
819 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
820 'rule_name' => 'nopunctuation',
821 'rule_parameters' => NULL,
826 'htmlType' => 'text',
827 'name' => 'bank_name',
828 'title' => ts('Bank Name'),
832 'autocomplete' => 'off',
834 'is_required' => TRUE,
838 'htmlType' => 'text',
839 'name' => 'check_number',
840 'title' => ts('Check Number'),
841 'is_required' => FALSE,
842 'attributes' => NULL,
844 'pan_truncation' => [
845 'htmlType' => 'text',
846 'name' => 'pan_truncation',
847 'title' => ts('Last 4 digits of the card'),
848 'is_required' => FALSE,
853 'autocomplete' => 'off',
857 'rule_message' => ts('Please enter valid last 4 digit card number.'),
858 'rule_name' => 'numeric',
859 'rule_parameters' => NULL,
864 'htmlType' => 'hidden',
865 'name' => 'payment_token',
866 'title' => ts('Authorization token'),
867 'is_required' => FALSE,
870 'autocomplete' => 'off',
871 'id' => 'payment_token',
878 * Get billing fields required for this processor.
880 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
883 * @param int $billingLocationID
887 public function getBillingAddressFields($billingLocationID = NULL) {
888 if (!$billingLocationID) {
889 // Note that although the billing id is passed around the forms the idea that it would be anything other than
890 // the result of the function below doesn't seem to have eventuated.
891 // So taking this as a param is possibly something to be removed in favour of the standard default.
892 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
894 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
898 'first_name' => 'billing_first_name',
899 'middle_name' => 'billing_middle_name',
900 'last_name' => 'billing_last_name',
901 'street_address' => "billing_street_address-{$billingLocationID}",
902 'city' => "billing_city-{$billingLocationID}",
903 'country' => "billing_country_id-{$billingLocationID}",
904 'state_province' => "billing_state_province_id-{$billingLocationID}",
905 'postal_code' => "billing_postal_code-{$billingLocationID}",
910 * Get form metadata for billing address fields.
912 * @param int $billingLocationID
915 * Array of metadata for address fields.
917 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
918 if (!$billingLocationID) {
919 // Note that although the billing id is passed around the forms the idea that it would be anything other than
920 // the result of the function below doesn't seem to have eventuated.
921 // So taking this as a param is possibly something to be removed in favour of the standard default.
922 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
925 $metadata['billing_first_name'] = [
926 'htmlType' => 'text',
927 'name' => 'billing_first_name',
928 'title' => ts('Billing First Name'),
933 'autocomplete' => 'off',
935 'is_required' => TRUE,
938 $metadata['billing_middle_name'] = [
939 'htmlType' => 'text',
940 'name' => 'billing_middle_name',
941 'title' => ts('Billing Middle Name'),
946 'autocomplete' => 'off',
948 'is_required' => FALSE,
951 $metadata['billing_last_name'] = [
952 'htmlType' => 'text',
953 'name' => 'billing_last_name',
954 'title' => ts('Billing Last Name'),
959 'autocomplete' => 'off',
961 'is_required' => TRUE,
964 $metadata["billing_street_address-{$billingLocationID}"] = [
965 'htmlType' => 'text',
966 'name' => "billing_street_address-{$billingLocationID}",
967 'title' => ts('Street Address'),
972 'autocomplete' => 'off',
974 'is_required' => TRUE,
977 $metadata["billing_city-{$billingLocationID}"] = [
978 'htmlType' => 'text',
979 'name' => "billing_city-{$billingLocationID}",
980 'title' => ts('City'),
985 'autocomplete' => 'off',
987 'is_required' => TRUE,
990 $metadata["billing_state_province_id-{$billingLocationID}"] = [
991 'htmlType' => 'chainSelect',
992 'title' => ts('State/Province'),
993 'name' => "billing_state_province_id-{$billingLocationID}",
995 'is_required' => TRUE,
998 $metadata["billing_postal_code-{$billingLocationID}"] = [
999 'htmlType' => 'text',
1000 'name' => "billing_postal_code-{$billingLocationID}",
1001 'title' => ts('Postal Code'),
1006 'autocomplete' => 'off',
1008 'is_required' => TRUE,
1011 $metadata["billing_country_id-{$billingLocationID}"] = [
1012 'htmlType' => 'select',
1013 'name' => "billing_country_id-{$billingLocationID}",
1014 'title' => ts('Country'),
1017 '' => ts('- select -'),
1018 ] + CRM_Core_PseudoConstant
::country(),
1019 'is_required' => TRUE,
1025 * Get base url dependent on component.
1027 * (or preferably set it using the setter function).
1031 protected function getBaseReturnUrl() {
1032 if ($this->baseReturnUrl
) {
1033 return $this->baseReturnUrl
;
1035 if ($this->_component
== 'event') {
1036 $baseURL = 'civicrm/event/register';
1039 $baseURL = 'civicrm/contribute/transact';
1045 * Get the currency for the transaction.
1047 * Handle any inconsistency about how it is passed in here.
1053 protected function getCurrency($params) {
1054 return CRM_Utils_Array
::value('currencyID', $params, CRM_Utils_Array
::value('currency', $params));
1058 * Get the currency for the transaction.
1060 * Handle any inconsistency about how it is passed in here.
1066 protected function getAmount($params) {
1067 return CRM_Utils_Money
::format($params['amount'], NULL, NULL, TRUE);
1071 * Get url to return to after cancelled or failed transaction.
1073 * @param string $qfKey
1074 * @param int $participantID
1076 * @return string cancel url
1078 public function getCancelUrl($qfKey, $participantID) {
1079 if (isset($this->cancelUrl
)) {
1080 return $this->cancelUrl
;
1083 if ($this->_component
== 'event') {
1084 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1087 'participantId' => $participantID,
1093 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1094 '_qf_Main_display' => 1,
1103 * Get URL to return the browser to on success.
1109 protected function getReturnSuccessUrl($qfKey) {
1110 if (isset($this->successUrl
)) {
1111 return $this->successUrl
;
1114 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1115 '_qf_ThankYou_display' => 1,
1123 * Get URL to return the browser to on failure.
1125 * @param string $key
1126 * @param int $participantID
1127 * @param int $eventID
1130 * URL for a failing transactor to be redirected to.
1132 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1133 if (isset($this->cancelUrl
)) {
1134 return $this->cancelUrl
;
1137 $test = $this->_is_test ?
'&action=preview' : '';
1138 if ($this->_component
== "event") {
1139 return CRM_Utils_System
::url('civicrm/event/register',
1140 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1145 return CRM_Utils_System
::url('civicrm/contribute/transact',
1146 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1153 * Get URl for when the back button is pressed.
1157 * @return string url
1159 protected function getGoBackUrl($qfKey) {
1160 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1161 '_qf_Confirm_display' => 'true',
1169 * Get the notify (aka ipn, web hook or silent post) url.
1171 * If there is no '.' in it we assume that we are dealing with localhost or
1172 * similar and it is unreachable from the web & hence invalid.
1175 * URL to notify outcome of transaction.
1177 protected function getNotifyUrl() {
1178 $url = CRM_Utils_System
::url(
1179 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1186 return (stristr($url, '.')) ?
$url : '';
1190 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1192 * Does a server to server payment transaction.
1194 * @param array $params
1195 * Assoc array of input parameters for this transaction.
1198 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1200 protected function doDirectPayment(&$params) {
1205 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1206 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1208 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1209 * the transaction & in fact doTransferCheckout would not traditionally come back.
1210 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1212 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1213 * In some cases the IPN will set the payment to "Completed" some time later.
1215 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1216 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1217 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1219 * @param array $params
1221 * @param string $component
1224 * Result array (containing at least the key payment_status_id)
1226 * @throws \Civi\Payment\Exception\PaymentProcessorException
1228 public function doPayment(&$params, $component = 'contribute') {
1229 $this->_component
= $component;
1230 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1232 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1233 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1234 // have an example of that at the mome.
1235 if ($params['amount'] == 0) {
1236 $result['payment_status_id'] = array_search('Completed', $statuses);
1240 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1241 $result = $this->doTransferCheckout($params, $component);
1242 if (is_array($result) && !isset($result['payment_status_id'])) {
1243 $result['payment_status_id'] = array_search('Pending', $statuses);
1247 $result = $this->doDirectPayment($params, $component);
1248 if (is_array($result) && !isset($result['payment_status_id'])) {
1249 if (!empty($params['is_recur'])) {
1250 // See comment block.
1251 $result['payment_status_id'] = array_search('Pending', $statuses);
1254 $result['payment_status_id'] = array_search('Completed', $statuses);
1258 if (is_a($result, 'CRM_Core_Error')) {
1259 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1267 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1269 * @param array $params
1271 * @throws \Civi\Payment\Exception\PaymentProcessorException
1273 public function doRefund(&$params) {}
1276 * Query payment processor for details about a transaction.
1278 * @param array $params
1279 * Array of parameters containing one of:
1280 * - trxn_id Id of an individual transaction.
1281 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1284 * Extra parameters retrieved.
1285 * Any parameters retrievable through this should be documented in the function comments at
1286 * CRM_Core_Payment::doQuery. Currently:
1287 * - fee_amount Amount of fee paid
1289 public function doQuery($params) {
1294 * This function checks to see if we have the right config values.
1297 * the error message if any
1299 abstract protected function checkConfig();
1302 * Redirect for paypal.
1304 * @todo move to paypal class or remove
1306 * @param $paymentProcessor
1310 public static function paypalRedirect(&$paymentProcessor) {
1311 if (!$paymentProcessor) {
1315 if (isset($_GET['payment_date']) &&
1316 isset($_GET['merchant_return_link']) &&
1317 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1318 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1327 * Handle incoming payment notification.
1329 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1331 * @todo move to0 \Civi\Payment\System factory method
1332 * Page callback for civicrm/payment/ipn
1334 public static function handleIPN() {
1336 self
::handlePaymentMethod(
1337 'PaymentNotification',
1339 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1340 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1341 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1345 catch (CRM_Core_Exception
$e) {
1346 Civi
::log()->error('ipn_payment_callback_exception', [
1348 'backtrace' => CRM_Core_Error
::formatBacktrace(debug_backtrace()),
1352 CRM_Utils_System
::civiExit();
1356 * Payment callback handler.
1358 * The processor_name or processor_id is passed in.
1359 * Note that processor_id is more reliable as one site may have more than one instance of a
1360 * processor & ideally the processor will be validating the results
1361 * Load requested payment processor and call that processor's handle<$method> method
1363 * @todo move to \Civi\Payment\System factory method
1365 * @param string $method
1366 * 'PaymentNotification' or 'PaymentCron'
1367 * @param array $params
1369 * @throws \CRM_Core_Exception
1370 * @throws \Exception
1372 public static function handlePaymentMethod($method, $params = []) {
1373 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1374 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1375 $lastParam = array_pop($q);
1376 if (is_numeric($lastParam)) {
1377 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1380 self
::logPaymentNotification($params);
1381 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1385 self
::logPaymentNotification($params);
1387 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1388 FROM civicrm_payment_processor_type ppt
1389 INNER JOIN civicrm_payment_processor pp
1390 ON pp.payment_processor_type_id = ppt.id
1393 if (isset($params['processor_id'])) {
1394 $sql .= " WHERE pp.id = %2";
1395 $args[2] = [$params['processor_id'], 'Integer'];
1396 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1399 // This is called when processor_name is passed - passing processor_id instead is recommended.
1400 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1402 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1405 $args[2] = [$params['processor_name'], 'String'];
1406 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1409 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1411 // Check whether we found anything at all.
1413 throw new CRM_Core_Exception($notFound);
1416 $method = 'handle' . $method;
1417 $extension_instance_found = FALSE;
1419 // In all likelihood, we'll just end up with the one instance returned here. But it's
1420 // possible we may get more. Hence, iterate through all instances ..
1422 while ($dao->fetch()) {
1423 // Check pp is extension - is this still required - surely the singleton below handles it.
1424 $ext = CRM_Extension_System
::singleton()->getMapper();
1425 if ($ext->isExtensionKey($dao->class_name
)) {
1426 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1427 require_once $ext->classToPath($paymentClass);
1430 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1432 // Should never be empty - we already established this processor_id exists and is active.
1433 if (empty($processorInstance)) {
1437 // Does PP implement this method, and can we call it?
1438 if (!method_exists($processorInstance, $method) ||
1439 !is_callable([$processorInstance, $method])
1441 // on the off chance there is a double implementation of this processor we should keep looking for another
1442 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1446 // Everything, it seems, is ok - execute pp callback handler
1447 $processorInstance->$method();
1448 $extension_instance_found = TRUE;
1451 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1452 $IPNParams = array_merge($_GET, $_REQUEST);
1453 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1454 if (!$extension_instance_found) {
1455 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1456 "%2 method is unsupported in legacy payment processors.";
1457 throw new CRM_Core_Exception(ts($message, [
1458 1 => $params['processor_name'],
1465 * Check whether a method is present ( & supported ) by the payment processor object.
1467 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1469 * @param string $method
1470 * Method to check for.
1474 public function isSupported($method) {
1475 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1479 * Some processors replace the form submit button with their own.
1481 * Returning false here will leave the button off front end forms.
1483 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1485 public function isSuppressSubmitButtons() {
1490 * Checks to see if invoice_id already exists in db.
1492 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1493 * it is better to standardise to being here.
1495 * @param int $invoiceId The ID to check.
1497 * @param null $contributionID
1498 * If a contribution exists pass in the contribution ID.
1501 * True if invoice ID otherwise exists, else false
1503 protected function checkDupe($invoiceId, $contributionID = NULL) {
1504 $contribution = new CRM_Contribute_DAO_Contribution();
1505 $contribution->invoice_id
= $invoiceId;
1506 if ($contributionID) {
1507 $contribution->whereAdd("id <> $contributionID");
1509 return $contribution->find();
1513 * Get url for users to manage this recurring contribution for this processor.
1515 * @param int $entityID
1516 * @param null $entity
1517 * @param string $action
1521 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1525 if (!$this->supports('cancelRecurring')) {
1528 $url = 'civicrm/contribute/unsubscribe';
1532 //in notify mode don't return the update billing url
1533 if (!$this->supports('updateSubscriptionBillingInfo')) {
1536 $url = 'civicrm/contribute/updatebilling';
1540 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1543 $url = 'civicrm/contribute/updaterecur';
1547 $userId = CRM_Core_Session
::singleton()->get('userID');
1549 $checksumValue = '';
1552 // Find related Contact
1556 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1560 case 'contribution':
1561 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1562 $entityArg = 'coid';
1567 SELECT DISTINCT con.contact_id
1568 FROM civicrm_contribution_recur rec
1569 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1571 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1577 $entityArg = 'crid';
1582 // Add entity arguments
1583 if ($entityArg != '') {
1584 // Add checksum argument
1585 if ($contactID != 0 && $userId != $contactID) {
1586 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1588 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1592 if ($this->supports('accountLoginURL')) {
1593 return $this->accountLoginURL();
1597 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1601 * Get description of payment to pass to processor.
1603 * This is often what people see in the interface so we want to get
1604 * as much unique information in as possible within the field length (& presumably the early part of the field)
1606 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1607 * having field names to clarify
1609 * @param array $params
1610 * @param int $length
1614 protected function getPaymentDescription($params, $length = 24) {
1619 'billing_first_name',
1620 'billing_last_name',
1623 if (isset($params['description'])) {
1624 $uninformativeStrings = [
1625 ts('Online Event Registration: '),
1626 ts('Online Contribution: '),
1628 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1630 foreach ($parts as $part) {
1631 if ((!empty($params[$part]))) {
1632 $validParts[] = $params[$part];
1635 return substr(implode('-', $validParts), 0, $length);
1639 * Checks if backoffice recurring edit is allowed
1643 public function supportsEditRecurringContribution() {
1648 * Does this processor support changing the amount for recurring contributions through code.
1650 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1651 * that will be updated at the payment processor.
1655 protected function supportsChangeSubscriptionAmount() {
1656 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
1660 * Checks if payment processor supports recurring contributions
1664 public function supportsRecurring() {
1665 if (!empty($this->_paymentProcessor
['is_recur'])) {
1672 * Checks if payment processor supports an account login URL
1673 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1674 * TODO: It is implemented by AuthorizeNET, any others?
1678 protected function supportsAccountLoginURL() {
1679 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
1683 * Should a receipt be sent out for a pending payment.
1685 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1687 public function isSendReceiptForPending() {