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
263 public static function logPaymentNotification($params) {
264 $message = 'payment_notification ';
265 if (!empty($params['processor_name'])) {
266 $message .= 'processor_name=' . $params['processor_name'];
268 if (!empty($params['processor_id'])) {
269 $message .= 'processor_id=' . $params['processor_id'];
272 $log = new CRM_Utils_SystemLogger();
273 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
274 $rawRequestData = file_get_contents("php://input");
275 if (CRM_Utils_JSON
::isValidJSON($rawRequestData)) {
276 $log->alert($message, json_decode($rawRequestData, TRUE));
279 $log->alert($message, $_REQUEST);
284 * Check if capability is supported.
286 * Capabilities have a one to one relationship with capability-related functions on this class.
288 * Payment processor classes should over-ride the capability-specific function rather than this one.
290 * @param string $capability
291 * E.g BackOffice, LiveMode, FutureRecurStartDate.
295 public function supports($capability) {
296 $function = 'supports' . ucfirst($capability);
297 if (method_exists($this, $function)) {
298 return $this->$function();
304 * Are back office payments supported.
306 * e.g paypal standard won't permit you to enter a credit card associated
307 * with someone else's login.
308 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
309 * reach a 'stable' point we disable.
313 protected function supportsBackOffice() {
314 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
323 * Can more than one transaction be processed at once?
325 * In general processors that process payment by server to server communication support this while others do not.
327 * In future we are likely to hit an issue where this depends on whether a token already exists.
331 protected function supportsMultipleConcurrentPayments() {
332 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
341 * Are live payments supported - e.g dummy doesn't support this.
345 protected function supportsLiveMode() {
350 * Are test payments supported.
354 protected function supportsTestMode() {
359 * Does this payment processor support refund?
363 public function supportsRefund() {
368 * Should the first payment date be configurable when setting up back office recurring payments.
370 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
374 protected function supportsFutureRecurStartDate() {
379 * Does this processor support cancelling recurring contributions through code.
381 * If the processor returns true it must be possible to take action from within CiviCRM
382 * that will result in no further payments being processed. In the case of token processors (e.g
383 * IATS, eWay) updating the contribution_recur table is probably sufficient.
387 protected function supportsCancelRecurring() {
388 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
392 * Does this processor support pre-approval.
394 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
396 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
397 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
398 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
402 protected function supportsPreApproval() {
407 * Does this processor support updating billing info for recurring contributions through code.
409 * If the processor returns true then it must be possible to update billing info from within CiviCRM
410 * that will be updated at the payment processor.
414 protected function supportsUpdateSubscriptionBillingInfo() {
415 return method_exists(CRM_Utils_System
::getClassName($this), 'updateSubscriptionBillingInfo');
419 * Can recurring contributions be set against pledges.
421 * In practice all processors that use the baseIPN function to finish transactions or
422 * call the completetransaction api support this by looking up previous contributions in the
423 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
424 * adding the new payment to the pledge.
426 * However, only enabling for processors it has been tested against.
430 protected function supportsRecurContributionsForPledges() {
435 * Function to action pre-approval if supported
437 * @param array $params
438 * Parameters from the form
440 * This function returns an array which should contain
441 * - pre_approval_parameters (this will be stored on the calling form & available later)
442 * - redirect_url (if set the browser will be redirected to this.
444 public function doPreApproval(&$params) {
448 * Get any details that may be available to the payment processor due to an approval process having happened.
450 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
453 * @param array $storedDetails
457 public function getPreApprovalDetails($storedDetails) {
462 * Default payment instrument validation.
464 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
465 * Not a static function, because I need to check for payment_type.
467 * @param array $values
468 * @param array $errors
470 public function validatePaymentInstrument($values, &$errors) {
471 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
472 if ($this->_paymentProcessor
['payment_type'] == 1) {
473 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
478 * Getter for the payment processor.
480 * The payment processor array is based on the civicrm_payment_processor table entry.
483 * Payment processor array.
485 public function getPaymentProcessor() {
486 return $this->_paymentProcessor
;
490 * Setter for the payment processor.
492 * @param array $processor
494 public function setPaymentProcessor($processor) {
495 $this->_paymentProcessor
= $processor;
499 * Setter for the payment form that wants to use the processor.
503 * @param CRM_Core_Form $paymentForm
505 public function setForm(&$paymentForm) {
506 $this->_paymentForm
= $paymentForm;
510 * Getter for payment form that is using the processor.
512 * @return CRM_Core_Form
515 public function getForm() {
516 return $this->_paymentForm
;
520 * Get help text information (help, description, etc.) about this payment,
521 * to display to the user.
523 * @param string $context
524 * Context of the text.
525 * Only explicitly supported contexts are handled without error.
526 * Currently supported:
527 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
529 * @param array $params
530 * Parameters for the field, context specific.
534 public function getText($context, $params) {
535 // I have deliberately added a noisy fail here.
536 // The function is intended to be extendable, but not by changes
537 // not documented clearly above.
539 case 'contributionPageRecurringHelp':
540 // require exactly two parameters
541 if (array_keys($params) == [
542 'is_recur_installments',
545 $gotText = ts('Your recurring contribution will be processed automatically.');
546 if ($params['is_recur_installments']) {
547 $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.');
549 if ($params['is_email_receipt']) {
550 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
555 case 'contributionPageContinueText':
556 if ($params['amount'] <= 0) {
557 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
559 if ($this->_paymentProcessor
['billing_mode'] == 4) {
560 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']]);
562 if ($params['is_payment_to_existing']) {
563 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
565 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
568 CRM_Core_Error
::deprecatedFunctionWarning('Calls to getText must use a supported method');
573 * Getter for accessing member vars.
575 * @todo believe this is unused
577 * @param string $name
581 public function getVar($name) {
582 return isset($this->$name) ?
$this->$name : NULL;
586 * Get name for the payment information type.
587 * @todo - use option group + name field (like Omnipay does)
590 public function getPaymentTypeName() {
591 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
595 * Get label for the payment information type.
596 * @todo - use option group + labels (like Omnipay does)
599 public function getPaymentTypeLabel() {
600 return $this->_paymentProcessor
['payment_type'] == 1 ?
ts('Credit Card') : ts('Direct Debit');
604 * Get array of fields that should be displayed on the payment form.
607 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
609 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
614 * Array of payment fields appropriate to the payment processor.
616 * @throws CiviCRM_API3_Exception
618 public function getPaymentFormFields() {
619 if ($this->_paymentProcessor
['billing_mode'] == 4) {
622 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
626 * Get an array of the fields that can be edited on the recurring contribution.
628 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
629 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
630 * can be updated from the contribution recur edit screen.
632 * The fields are likely to be a subset of these
635 * - 'frequency_interval',
636 * - 'frequency_unit',
638 * - 'next_sched_contribution_date',
640 * - 'failure_retry_day',
642 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
643 * metadata is not defined in the xml for the field it will cause an error.
645 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
646 * form (UpdateSubscription).
650 public function getEditableRecurringScheduleFields() {
651 if ($this->supports('changeSubscriptionAmount')) {
658 * Get the help text to present on the recurring update page.
660 * This should reflect what can or cannot be edited.
664 public function getRecurringScheduleUpdateHelpText() {
665 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
666 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.');
668 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.');
672 * Get the metadata for all required fields.
676 protected function getMandatoryFields() {
677 $mandatoryFields = [];
678 foreach ($this->getAllFields() as $field_name => $field_spec) {
679 if (!empty($field_spec['is_required'])) {
680 $mandatoryFields[$field_name] = $field_spec;
683 return $mandatoryFields;
687 * Get the metadata of all the fields configured for this processor.
691 protected function getAllFields() {
692 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
693 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
694 return array_merge($paymentFields, $billingFields);
698 * Get array of fields that should be displayed on the payment form for credit cards.
702 protected function getCreditCardFormFields() {
705 'credit_card_number',
707 'credit_card_exp_date',
712 * Get array of fields that should be displayed on the payment form for direct debits.
716 protected function getDirectDebitFormFields() {
719 'bank_account_number',
720 'bank_identification_number',
726 * Return an array of all the details about the fields potentially required for payment fields.
728 * Only those determined by getPaymentFormFields will actually be assigned to the form
733 public function getPaymentFormFieldsMetadata() {
734 //@todo convert credit card type into an option value
735 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::creditCard();
736 $isCVVRequired = Civi
::settings()->get('cvv_backoffice_required');
737 if (!$this->isBackOffice()) {
738 $isCVVRequired = TRUE;
741 'credit_card_number' => [
742 'htmlType' => 'text',
743 'name' => 'credit_card_number',
744 'title' => ts('Card Number'),
748 'autocomplete' => 'off',
749 'class' => 'creditcard',
751 'is_required' => TRUE,
752 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
755 'htmlType' => 'text',
757 'title' => ts('Security Code'),
761 'autocomplete' => 'off',
763 'is_required' => $isCVVRequired,
766 '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.'),
767 'rule_name' => 'integer',
768 'rule_parameters' => NULL,
772 'credit_card_exp_date' => [
773 'htmlType' => 'date',
774 'name' => 'credit_card_exp_date',
775 'title' => ts('Expiration Date'),
776 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
777 'is_required' => TRUE,
780 'rule_message' => ts('Card expiration date cannot be a past date.'),
781 'rule_name' => 'currentDate',
782 'rule_parameters' => TRUE,
785 'extra' => ['class' => 'crm-form-select'],
787 'credit_card_type' => [
788 'htmlType' => 'select',
789 'name' => 'credit_card_type',
790 'title' => ts('Card Type'),
791 'attributes' => $creditCardType,
792 'is_required' => FALSE,
794 'account_holder' => [
795 'htmlType' => 'text',
796 'name' => 'account_holder',
797 'title' => ts('Account Holder'),
801 'autocomplete' => 'on',
803 'is_required' => TRUE,
805 //e.g. IBAN can have maxlength of 34 digits
806 'bank_account_number' => [
807 'htmlType' => 'text',
808 'name' => 'bank_account_number',
809 'title' => ts('Bank Account Number'),
813 'autocomplete' => 'off',
817 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
818 'rule_name' => 'nopunctuation',
819 'rule_parameters' => NULL,
822 'is_required' => TRUE,
824 //e.g. SWIFT-BIC can have maxlength of 11 digits
825 'bank_identification_number' => [
826 'htmlType' => 'text',
827 'name' => 'bank_identification_number',
828 'title' => ts('Bank Identification Number'),
832 'autocomplete' => 'off',
834 'is_required' => TRUE,
837 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
838 'rule_name' => 'nopunctuation',
839 'rule_parameters' => NULL,
844 'htmlType' => 'text',
845 'name' => 'bank_name',
846 'title' => ts('Bank Name'),
850 'autocomplete' => 'off',
852 'is_required' => TRUE,
856 'htmlType' => 'text',
857 'name' => 'check_number',
858 'title' => ts('Check Number'),
859 'is_required' => FALSE,
860 'attributes' => NULL,
862 'pan_truncation' => [
863 'htmlType' => 'text',
864 'name' => 'pan_truncation',
865 'title' => ts('Last 4 digits of the card'),
866 'is_required' => FALSE,
871 'autocomplete' => 'off',
875 'rule_message' => ts('Please enter valid last 4 digit card number.'),
876 'rule_name' => 'numeric',
877 'rule_parameters' => NULL,
882 'htmlType' => 'hidden',
883 'name' => 'payment_token',
884 'title' => ts('Authorization token'),
885 'is_required' => FALSE,
888 'autocomplete' => 'off',
889 'id' => 'payment_token',
896 * Get billing fields required for this processor.
898 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
901 * @param int $billingLocationID
905 public function getBillingAddressFields($billingLocationID = NULL) {
906 if (!$billingLocationID) {
907 // Note that although the billing id is passed around the forms the idea that it would be anything other than
908 // the result of the function below doesn't seem to have eventuated.
909 // So taking this as a param is possibly something to be removed in favour of the standard default.
910 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
912 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
916 'first_name' => 'billing_first_name',
917 'middle_name' => 'billing_middle_name',
918 'last_name' => 'billing_last_name',
919 'street_address' => "billing_street_address-{$billingLocationID}",
920 'city' => "billing_city-{$billingLocationID}",
921 'country' => "billing_country_id-{$billingLocationID}",
922 'state_province' => "billing_state_province_id-{$billingLocationID}",
923 'postal_code' => "billing_postal_code-{$billingLocationID}",
928 * Get form metadata for billing address fields.
930 * @param int $billingLocationID
933 * Array of metadata for address fields.
935 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
936 if (!$billingLocationID) {
937 // Note that although the billing id is passed around the forms the idea that it would be anything other than
938 // the result of the function below doesn't seem to have eventuated.
939 // So taking this as a param is possibly something to be removed in favour of the standard default.
940 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
943 $metadata['billing_first_name'] = [
944 'htmlType' => 'text',
945 'name' => 'billing_first_name',
946 'title' => ts('Billing First Name'),
951 'autocomplete' => 'off',
953 'is_required' => TRUE,
956 $metadata['billing_middle_name'] = [
957 'htmlType' => 'text',
958 'name' => 'billing_middle_name',
959 'title' => ts('Billing Middle Name'),
964 'autocomplete' => 'off',
966 'is_required' => FALSE,
969 $metadata['billing_last_name'] = [
970 'htmlType' => 'text',
971 'name' => 'billing_last_name',
972 'title' => ts('Billing Last Name'),
977 'autocomplete' => 'off',
979 'is_required' => TRUE,
982 $metadata["billing_street_address-{$billingLocationID}"] = [
983 'htmlType' => 'text',
984 'name' => "billing_street_address-{$billingLocationID}",
985 'title' => ts('Street Address'),
990 'autocomplete' => 'off',
992 'is_required' => TRUE,
995 $metadata["billing_city-{$billingLocationID}"] = [
996 'htmlType' => 'text',
997 'name' => "billing_city-{$billingLocationID}",
998 'title' => ts('City'),
1003 'autocomplete' => 'off',
1005 'is_required' => TRUE,
1008 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1009 'htmlType' => 'chainSelect',
1010 'title' => ts('State/Province'),
1011 'name' => "billing_state_province_id-{$billingLocationID}",
1013 'is_required' => TRUE,
1016 $metadata["billing_postal_code-{$billingLocationID}"] = [
1017 'htmlType' => 'text',
1018 'name' => "billing_postal_code-{$billingLocationID}",
1019 'title' => ts('Postal Code'),
1024 'autocomplete' => 'off',
1026 'is_required' => TRUE,
1029 $metadata["billing_country_id-{$billingLocationID}"] = [
1030 'htmlType' => 'select',
1031 'name' => "billing_country_id-{$billingLocationID}",
1032 'title' => ts('Country'),
1035 '' => ts('- select -'),
1036 ] + CRM_Core_PseudoConstant
::country(),
1037 'is_required' => TRUE,
1043 * Get base url dependent on component.
1045 * (or preferably set it using the setter function).
1049 protected function getBaseReturnUrl() {
1050 if ($this->baseReturnUrl
) {
1051 return $this->baseReturnUrl
;
1053 if ($this->_component
== 'event') {
1054 $baseURL = 'civicrm/event/register';
1057 $baseURL = 'civicrm/contribute/transact';
1063 * Get the currency for the transaction.
1065 * Handle any inconsistency about how it is passed in here.
1071 protected function getCurrency($params) {
1072 return CRM_Utils_Array
::value('currencyID', $params, CRM_Utils_Array
::value('currency', $params));
1076 * Get the currency for the transaction.
1078 * Handle any inconsistency about how it is passed in here.
1084 protected function getAmount($params) {
1085 return CRM_Utils_Money
::format($params['amount'], NULL, NULL, TRUE);
1089 * Get url to return to after cancelled or failed transaction.
1091 * @param string $qfKey
1092 * @param int $participantID
1094 * @return string cancel url
1096 public function getCancelUrl($qfKey, $participantID) {
1097 if (isset($this->cancelUrl
)) {
1098 return $this->cancelUrl
;
1101 if ($this->_component
== 'event') {
1102 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1105 'participantId' => $participantID,
1111 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1112 '_qf_Main_display' => 1,
1121 * Get URL to return the browser to on success.
1127 protected function getReturnSuccessUrl($qfKey) {
1128 if (isset($this->successUrl
)) {
1129 return $this->successUrl
;
1132 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1133 '_qf_ThankYou_display' => 1,
1141 * Get URL to return the browser to on failure.
1143 * @param string $key
1144 * @param int $participantID
1145 * @param int $eventID
1148 * URL for a failing transactor to be redirected to.
1150 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1151 if (isset($this->cancelUrl
)) {
1152 return $this->cancelUrl
;
1155 $test = $this->_is_test ?
'&action=preview' : '';
1156 if ($this->_component
== "event") {
1157 return CRM_Utils_System
::url('civicrm/event/register',
1158 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1163 return CRM_Utils_System
::url('civicrm/contribute/transact',
1164 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1171 * Get URl for when the back button is pressed.
1175 * @return string url
1177 protected function getGoBackUrl($qfKey) {
1178 return CRM_Utils_System
::url($this->getBaseReturnUrl(), [
1179 '_qf_Confirm_display' => 'true',
1187 * Get the notify (aka ipn, web hook or silent post) url.
1189 * If there is no '.' in it we assume that we are dealing with localhost or
1190 * similar and it is unreachable from the web & hence invalid.
1193 * URL to notify outcome of transaction.
1195 protected function getNotifyUrl() {
1196 $url = CRM_Utils_System
::url(
1197 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1204 return (stristr($url, '.')) ?
$url : '';
1208 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1210 * Does a server to server payment transaction.
1212 * @param array $params
1213 * Assoc array of input parameters for this transaction.
1216 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1218 protected function doDirectPayment(&$params) {
1223 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1224 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1226 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1227 * the transaction & in fact doTransferCheckout would not traditionally come back.
1228 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1230 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1231 * In some cases the IPN will set the payment to "Completed" some time later.
1233 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1234 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1235 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1237 * @param array $params
1239 * @param string $component
1242 * Result array (containing at least the key payment_status_id)
1244 * @throws \Civi\Payment\Exception\PaymentProcessorException
1246 public function doPayment(&$params, $component = 'contribute') {
1247 $this->_component
= $component;
1248 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
1250 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1251 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1252 // have an example of that at the mome.
1253 if ($params['amount'] == 0) {
1254 $result['payment_status_id'] = array_search('Completed', $statuses);
1258 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1259 $result = $this->doTransferCheckout($params, $component);
1260 if (is_array($result) && !isset($result['payment_status_id'])) {
1261 $result['payment_status_id'] = array_search('Pending', $statuses);
1265 $result = $this->doDirectPayment($params, $component);
1266 if (is_array($result) && !isset($result['payment_status_id'])) {
1267 if (!empty($params['is_recur'])) {
1268 // See comment block.
1269 $result['payment_status_id'] = array_search('Pending', $statuses);
1272 $result['payment_status_id'] = array_search('Completed', $statuses);
1276 if (is_a($result, 'CRM_Core_Error')) {
1277 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1285 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1287 * @param array $params
1289 * @throws \Civi\Payment\Exception\PaymentProcessorException
1291 public function doRefund(&$params) {}
1294 * Query payment processor for details about a transaction.
1296 * @param array $params
1297 * Array of parameters containing one of:
1298 * - trxn_id Id of an individual transaction.
1299 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1302 * Extra parameters retrieved.
1303 * Any parameters retrievable through this should be documented in the function comments at
1304 * CRM_Core_Payment::doQuery. Currently:
1305 * - fee_amount Amount of fee paid
1307 public function doQuery($params) {
1312 * This function checks to see if we have the right config values.
1315 * the error message if any
1317 abstract protected function checkConfig();
1320 * Redirect for paypal.
1322 * @todo move to paypal class or remove
1324 * @param $paymentProcessor
1328 public static function paypalRedirect(&$paymentProcessor) {
1329 if (!$paymentProcessor) {
1333 if (isset($_GET['payment_date']) &&
1334 isset($_GET['merchant_return_link']) &&
1335 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1336 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1345 * Handle incoming payment notification.
1347 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1349 * @todo move to0 \Civi\Payment\System factory method
1350 * Page callback for civicrm/payment/ipn
1352 public static function handleIPN() {
1354 self
::handlePaymentMethod(
1355 'PaymentNotification',
1357 'processor_name' => CRM_Utils_Request
::retrieveValue('processor_name', 'String'),
1358 'processor_id' => CRM_Utils_Request
::retrieveValue('processor_id', 'Integer'),
1359 'mode' => CRM_Utils_Request
::retrieveValue('mode', 'Alphanumeric'),
1363 catch (CRM_Core_Exception
$e) {
1364 Civi
::log()->error('ipn_payment_callback_exception', [
1366 'backtrace' => CRM_Core_Error
::formatBacktrace(debug_backtrace()),
1370 CRM_Utils_System
::civiExit();
1374 * Payment callback handler.
1376 * The processor_name or processor_id is passed in.
1377 * Note that processor_id is more reliable as one site may have more than one instance of a
1378 * processor & ideally the processor will be validating the results
1379 * Load requested payment processor and call that processor's handle<$method> method
1381 * @todo move to \Civi\Payment\System factory method
1383 * @param string $method
1384 * 'PaymentNotification' or 'PaymentCron'
1385 * @param array $params
1387 * @throws \CRM_Core_Exception
1388 * @throws \Exception
1390 public static function handlePaymentMethod($method, $params = []) {
1391 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1392 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1393 $lastParam = array_pop($q);
1394 if (is_numeric($lastParam)) {
1395 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1398 self
::logPaymentNotification($params);
1399 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1403 self
::logPaymentNotification($params);
1405 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1406 FROM civicrm_payment_processor_type ppt
1407 INNER JOIN civicrm_payment_processor pp
1408 ON pp.payment_processor_type_id = ppt.id
1411 if (isset($params['processor_id'])) {
1412 $sql .= " WHERE pp.id = %2";
1413 $args[2] = [$params['processor_id'], 'Integer'];
1414 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1417 // This is called when processor_name is passed - passing processor_id instead is recommended.
1418 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1420 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1423 $args[2] = [$params['processor_name'], 'String'];
1424 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1427 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1429 // Check whether we found anything at all.
1431 throw new CRM_Core_Exception($notFound);
1434 $method = 'handle' . $method;
1435 $extension_instance_found = FALSE;
1437 // In all likelihood, we'll just end up with the one instance returned here. But it's
1438 // possible we may get more. Hence, iterate through all instances ..
1440 while ($dao->fetch()) {
1441 // Check pp is extension - is this still required - surely the singleton below handles it.
1442 $ext = CRM_Extension_System
::singleton()->getMapper();
1443 if ($ext->isExtensionKey($dao->class_name
)) {
1444 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1445 require_once $ext->classToPath($paymentClass);
1448 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1450 // Should never be empty - we already established this processor_id exists and is active.
1451 if (empty($processorInstance)) {
1455 // Does PP implement this method, and can we call it?
1456 if (!method_exists($processorInstance, $method) ||
1457 !is_callable([$processorInstance, $method])
1459 // on the off chance there is a double implementation of this processor we should keep looking for another
1460 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1464 // Everything, it seems, is ok - execute pp callback handler
1465 $processorInstance->$method();
1466 $extension_instance_found = TRUE;
1469 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1470 $IPNParams = array_merge($_GET, $_REQUEST);
1471 CRM_Utils_Hook
::postIPNProcess($IPNParams);
1472 if (!$extension_instance_found) {
1473 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1474 "%2 method is unsupported in legacy payment processors.";
1475 throw new CRM_Core_Exception(ts($message, [
1476 1 => $params['processor_name'],
1483 * Check whether a method is present ( & supported ) by the payment processor object.
1485 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1487 * @param string $method
1488 * Method to check for.
1492 public function isSupported($method) {
1493 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1497 * Some processors replace the form submit button with their own.
1499 * Returning false here will leave the button off front end forms.
1501 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1503 public function isSuppressSubmitButtons() {
1508 * Checks to see if invoice_id already exists in db.
1510 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1511 * it is better to standardise to being here.
1513 * @param int $invoiceId The ID to check.
1515 * @param null $contributionID
1516 * If a contribution exists pass in the contribution ID.
1519 * True if invoice ID otherwise exists, else false
1521 protected function checkDupe($invoiceId, $contributionID = NULL) {
1522 $contribution = new CRM_Contribute_DAO_Contribution();
1523 $contribution->invoice_id
= $invoiceId;
1524 if ($contributionID) {
1525 $contribution->whereAdd("id <> $contributionID");
1527 return $contribution->find();
1531 * Get url for users to manage this recurring contribution for this processor.
1533 * @param int $entityID
1534 * @param null $entity
1535 * @param string $action
1539 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1543 if (!$this->supports('cancelRecurring')) {
1546 $url = 'civicrm/contribute/unsubscribe';
1550 //in notify mode don't return the update billing url
1551 if (!$this->supports('updateSubscriptionBillingInfo')) {
1554 $url = 'civicrm/contribute/updatebilling';
1558 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1561 $url = 'civicrm/contribute/updaterecur';
1565 $userId = CRM_Core_Session
::singleton()->get('userID');
1567 $checksumValue = '';
1570 // Find related Contact
1574 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1578 case 'contribution':
1579 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1580 $entityArg = 'coid';
1585 SELECT DISTINCT con.contact_id
1586 FROM civicrm_contribution_recur rec
1587 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1589 $contactID = CRM_Core_DAO
::singleValueQuery($sql, [
1595 $entityArg = 'crid';
1600 // Add entity arguments
1601 if ($entityArg != '') {
1602 // Add checksum argument
1603 if ($contactID != 0 && $userId != $contactID) {
1604 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1606 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1610 if ($this->supports('accountLoginURL')) {
1611 return $this->accountLoginURL();
1615 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1619 * Get description of payment to pass to processor.
1621 * This is often what people see in the interface so we want to get
1622 * as much unique information in as possible within the field length (& presumably the early part of the field)
1624 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1625 * having field names to clarify
1627 * @param array $params
1628 * @param int $length
1632 protected function getPaymentDescription($params, $length = 24) {
1637 'billing_first_name',
1638 'billing_last_name',
1641 if (isset($params['description'])) {
1642 $uninformativeStrings = [
1643 ts('Online Event Registration: '),
1644 ts('Online Contribution: '),
1646 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1648 foreach ($parts as $part) {
1649 if ((!empty($params[$part]))) {
1650 $validParts[] = $params[$part];
1653 return substr(implode('-', $validParts), 0, $length);
1657 * Checks if backoffice recurring edit is allowed
1661 public function supportsEditRecurringContribution() {
1666 * Does this processor support changing the amount for recurring contributions through code.
1668 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1669 * that will be updated at the payment processor.
1673 protected function supportsChangeSubscriptionAmount() {
1674 return method_exists(CRM_Utils_System
::getClassName($this), 'changeSubscriptionAmount');
1678 * Checks if payment processor supports recurring contributions
1682 public function supportsRecurring() {
1683 if (!empty($this->_paymentProcessor
['is_recur'])) {
1690 * Checks if payment processor supports an account login URL
1691 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1692 * TODO: It is implemented by AuthorizeNET, any others?
1696 protected function supportsAccountLoginURL() {
1697 return method_exists(CRM_Utils_System
::getClassName($this), 'accountLoginURL');
1701 * Should a receipt be sent out for a pending payment.
1703 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1705 public function isSendReceiptForPending() {