3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 use Civi\Payment\System
;
29 use Civi\Payment\Exception\PaymentProcessorException
;
32 * Class CRM_Core_Payment.
34 * This class is the main class for the payment processor subsystem.
36 * It is the parent class for payment processors. It also holds some IPN related functions
37 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
39 abstract class CRM_Core_Payment
{
42 * Component - ie. event or contribute.
44 * This is used for setting return urls.
48 protected $_component;
51 * How are we getting billing information.
53 * We are trying to completely deprecate these parameters.
55 * FORM - we collect it on the same page
56 * BUTTON - the processor collects it and sends it back to us via some protocol
59 BILLING_MODE_FORM
= 1,
60 BILLING_MODE_BUTTON
= 2,
61 BILLING_MODE_NOTIFY
= 4;
64 * Which payment type(s) are we using?
69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
72 PAYMENT_TYPE_CREDIT_CARD
= 1,
73 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
76 * Subscription / Recurring payment Status
80 RECURRING_PAYMENT_START
= 'START',
81 RECURRING_PAYMENT_END
= 'END';
86 protected $_paymentProcessor;
89 * Base url of the calling form (offsite processors).
93 protected $baseReturnUrl;
96 * Return url upon success (offsite processors).
100 protected $successUrl;
103 * Return url upon failure (offsite processors).
107 protected $cancelUrl;
110 * Processor type label.
112 * (Deprecated parameter but used in some messages).
118 public $_processorName;
121 * The profile configured to show on the billing form.
123 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
124 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
125 * requirements with the configured requirements.
127 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
130 * Note this change would probably include converting 'billing' to a reserved profile.
134 protected $billingProfile;
137 * Payment instrument ID.
139 * This is normally retrieved from the payment_processor table.
143 protected $paymentInstrumentID;
146 * Is this a back office transaction.
150 protected $backOffice = FALSE;
155 public function isBackOffice() {
156 return $this->backOffice
;
160 * Set back office property.
162 * @param bool $isBackOffice
164 public function setBackOffice($isBackOffice) {
165 $this->backOffice
= $isBackOffice;
169 * Get payment instrument id.
173 public function getPaymentInstrumentID() {
174 return $this->paymentInstrumentID ?
$this->paymentInstrumentID
: $this->_paymentProcessor
['payment_instrument_id'];
178 * Set payment Instrument id.
180 * By default we actually ignore the form value. The manual processor takes it more seriously.
182 * @param int $paymentInstrumentID
184 public function setPaymentInstrumentID($paymentInstrumentID) {
185 $this->paymentInstrumentID
= $this->_paymentProcessor
['payment_instrument_id'];
189 * Set base return path (offsite processors).
191 * This is only useful with an internal civicrm form.
194 * Internal civicrm path.
196 public function setBaseReturnUrl($url) {
197 $this->baseReturnUrl
= $url;
201 * Set success return URL (offsite processors).
203 * This overrides $baseReturnUrl
206 * Full url of site to return browser to upon success.
208 public function setSuccessUrl($url) {
209 $this->successUrl
= $url;
213 * Set cancel return URL (offsite processors).
215 * This overrides $baseReturnUrl
218 * Full url of site to return browser to upon failure.
220 public function setCancelUrl($url) {
221 $this->cancelUrl
= $url;
225 * Set the configured payment profile.
227 * @param int|string $value
229 public function setBillingProfile($value) {
230 $this->billingProfile
= $value;
234 * Opportunity for the payment processor to override the entire form build.
236 * @param CRM_Core_Form $form
239 * Should form building stop at this point?
241 public function buildForm(&$form) {
246 * Log payment notification message to forensic system log.
248 * @todo move to factory class \Civi\Payment\System (or similar)
250 * @param array $params
254 public static function logPaymentNotification($params) {
255 $message = 'payment_notification ';
256 if (!empty($params['processor_name'])) {
257 $message .= 'processor_name=' . $params['processor_name'];
259 if (!empty($params['processor_id'])) {
260 $message .= 'processor_id=' . $params['processor_id'];
263 $log = new CRM_Utils_SystemLogger();
264 $log->alert($message, $_REQUEST);
268 * Check if capability is supported.
270 * Capabilities have a one to one relationship with capability-related functions on this class.
272 * Payment processor classes should over-ride the capability-specific function rather than this one.
274 * @param string $capability
275 * E.g BackOffice, LiveMode, FutureRecurStartDate.
279 public function supports($capability) {
280 $function = 'supports' . ucfirst($capability);
281 if (method_exists($this, $function)) {
282 return $this->$function();
288 * Are back office payments supported.
290 * e.g paypal standard won't permit you to enter a credit card associated
291 * with someone else's login.
292 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
293 * reach a 'stable' point we disable.
297 protected function supportsBackOffice() {
298 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
307 * Can more than one transaction be processed at once?
309 * In general processors that process payment by server to server communication support this while others do not.
311 * In future we are likely to hit an issue where this depends on whether a token already exists.
315 protected function supportsMultipleConcurrentPayments() {
316 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
325 * Are live payments supported - e.g dummy doesn't support this.
329 protected function supportsLiveMode() {
334 * Are test payments supported.
338 protected function supportsTestMode() {
343 * Does this payment processor support refund?
347 public function supportsRefund() {
352 * Should the first payment date be configurable when setting up back office recurring payments.
354 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
358 protected function supportsFutureRecurStartDate() {
363 * Does this processor support cancelling recurring contributions through code.
365 * If the processor returns true it must be possible to take action from within CiviCRM
366 * that will result in no further payments being processed. In the case of token processors (e.g
367 * IATS, eWay) updating the contribution_recur table is probably sufficient.
371 protected function supportsCancelRecurring() {
372 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
376 * Does this processor support pre-approval.
378 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
380 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
381 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
382 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
386 protected function supportsPreApproval() {
391 * Does this processor support updating billing info for recurring contributions through code.
393 * If the processor returns true then it must be possible to update billing info from within CiviCRM
394 * that will be updated at the payment processor.
398 protected function supportsUpdateSubscriptionBillingInfo() {
399 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
403 * Can recurring contributions be set against pledges.
405 * In practice all processors that use the baseIPN function to finish transactions or
406 * call the completetransaction api support this by looking up previous contributions in the
407 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
408 * adding the new payment to the pledge.
410 * However, only enabling for processors it has been tested against.
414 protected function supportsRecurContributionsForPledges() {
419 * Function to action pre-approval if supported
421 * @param array $params
422 * Parameters from the form
424 * This function returns an array which should contain
425 * - pre_approval_parameters (this will be stored on the calling form & available later)
426 * - redirect_url (if set the browser will be redirected to this.
428 public function doPreApproval(&$params) {
432 * Get any details that may be available to the payment processor due to an approval process having happened.
434 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
437 * @param array $storedDetails
441 public function getPreApprovalDetails($storedDetails) {
446 * Default payment instrument validation.
448 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
449 * Not a static function, because I need to check for payment_type.
451 * @param array $values
452 * @param array $errors
454 public function validatePaymentInstrument($values, &$errors) {
455 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
456 if ($this->_paymentProcessor
['payment_type'] == 1) {
457 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
462 * Getter for the payment processor.
464 * The payment processor array is based on the civicrm_payment_processor table entry.
467 * Payment processor array.
469 public function getPaymentProcessor() {
470 return $this->_paymentProcessor
;
474 * Setter for the payment processor.
476 * @param array $processor
478 public function setPaymentProcessor($processor) {
479 $this->_paymentProcessor
= $processor;
483 * Setter for the payment form that wants to use the processor.
487 * @param CRM_Core_Form $paymentForm
489 public function setForm(&$paymentForm) {
490 $this->_paymentForm
= $paymentForm;
494 * Getter for payment form that is using the processor.
496 * @return CRM_Core_Form
499 public function getForm() {
500 return $this->_paymentForm
;
504 * Get help text information (help, description, etc.) about this payment,
505 * to display to the user.
507 * @param string $context
508 * Context of the text.
509 * Only explicitly supported contexts are handled without error.
510 * Currently supported:
511 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
513 * @param array $params
514 * Parameters for the field, context specific.
518 public function getText($context, $params) {
519 // I have deliberately added a noisy fail here.
520 // The function is intended to be extendable, but not by changes
521 // not documented clearly above.
523 case 'contributionPageRecurringHelp':
524 // require exactly two parameters
525 if (array_keys($params) == [
526 'is_recur_installments',
529 $gotText = ts('Your recurring contribution will be processed automatically.');
530 if ($params['is_recur_installments']) {
531 $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.');
533 if ($params['is_email_receipt']) {
534 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
539 case 'contributionPageContinueText':
540 if ($params['amount'] <= 0) {
541 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
543 if ($this->_paymentProcessor
['billing_mode'] == 4) {
544 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']]);
546 if ($params['is_payment_to_existing']) {
547 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
549 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
552 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
557 * Getter for accessing member vars.
559 * @todo believe this is unused
561 * @param string $name
565 public function getVar($name) {
566 return isset($this->$name) ?
$this->$name : NULL;
570 * Get name for the payment information type.
571 * @todo - use option group + name field (like Omnipay does)
574 public function getPaymentTypeName() {
575 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
579 * Get label for the payment information type.
580 * @todo - use option group + labels (like Omnipay does)
583 public function getPaymentTypeLabel() {
584 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
588 * Get array of fields that should be displayed on the payment form.
591 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
593 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
598 * Array of payment fields appropriate to the payment processor.
600 * @throws CiviCRM_API3_Exception
602 public function getPaymentFormFields() {
603 if ($this->_paymentProcessor
['billing_mode'] == 4) {
606 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
610 * Get an array of the fields that can be edited on the recurring contribution.
612 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
613 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
614 * can be updated from the contribution recur edit screen.
616 * The fields are likely to be a subset of these
619 * - 'frequency_interval',
620 * - 'frequency_unit',
622 * - 'next_sched_contribution_date',
624 * - 'failure_retry_day',
626 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
627 * metadata is not defined in the xml for the field it will cause an error.
629 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
630 * form (UpdateSubscription).
634 public function getEditableRecurringScheduleFields() {
635 if ($this->supports('changeSubscriptionAmount')) {
642 * Get the help text to present on the recurring update page.
644 * This should reflect what can or cannot be edited.
648 public function getRecurringScheduleUpdateHelpText() {
649 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
650 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.');
652 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.');
656 * Get the metadata for all required fields.
660 protected function getMandatoryFields() {
661 $mandatoryFields = [];
662 foreach ($this->getAllFields() as $field_name => $field_spec) {
663 if (!empty($field_spec['is_required'])) {
664 $mandatoryFields[$field_name] = $field_spec;
667 return $mandatoryFields;
671 * Get the metadata of all the fields configured for this processor.
675 protected function getAllFields() {
676 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
677 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
678 return array_merge($paymentFields, $billingFields);
682 * Get array of fields that should be displayed on the payment form for credit cards.
686 protected function getCreditCardFormFields() {
689 'credit_card_number',
691 'credit_card_exp_date',
696 * Get array of fields that should be displayed on the payment form for direct debits.
700 protected function getDirectDebitFormFields() {
703 'bank_account_number',
704 'bank_identification_number',
710 * Return an array of all the details about the fields potentially required for payment fields.
712 * Only those determined by getPaymentFormFields will actually be assigned to the form
717 public function getPaymentFormFieldsMetadata() {
718 //@todo convert credit card type into an option value
719 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
720 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
721 if (!$this->isBackOffice()) {
722 $isCVVRequired = TRUE;
725 'credit_card_number' => [
726 'htmlType' => 'text',
727 'name' => 'credit_card_number',
728 'title' => ts('Card Number'),
732 'autocomplete' => 'off',
733 'class' => 'creditcard',
735 'is_required' => TRUE,
736 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
739 'htmlType' => 'text',
741 'title' => ts('Security Code'),
745 'autocomplete' => 'off',
747 'is_required' => $isCVVRequired,
750 '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.'),
751 'rule_name' => 'integer',
752 'rule_parameters' => NULL,
756 'credit_card_exp_date' => [
757 'htmlType' => 'date',
758 'name' => 'credit_card_exp_date',
759 'title' => ts('Expiration Date'),
760 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
761 'is_required' => TRUE,
764 'rule_message' => ts('Card expiration date cannot be a past date.'),
765 'rule_name' => 'currentDate',
766 'rule_parameters' => TRUE,
769 'extra' => ['class' => 'crm-form-select'],
771 'credit_card_type' => [
772 'htmlType' => 'select',
773 'name' => 'credit_card_type',
774 'title' => ts('Card Type'),
775 'attributes' => $creditCardType,
776 'is_required' => FALSE,
778 'account_holder' => [
779 'htmlType' => 'text',
780 'name' => 'account_holder',
781 'title' => ts('Account Holder'),
785 'autocomplete' => 'on',
787 'is_required' => TRUE,
789 //e.g. IBAN can have maxlength of 34 digits
790 'bank_account_number' => [
791 'htmlType' => 'text',
792 'name' => 'bank_account_number',
793 'title' => ts('Bank Account Number'),
797 'autocomplete' => 'off',
801 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
802 'rule_name' => 'nopunctuation',
803 'rule_parameters' => NULL,
806 'is_required' => TRUE,
808 //e.g. SWIFT-BIC can have maxlength of 11 digits
809 'bank_identification_number' => [
810 'htmlType' => 'text',
811 'name' => 'bank_identification_number',
812 'title' => ts('Bank Identification Number'),
816 'autocomplete' => 'off',
818 'is_required' => TRUE,
821 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
822 'rule_name' => 'nopunctuation',
823 'rule_parameters' => NULL,
828 'htmlType' => 'text',
829 'name' => 'bank_name',
830 'title' => ts('Bank Name'),
834 'autocomplete' => 'off',
836 'is_required' => TRUE,
840 'htmlType' => 'text',
841 'name' => 'check_number',
842 'title' => ts('Check Number'),
843 'is_required' => FALSE,
844 'attributes' => NULL,
846 'pan_truncation' => [
847 'htmlType' => 'text',
848 'name' => 'pan_truncation',
849 'title' => ts('Last 4 digits of the card'),
850 'is_required' => FALSE,
855 'autocomplete' => 'off',
859 'rule_message' => ts('Please enter valid last 4 digit card number.'),
860 'rule_name' => 'numeric',
861 'rule_parameters' => NULL,
866 'htmlType' => 'hidden',
867 'name' => 'payment_token',
868 'title' => ts('Authorization token'),
869 'is_required' => FALSE,
872 'autocomplete' => 'off',
873 'id' => 'payment_token',
880 * Get billing fields required for this processor.
882 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
885 * @param int $billingLocationID
889 public function getBillingAddressFields($billingLocationID = NULL) {
890 if (!$billingLocationID) {
891 // Note that although the billing id is passed around the forms the idea that it would be anything other than
892 // the result of the function below doesn't seem to have eventuated.
893 // So taking this as a param is possibly something to be removed in favour of the standard default.
894 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
896 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
900 'first_name' => 'billing_first_name',
901 'middle_name' => 'billing_middle_name',
902 'last_name' => 'billing_last_name',
903 'street_address' => "billing_street_address-{$billingLocationID}",
904 'city' => "billing_city-{$billingLocationID}",
905 'country' => "billing_country_id-{$billingLocationID}",
906 'state_province' => "billing_state_province_id-{$billingLocationID}",
907 'postal_code' => "billing_postal_code-{$billingLocationID}",
912 * Get form metadata for billing address fields.
914 * @param int $billingLocationID
917 * Array of metadata for address fields.
919 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
920 if (!$billingLocationID) {
921 // Note that although the billing id is passed around the forms the idea that it would be anything other than
922 // the result of the function below doesn't seem to have eventuated.
923 // So taking this as a param is possibly something to be removed in favour of the standard default.
924 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
927 $metadata['billing_first_name'] = [
928 'htmlType' => 'text',
929 'name' => 'billing_first_name',
930 'title' => ts('Billing First Name'),
935 'autocomplete' => 'off',
937 'is_required' => TRUE,
940 $metadata['billing_middle_name'] = [
941 'htmlType' => 'text',
942 'name' => 'billing_middle_name',
943 'title' => ts('Billing Middle Name'),
948 'autocomplete' => 'off',
950 'is_required' => FALSE,
953 $metadata['billing_last_name'] = [
954 'htmlType' => 'text',
955 'name' => 'billing_last_name',
956 'title' => ts('Billing Last Name'),
961 'autocomplete' => 'off',
963 'is_required' => TRUE,
966 $metadata["billing_street_address-{$billingLocationID}"] = [
967 'htmlType' => 'text',
968 'name' => "billing_street_address-{$billingLocationID}",
969 'title' => ts('Street Address'),
974 'autocomplete' => 'off',
976 'is_required' => TRUE,
979 $metadata["billing_city-{$billingLocationID}"] = [
980 'htmlType' => 'text',
981 'name' => "billing_city-{$billingLocationID}",
982 'title' => ts('City'),
987 'autocomplete' => 'off',
989 'is_required' => TRUE,
992 $metadata["billing_state_province_id-{$billingLocationID}"] = [
993 'htmlType' => 'chainSelect',
994 'title' => ts('State/Province'),
995 'name' => "billing_state_province_id-{$billingLocationID}",
997 'is_required' => TRUE,
1000 $metadata["billing_postal_code-{$billingLocationID}"] = [
1001 'htmlType' => 'text',
1002 'name' => "billing_postal_code-{$billingLocationID}",
1003 'title' => ts('Postal Code'),
1008 'autocomplete' => 'off',
1010 'is_required' => TRUE,
1013 $metadata["billing_country_id-{$billingLocationID}"] = [
1014 'htmlType' => 'select',
1015 'name' => "billing_country_id-{$billingLocationID}",
1016 'title' => ts('Country'),
1019 '' => ts('- select -'),
1020 ] + CRM_Core_PseudoConstant
::country(),
1021 'is_required' => TRUE,
1027 * Get base url dependent on component.
1029 * (or preferably set it using the setter function).
1033 protected function getBaseReturnUrl() {
1034 if ($this->baseReturnUrl
) {
1035 return $this->baseReturnUrl
;
1037 if ($this->_component
== 'event') {
1038 $baseURL = 'civicrm/event/register';
1041 $baseURL = 'civicrm/contribute/transact';
1047 * Get the currency for the transaction.
1049 * Handle any inconsistency about how it is passed in here.
1055 protected function getCurrency($params) {
1056 return CRM_Utils_Array
::value('currencyID', $params, CRM_Utils_Array
::value('currency', $params));
1060 * Get the currency for the transaction.
1062 * Handle any inconsistency about how it is passed in here.
1068 protected function getAmount($params) {
1069 return CRM_Utils_Money
::format($params['amount'], NULL, NULL, TRUE);
1073 * Get url to return to after cancelled or failed transaction.
1075 * @param string $qfKey
1076 * @param int $participantID
1078 * @return string cancel url
1080 public function getCancelUrl($qfKey, $participantID) {
1081 if (isset($this->cancelUrl
)) {
1082 return $this->cancelUrl
;
1085 if ($this->_component
== 'event') {
1086 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1089 'participantId' => $participantID,
1095 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1096 '_qf_Main_display' => 1,
1105 * Get URL to return the browser to on success.
1111 protected function getReturnSuccessUrl($qfKey) {
1112 if (isset($this->successUrl
)) {
1113 return $this->successUrl
;
1116 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1117 '_qf_ThankYou_display' => 1,
1125 * Get URL to return the browser to on failure.
1127 * @param string $key
1128 * @param int $participantID
1129 * @param int $eventID
1132 * URL for a failing transactor to be redirected to.
1134 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1135 if (isset($this->cancelUrl
)) {
1136 return $this->cancelUrl
;
1139 $test = $this->_is_test ?
'&action=preview' : '';
1140 if ($this->_component
== "event") {
1141 return CRM_Utils_System
::url('civicrm/event/register',
1142 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1147 return CRM_Utils_System
::url('civicrm/contribute/transact',
1148 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1155 * Get URl for when the back button is pressed.
1159 * @return string url
1161 protected function getGoBackUrl($qfKey) {
1162 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1163 '_qf_Confirm_display' => 'true',
1171 * Get the notify (aka ipn, web hook or silent post) url.
1173 * If there is no '.' in it we assume that we are dealing with localhost or
1174 * similar and it is unreachable from the web & hence invalid.
1177 * URL to notify outcome of transaction.
1179 protected function getNotifyUrl() {
1180 $url = CRM_Utils_System
::url(
1181 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1188 return (stristr($url, '.')) ?
$url : '';
1192 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1194 * Does a server to server payment transaction.
1196 * @param array $params
1197 * Assoc array of input parameters for this transaction.
1200 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1202 protected function doDirectPayment(&$params) {
1207 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1209 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
1212 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
1213 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
1214 * doTransferCheckout would not traditionally come back.
1216 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
1219 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
1220 * return Error objects
1223 * Payment processors should override this function directly instead of using doDirectPayment/doTransferCheckout which are deprecated.
1224 * Payment processors should set and return payment_status_id (Pending if the IPN will complete it, Completed if successful).
1225 * @fixme For the contribution workflow we have a contributionID, but for the event and membership workflow the contribution has not yet been created
1226 * 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
1227 * 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)
1229 * @param array $params
1231 * @param string $component
1236 * @throws \Civi\Payment\Exception\PaymentProcessorException
1238 public function doPayment(&$params, $component = 'contribute') {
1239 $this->_component
= $component;
1240 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1242 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1243 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1244 // have an example of that at the mome.
1245 if ($params['amount'] == 0) {
1246 $result['payment_status_id'] = array_search('Completed', $statuses);
1250 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1251 $result = $this->doTransferCheckout($params, $component);
1252 if (is_array($result) && !isset($result['payment_status_id'])) {
1253 $result['payment_status_id'] = array_search('Pending', $statuses);
1257 $result = $this->doDirectPayment($params, $component);
1258 if (is_array($result) && !isset($result['payment_status_id'])) {
1259 if (!empty($params['is_recur'])) {
1260 // See comment block.
1261 $result['payment_status_id'] = array_search('Pending', $statuses);
1264 $result['payment_status_id'] = array_search('Completed', $statuses);
1268 if (is_a($result, 'CRM_Core_Error')) {
1269 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1277 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1279 * @param array $params
1281 * @throws \Civi\Payment\Exception\PaymentProcessorException
1283 public function doRefund(&$params) {}
1286 * Query payment processor for details about a transaction.
1288 * @param array $params
1289 * Array of parameters containing one of:
1290 * - trxn_id Id of an individual transaction.
1291 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1294 * Extra parameters retrieved.
1295 * Any parameters retrievable through this should be documented in the function comments at
1296 * CRM_Core_Payment::doQuery. Currently:
1297 * - fee_amount Amount of fee paid
1299 public function doQuery($params) {
1304 * This function checks to see if we have the right config values.
1307 * the error message if any
1309 abstract protected function checkConfig();
1312 * Redirect for paypal.
1314 * @todo move to paypal class or remove
1316 * @param $paymentProcessor
1320 public static function paypalRedirect(&$paymentProcessor) {
1321 if (!$paymentProcessor) {
1325 if (isset($_GET['payment_date']) &&
1326 isset($_GET['merchant_return_link']) &&
1327 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1328 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1337 * Handle incoming payment notification.
1339 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1341 * @todo move to0 \Civi\Payment\System factory method
1342 * Page callback for civicrm/payment/ipn
1344 public static function handleIPN() {
1346 self
::handlePaymentMethod(
1347 'PaymentNotification',
1349 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1350 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1351 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1355 catch (CRM_Core_Exception
$e) {
1356 Civi
::log()->error('ipn_payment_callback_exception', [
1358 'backtrace' => CRM_Core_Error
::formatBacktrace(debug_backtrace()),
1362 CRM_Utils_System
::civiExit();
1366 * Payment callback handler.
1368 * The processor_name or processor_id is passed in.
1369 * Note that processor_id is more reliable as one site may have more than one instance of a
1370 * processor & ideally the processor will be validating the results
1371 * Load requested payment processor and call that processor's handle<$method> method
1373 * @todo move to \Civi\Payment\System factory method
1375 * @param string $method
1376 * 'PaymentNotification' or 'PaymentCron'
1377 * @param array $params
1379 * @throws \CRM_Core_Exception
1380 * @throws \Exception
1382 public static function handlePaymentMethod($method, $params = []) {
1383 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1384 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1385 $lastParam = array_pop($q);
1386 if (is_numeric($lastParam)) {
1387 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1390 self
::logPaymentNotification($params);
1391 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1395 self
::logPaymentNotification($params);
1397 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1398 FROM civicrm_payment_processor_type ppt
1399 INNER JOIN civicrm_payment_processor pp
1400 ON pp.payment_processor_type_id = ppt.id
1403 if (isset($params['processor_id'])) {
1404 $sql .= " WHERE pp.id = %2";
1405 $args[2] = [$params['processor_id'], 'Integer'];
1406 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1409 // This is called when processor_name is passed - passing processor_id instead is recommended.
1410 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1412 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1415 $args[2] = [$params['processor_name'], 'String'];
1416 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1419 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1421 // Check whether we found anything at all.
1423 throw new CRM_Core_Exception($notFound);
1426 $method = 'handle' . $method;
1427 $extension_instance_found = FALSE;
1429 // In all likelihood, we'll just end up with the one instance returned here. But it's
1430 // possible we may get more. Hence, iterate through all instances ..
1432 while ($dao->fetch()) {
1433 // Check pp is extension - is this still required - surely the singleton below handles it.
1434 $ext = CRM_Extension_System
::singleton()->getMapper();
1435 if ($ext->isExtensionKey($dao->class_name
)) {
1436 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1437 require_once $ext->classToPath($paymentClass);
1440 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1442 // Should never be empty - we already established this processor_id exists and is active.
1443 if (empty($processorInstance)) {
1447 // Does PP implement this method, and can we call it?
1448 if (!method_exists($processorInstance, $method) ||
1449 !is_callable([$processorInstance, $method])
1451 // on the off chance there is a double implementation of this processor we should keep looking for another
1452 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1456 // Everything, it seems, is ok - execute pp callback handler
1457 $processorInstance->$method();
1458 $extension_instance_found = TRUE;
1461 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1462 $IPNParams = array_merge($_GET, $_REQUEST);
1463 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1464 if (!$extension_instance_found) {
1465 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1466 "%2 method is unsupported in legacy payment processors.";
1467 throw new CRM_Core_Exception(ts($message, [
1468 1 => $params['processor_name'],
1475 * Check whether a method is present ( & supported ) by the payment processor object.
1477 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1479 * @param string $method
1480 * Method to check for.
1484 public function isSupported($method) {
1485 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1489 * Some processors replace the form submit button with their own.
1491 * Returning false here will leave the button off front end forms.
1493 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1495 public function isSuppressSubmitButtons() {
1500 * Checks to see if invoice_id already exists in db.
1502 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1503 * it is better to standardise to being here.
1505 * @param int $invoiceId The ID to check.
1507 * @param null $contributionID
1508 * If a contribution exists pass in the contribution ID.
1511 * True if invoice ID otherwise exists, else false
1513 protected function checkDupe($invoiceId, $contributionID = NULL) {
1514 $contribution = new CRM_Contribute_DAO_Contribution();
1515 $contribution->invoice_id
= $invoiceId;
1516 if ($contributionID) {
1517 $contribution->whereAdd("id <> $contributionID");
1519 return $contribution->find();
1523 * Get url for users to manage this recurring contribution for this processor.
1525 * @param int $entityID
1526 * @param null $entity
1527 * @param string $action
1531 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1535 if (!$this->supports('cancelRecurring')) {
1538 $url = 'civicrm/contribute/unsubscribe';
1542 //in notify mode don't return the update billing url
1543 if (!$this->supports('updateSubscriptionBillingInfo')) {
1546 $url = 'civicrm/contribute/updatebilling';
1550 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1553 $url = 'civicrm/contribute/updaterecur';
1557 $userId = CRM_Core_Session
::singleton()->get('userID');
1559 $checksumValue = '';
1562 // Find related Contact
1566 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1570 case 'contribution':
1571 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1572 $entityArg = 'coid';
1577 SELECT DISTINCT con.contact_id
1578 FROM civicrm_contribution_recur rec
1579 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1581 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1587 $entityArg = 'crid';
1592 // Add entity arguments
1593 if ($entityArg != '') {
1594 // Add checksum argument
1595 if ($contactID != 0 && $userId != $contactID) {
1596 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1598 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1602 if ($this->supports('accountLoginURL')) {
1603 return $this->accountLoginURL();
1607 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1611 * Get description of payment to pass to processor.
1613 * This is often what people see in the interface so we want to get
1614 * as much unique information in as possible within the field length (& presumably the early part of the field)
1616 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1617 * having field names to clarify
1619 * @param array $params
1620 * @param int $length
1624 protected function getPaymentDescription($params, $length = 24) {
1629 'billing_first_name',
1630 'billing_last_name',
1633 if (isset($params['description'])) {
1634 $uninformativeStrings = [
1635 ts('Online Event Registration: '),
1636 ts('Online Contribution: '),
1638 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1640 foreach ($parts as $part) {
1641 if ((!empty($params[$part]))) {
1642 $validParts[] = $params[$part];
1645 return substr(implode('-', $validParts), 0, $length);
1649 * Checks if backoffice recurring edit is allowed
1653 public function supportsEditRecurringContribution() {
1658 * Does this processor support changing the amount for recurring contributions through code.
1660 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1661 * that will be updated at the payment processor.
1665 protected function supportsChangeSubscriptionAmount() {
1666 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
1670 * Checks if payment processor supports recurring contributions
1674 public function supportsRecurring() {
1675 if (!empty($this->_paymentProcessor
['is_recur'])) {
1682 * Checks if payment processor supports an account login URL
1683 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1684 * TODO: It is implemented by AuthorizeNET, any others?
1688 protected function supportsAccountLoginURL() {
1689 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
1693 * Should a receipt be sent out for a pending payment.
1695 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1697 public function isSendReceiptForPending() {