3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 use Civi\Payment\System
;
29 use Civi\Payment\Exception\PaymentProcessorException
;
32 * Class CRM_Core_Payment.
34 * This class is the main class for the payment processor subsystem.
36 * It is the parent class for payment processors. It also holds some IPN related functions
37 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
39 abstract class CRM_Core_Payment
{
42 * Component - ie. event or contribute.
44 * This is used for setting return urls.
48 protected $_component;
51 * How are we getting billing information.
53 * We are trying to completely deprecate these parameters.
55 * FORM - we collect it on the same page
56 * BUTTON - the processor collects it and sends it back to us via some protocol
59 BILLING_MODE_FORM
= 1,
60 BILLING_MODE_BUTTON
= 2,
61 BILLING_MODE_NOTIFY
= 4;
64 * Which payment type(s) are we using?
69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
72 PAYMENT_TYPE_CREDIT_CARD
= 1,
73 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
76 * Subscription / Recurring payment Status
80 RECURRING_PAYMENT_START
= 'START',
81 RECURRING_PAYMENT_END
= 'END';
83 protected $_paymentProcessor;
86 * Base url of the calling form (offsite processors).
90 protected $baseReturnUrl;
93 * Return url upon success (offsite processors).
97 protected $successUrl;
100 * Return url upon failure (offsite processors).
104 protected $cancelUrl;
107 * The profile configured to show on the billing form.
109 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
110 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
111 * requirements with the configured requirements.
113 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
116 * Note this change would probably include converting 'billing' to a reserved profile.
120 protected $billingProfile;
123 * Payment instrument ID.
125 * This is normally retrieved from the payment_processor table.
129 protected $paymentInstrumentID;
132 * Is this a back office transaction.
136 protected $backOffice = FALSE;
141 public function isBackOffice() {
142 return $this->backOffice
;
146 * Set back office property.
148 * @param bool $isBackOffice
150 public function setBackOffice($isBackOffice) {
151 $this->backOffice
= $isBackOffice;
155 * Get payment instrument id.
159 public function getPaymentInstrumentID() {
160 return $this->paymentInstrumentID ?
$this->paymentInstrumentID
: $this->_paymentProcessor
['payment_instrument_id'];
164 * Set payment Instrument id.
166 * By default we actually ignore the form value. The manual processor takes it more seriously.
168 * @param int $paymentInstrumentID
170 public function setPaymentInstrumentID($paymentInstrumentID) {
171 $this->paymentInstrumentID
= $this->_paymentProcessor
['payment_instrument_id'];
175 * Set base return path (offsite processors).
177 * This is only useful with an internal civicrm form.
180 * Internal civicrm path.
182 public function setBaseReturnUrl($url) {
183 $this->baseReturnUrl
= $url;
187 * Set success return URL (offsite processors).
189 * This overrides $baseReturnUrl
192 * Full url of site to return browser to upon success.
194 public function setSuccessUrl($url) {
195 $this->successUrl
= $url;
199 * Set cancel return URL (offsite processors).
201 * This overrides $baseReturnUrl
204 * Full url of site to return browser to upon failure.
206 public function setCancelUrl($url) {
207 $this->cancelUrl
= $url;
211 * Set the configured payment profile.
213 * @param int|string $value
215 public function setBillingProfile($value) {
216 $this->billingProfile
= $value;
220 * Opportunity for the payment processor to override the entire form build.
222 * @param CRM_Core_Form $form
225 * Should form building stop at this point?
227 public function buildForm(&$form) {
232 * Log payment notification message to forensic system log.
234 * @todo move to factory class \Civi\Payment\System (or similar)
236 * @param array $params
240 public static function logPaymentNotification($params) {
241 $message = 'payment_notification ';
242 if (!empty($params['processor_name'])) {
243 $message .= 'processor_name=' . $params['processor_name'];
245 if (!empty($params['processor_id'])) {
246 $message .= 'processor_id=' . $params['processor_id'];
249 $log = new CRM_Utils_SystemLogger();
250 $log->alert($message, $_REQUEST);
254 * Check if capability is supported.
256 * Capabilities have a one to one relationship with capability-related functions on this class.
258 * Payment processor classes should over-ride the capability-specific function rather than this one.
260 * @param string $capability
261 * E.g BackOffice, LiveMode, FutureRecurStartDate.
265 public function supports($capability) {
266 $function = 'supports' . ucfirst($capability);
267 if (method_exists($this, $function)) {
268 return $this->$function();
274 * Are back office payments supported.
276 * e.g paypal standard won't permit you to enter a credit card associated
277 * with someone else's login.
278 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
279 * reach a 'stable' point we disable.
283 protected function supportsBackOffice() {
284 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
293 * Can more than one transaction be processed at once?
295 * In general processors that process payment by server to server communication support this while others do not.
297 * In future we are likely to hit an issue where this depends on whether a token already exists.
301 protected function supportsMultipleConcurrentPayments() {
302 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
311 * Are live payments supported - e.g dummy doesn't support this.
315 protected function supportsLiveMode() {
320 * Are test payments supported.
324 protected function supportsTestMode() {
329 * Should the first payment date be configurable when setting up back office recurring payments.
331 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
335 protected function supportsFutureRecurStartDate() {
340 * Does this processor support cancelling recurring contributions through code.
342 * If the processor returns true it must be possible to take action from within CiviCRM
343 * that will result in no further payments being processed. In the case of token processors (e.g
344 * IATS, eWay) updating the contribution_recur table is probably sufficient.
348 protected function supportsCancelRecurring() {
349 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
353 * Does this processor support pre-approval.
355 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
357 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
358 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
359 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
363 protected function supportsPreApproval() {
368 * Can recurring contributions be set against pledges.
370 * In practice all processors that use the baseIPN function to finish transactions or
371 * call the completetransaction api support this by looking up previous contributions in the
372 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
373 * adding the new payment to the pledge.
375 * However, only enabling for processors it has been tested against.
379 protected function supportsRecurContributionsForPledges() {
384 * Function to action pre-approval if supported
386 * @param array $params
387 * Parameters from the form
389 * This function returns an array which should contain
390 * - pre_approval_parameters (this will be stored on the calling form & available later)
391 * - redirect_url (if set the browser will be redirected to this.
393 public function doPreApproval(&$params) {}
396 * Get any details that may be available to the payment processor due to an approval process having happened.
398 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
401 * @param array $storedDetails
405 public function getPreApprovalDetails($storedDetails) {
410 * Default payment instrument validation.
412 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
413 * Not a static function, because I need to check for payment_type.
415 * @param array $values
416 * @param array $errors
418 public function validatePaymentInstrument($values, &$errors) {
419 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
420 if ($this->_paymentProcessor
['payment_type'] == 1) {
421 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
426 * Getter for the payment processor.
428 * The payment processor array is based on the civicrm_payment_processor table entry.
431 * Payment processor array.
433 public function getPaymentProcessor() {
434 return $this->_paymentProcessor
;
438 * Setter for the payment processor.
440 * @param array $processor
442 public function setPaymentProcessor($processor) {
443 $this->_paymentProcessor
= $processor;
447 * Setter for the payment form that wants to use the processor.
451 * @param CRM_Core_Form $paymentForm
453 public function setForm(&$paymentForm) {
454 $this->_paymentForm
= $paymentForm;
458 * Getter for payment form that is using the processor.
460 * @return CRM_Core_Form
463 public function getForm() {
464 return $this->_paymentForm
;
468 * Get help text information (help, description, etc.) about this payment,
469 * to display to the user.
471 * @param string $context
472 * Context of the text.
473 * Only explicitly supported contexts are handled without error.
474 * Currently supported:
475 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
477 * @param array $params
478 * Parameters for the field, context specific.
482 public function getText($context, $params) {
483 // I have deliberately added a noisy fail here.
484 // The function is intended to be extendable, but not by changes
485 // not documented clearly above.
487 case 'contributionPageRecurringHelp':
488 // require exactly two parameters
489 if (array_keys($params) == array('is_recur_installments', 'is_email_receipt')) {
490 $gotText = ts('Your recurring contribution will be processed automatically.');
491 if ($params['is_recur_installments']) {
492 $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.');
494 if ($params['is_email_receipt']) {
495 $gotText .= ts(' You will receive an email receipt for each recurring contribution.');
504 * Getter for accessing member vars.
506 * @todo believe this is unused
508 * @param string $name
512 public function getVar($name) {
513 return isset($this->$name) ?
$this->$name : NULL;
517 * Get name for the payment information type.
518 * @todo - use option group + name field (like Omnipay does)
521 public function getPaymentTypeName() {
522 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
526 * Get label for the payment information type.
527 * @todo - use option group + labels (like Omnipay does)
530 public function getPaymentTypeLabel() {
531 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
535 * Get array of fields that should be displayed on the payment form.
538 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
540 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
545 * Array of payment fields appropriate to the payment processor.
547 * @throws CiviCRM_API3_Exception
549 public function getPaymentFormFields() {
550 if ($this->_paymentProcessor
['billing_mode'] == 4) {
553 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
557 * Get an array of the fields that can be edited on the recurring contribution.
559 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
560 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
561 * can be updated from the contribution recur edit screen.
563 * The fields are likely to be a subset of these
566 * - 'frequency_interval',
567 * - 'frequency_unit',
569 * - 'next_sched_contribution_date',
571 * - 'failure_retry_day',
573 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
574 * metadata is not defined in the xml for the field it will cause an error.
576 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
577 * form (UpdateSubscription).
581 public function getEditableRecurringScheduleFields() {
582 if (method_exists($this, 'changeSubscriptionAmount')) {
583 return array('amount');
588 * Get the help text to present on the recurring update page.
590 * This should reflect what can or cannot be edited.
594 public function getRecurringScheduleUpdateHelpText() {
595 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
596 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.');
598 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.');
602 * Get the metadata for all required fields.
606 protected function getMandatoryFields() {
607 $mandatoryFields = array();
608 foreach ($this->getAllFields() as $field_name => $field_spec) {
609 if (!empty($field_spec['is_required'])) {
610 $mandatoryFields[$field_name] = $field_spec;
613 return $mandatoryFields;
617 * Get the metadata of all the fields configured for this processor.
621 protected function getAllFields() {
622 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
623 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
624 return array_merge($paymentFields, $billingFields);
627 * Get array of fields that should be displayed on the payment form for credit cards.
631 protected function getCreditCardFormFields() {
634 'credit_card_number',
636 'credit_card_exp_date',
641 * Get array of fields that should be displayed on the payment form for direct debits.
645 protected function getDirectDebitFormFields() {
648 'bank_account_number',
649 'bank_identification_number',
655 * Return an array of all the details about the fields potentially required for payment fields.
657 * Only those determined by getPaymentFormFields will actually be assigned to the form
662 public function getPaymentFormFieldsMetadata() {
663 //@todo convert credit card type into an option value
664 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
666 'credit_card_number' => array(
667 'htmlType' => 'text',
668 'name' => 'credit_card_number',
669 'title' => ts('Card Number'),
671 'attributes' => array(
674 'autocomplete' => 'off',
675 'class' => 'creditcard',
677 'is_required' => TRUE,
680 'htmlType' => 'text',
682 'title' => ts('Security Code'),
684 'attributes' => array(
687 'autocomplete' => 'off',
689 'is_required' => Civi
::settings()->get('cvv_backoffice_required'),
692 '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.'),
693 'rule_name' => 'integer',
694 'rule_parameters' => NULL,
698 'credit_card_exp_date' => array(
699 'htmlType' => 'date',
700 'name' => 'credit_card_exp_date',
701 'title' => ts('Expiration Date'),
703 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
704 'is_required' => TRUE,
707 'rule_message' => ts('Card expiration date cannot be a past date.'),
708 'rule_name' => 'currentDate',
709 'rule_parameters' => TRUE,
713 'credit_card_type' => array(
714 'htmlType' => 'select',
715 'name' => 'credit_card_type',
716 'title' => ts('Card Type'),
718 'attributes' => $creditCardType,
719 'is_required' => FALSE,
721 'account_holder' => array(
722 'htmlType' => 'text',
723 'name' => 'account_holder',
724 'title' => ts('Account Holder'),
726 'attributes' => array(
729 'autocomplete' => 'on',
731 'is_required' => TRUE,
733 //e.g. IBAN can have maxlength of 34 digits
734 'bank_account_number' => array(
735 'htmlType' => 'text',
736 'name' => 'bank_account_number',
737 'title' => ts('Bank Account Number'),
739 'attributes' => array(
742 'autocomplete' => 'off',
746 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
747 'rule_name' => 'nopunctuation',
748 'rule_parameters' => NULL,
751 'is_required' => TRUE,
753 //e.g. SWIFT-BIC can have maxlength of 11 digits
754 'bank_identification_number' => array(
755 'htmlType' => 'text',
756 'name' => 'bank_identification_number',
757 'title' => ts('Bank Identification Number'),
759 'attributes' => array(
762 'autocomplete' => 'off',
764 'is_required' => TRUE,
767 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
768 'rule_name' => 'nopunctuation',
769 'rule_parameters' => NULL,
773 'bank_name' => array(
774 'htmlType' => 'text',
775 'name' => 'bank_name',
776 'title' => ts('Bank Name'),
778 'attributes' => array(
781 'autocomplete' => 'off',
783 'is_required' => TRUE,
786 'check_number' => array(
787 'htmlType' => 'text',
788 'name' => 'check_number',
789 'title' => ts('Check Number'),
790 'is_required' => FALSE,
792 'attributes' => NULL,
794 'pan_truncation' => array(
795 'htmlType' => 'text',
796 'name' => 'pan_truncation',
797 'title' => ts('Last 4 digits of the card'),
798 'is_required' => FALSE,
800 'attributes' => array(
804 'autocomplete' => 'off',
808 'rule_message' => ts('Please enter valid last 4 digit card number.'),
809 'rule_name' => 'numeric',
810 'rule_parameters' => NULL,
818 * Get billing fields required for this processor.
820 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
823 * @param int $billingLocationID
827 public function getBillingAddressFields($billingLocationID = NULL) {
828 if (!$billingLocationID) {
829 // Note that although the billing id is passed around the forms the idea that it would be anything other than
830 // the result of the function below doesn't seem to have eventuated.
831 // So taking this as a param is possibly something to be removed in favour of the standard default.
832 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
834 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
838 'first_name' => 'billing_first_name',
839 'middle_name' => 'billing_middle_name',
840 'last_name' => 'billing_last_name',
841 'street_address' => "billing_street_address-{$billingLocationID}",
842 'city' => "billing_city-{$billingLocationID}",
843 'country' => "billing_country_id-{$billingLocationID}",
844 'state_province' => "billing_state_province_id-{$billingLocationID}",
845 'postal_code' => "billing_postal_code-{$billingLocationID}",
850 * Get form metadata for billing address fields.
852 * @param int $billingLocationID
855 * Array of metadata for address fields.
857 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
858 if (!$billingLocationID) {
859 // Note that although the billing id is passed around the forms the idea that it would be anything other than
860 // the result of the function below doesn't seem to have eventuated.
861 // So taking this as a param is possibly something to be removed in favour of the standard default.
862 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
865 $metadata['billing_first_name'] = array(
866 'htmlType' => 'text',
867 'name' => 'billing_first_name',
868 'title' => ts('Billing First Name'),
870 'attributes' => array(
873 'autocomplete' => 'off',
875 'is_required' => TRUE,
878 $metadata['billing_middle_name'] = array(
879 'htmlType' => 'text',
880 'name' => 'billing_middle_name',
881 'title' => ts('Billing Middle Name'),
883 'attributes' => array(
886 'autocomplete' => 'off',
888 'is_required' => FALSE,
891 $metadata['billing_last_name'] = array(
892 'htmlType' => 'text',
893 'name' => 'billing_last_name',
894 'title' => ts('Billing Last Name'),
896 'attributes' => array(
899 'autocomplete' => 'off',
901 'is_required' => TRUE,
904 $metadata["billing_street_address-{$billingLocationID}"] = array(
905 'htmlType' => 'text',
906 'name' => "billing_street_address-{$billingLocationID}",
907 'title' => ts('Street Address'),
909 'attributes' => array(
912 'autocomplete' => 'off',
914 'is_required' => TRUE,
917 $metadata["billing_city-{$billingLocationID}"] = array(
918 'htmlType' => 'text',
919 'name' => "billing_city-{$billingLocationID}",
920 'title' => ts('City'),
922 'attributes' => array(
925 'autocomplete' => 'off',
927 'is_required' => TRUE,
930 $metadata["billing_state_province_id-{$billingLocationID}"] = array(
931 'htmlType' => 'chainSelect',
932 'title' => ts('State/Province'),
933 'name' => "billing_state_province_id-{$billingLocationID}",
935 'is_required' => TRUE,
938 $metadata["billing_postal_code-{$billingLocationID}"] = array(
939 'htmlType' => 'text',
940 'name' => "billing_postal_code-{$billingLocationID}",
941 'title' => ts('Postal Code'),
943 'attributes' => array(
946 'autocomplete' => 'off',
948 'is_required' => TRUE,
951 $metadata["billing_country_id-{$billingLocationID}"] = array(
952 'htmlType' => 'select',
953 'name' => "billing_country_id-{$billingLocationID}",
954 'title' => ts('Country'),
956 'attributes' => array(
957 '' => ts('- select -'),
958 ) + CRM_Core_PseudoConstant
::country(),
959 'is_required' => TRUE,
965 * Get base url dependent on component.
967 * (or preferably set it using the setter function).
971 protected function getBaseReturnUrl() {
972 if ($this->baseReturnUrl
) {
973 return $this->baseReturnUrl
;
975 if ($this->_component
== 'event') {
976 $baseURL = 'civicrm/event/register';
979 $baseURL = 'civicrm/contribute/transact';
985 * Get url to return to after cancelled or failed transaction.
987 * @param string $qfKey
988 * @param int $participantID
990 * @return string cancel url
992 public function getCancelUrl($qfKey, $participantID) {
993 if (isset($this->cancelUrl
)) {
994 return $this->cancelUrl
;
997 if ($this->_component
== 'event') {
998 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
1001 'participantId' => $participantID,
1007 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
1008 '_qf_Main_display' => 1,
1017 * Get URL to return the browser to on success.
1023 protected function getReturnSuccessUrl($qfKey) {
1024 if (isset($this->successUrl
)) {
1025 return $this->successUrl
;
1028 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
1029 '_qf_ThankYou_display' => 1,
1037 * Get URL to return the browser to on failure.
1039 * @param string $key
1040 * @param int $participantID
1041 * @param int $eventID
1044 * URL for a failing transactor to be redirected to.
1046 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1047 if (isset($this->cancelUrl
)) {
1048 return $this->cancelUrl
;
1051 $test = $this->_is_test ?
'&action=preview' : '';
1052 if ($this->_component
== "event") {
1053 return CRM_Utils_System
::url('civicrm/event/register',
1054 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1059 return CRM_Utils_System
::url('civicrm/contribute/transact',
1060 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1067 * Get URl for when the back button is pressed.
1071 * @return string url
1073 protected function getGoBackUrl($qfKey) {
1074 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
1075 '_qf_Confirm_display' => 'true',
1083 * Get the notify (aka ipn, web hook or silent post) url.
1085 * If there is no '.' in it we assume that we are dealing with localhost or
1086 * similar and it is unreachable from the web & hence invalid.
1089 * URL to notify outcome of transaction.
1091 protected function getNotifyUrl() {
1092 $url = CRM_Utils_System
::url(
1093 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1099 return (stristr($url, '.')) ?
$url : '';
1103 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1105 * Does a server to server payment transaction.
1107 * @param array $params
1108 * Assoc array of input parameters for this transaction.
1111 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1113 protected function doDirectPayment(&$params) {
1118 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
1120 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
1123 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
1124 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
1125 * doTransferCheckout would not traditionally come back.
1127 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
1130 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
1131 * return Error objects
1133 * @param array $params
1135 * @param string $component
1140 * @throws \Civi\Payment\Exception\PaymentProcessorException
1142 public function doPayment(&$params, $component = 'contribute') {
1143 $this->_component
= $component;
1144 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1146 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1147 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1148 // have an example of that at the mome.
1149 if ($params['amount'] == 0) {
1150 $result['payment_status_id'] = array_search('Completed', $statuses);
1154 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1155 $result = $this->doTransferCheckout($params, $component);
1156 if (is_array($result) && !isset($result['payment_status_id'])) {
1157 $result['payment_status_id'] = array_search('Pending', $statuses);
1161 $result = $this->doDirectPayment($params, $component);
1162 if (is_array($result) && !isset($result['payment_status_id'])) {
1163 if (!empty($params['is_recur'])) {
1164 // See comment block.
1165 $result['payment_status_id'] = array_search('Pending', $statuses);
1168 $result['payment_status_id'] = array_search('Completed', $statuses);
1172 if (is_a($result, 'CRM_Core_Error')) {
1173 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1179 * Query payment processor for details about a transaction.
1181 * @param array $params
1182 * Array of parameters containing one of:
1183 * - trxn_id Id of an individual transaction.
1184 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1187 * Extra parameters retrieved.
1188 * Any parameters retrievable through this should be documented in the function comments at
1189 * CRM_Core_Payment::doQuery. Currently:
1190 * - fee_amount Amount of fee paid
1192 public function doQuery($params) {
1197 * This function checks to see if we have the right config values.
1200 * the error message if any
1202 abstract protected function checkConfig();
1205 * Redirect for paypal.
1207 * @todo move to paypal class or remove
1209 * @param $paymentProcessor
1213 public static function paypalRedirect(&$paymentProcessor) {
1214 if (!$paymentProcessor) {
1218 if (isset($_GET['payment_date']) &&
1219 isset($_GET['merchant_return_link']) &&
1220 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1221 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1230 * Handle incoming payment notification.
1232 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1234 * @todo move to0 \Civi\Payment\System factory method
1235 * Page callback for civicrm/payment/ipn
1237 public static function handleIPN() {
1238 self
::handlePaymentMethod(
1239 'PaymentNotification',
1241 'processor_name' => @$_GET['processor_name'],
1242 'processor_id' => @$_GET['processor_id'],
1243 'mode' => @$_GET['mode'],
1246 CRM_Utils_System
::civiExit();
1250 * Payment callback handler.
1252 * The processor_name or processor_id is passed in.
1253 * Note that processor_id is more reliable as one site may have more than one instance of a
1254 * processor & ideally the processor will be validating the results
1255 * Load requested payment processor and call that processor's handle<$method> method
1257 * @todo move to \Civi\Payment\System factory method
1259 * @param string $method
1260 * 'PaymentNotification' or 'PaymentCron'
1261 * @param array $params
1263 * @throws \CRM_Core_Exception
1264 * @throws \Exception
1266 public static function handlePaymentMethod($method, $params = array()) {
1267 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1268 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1269 $lastParam = array_pop($q);
1270 if (is_numeric($lastParam)) {
1271 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1274 self
::logPaymentNotification($params);
1275 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1279 self
::logPaymentNotification($params);
1281 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1282 FROM civicrm_payment_processor_type ppt
1283 INNER JOIN civicrm_payment_processor pp
1284 ON pp.payment_processor_type_id = ppt.id
1287 if (isset($params['processor_id'])) {
1288 $sql .= " WHERE pp.id = %2";
1289 $args[2] = array($params['processor_id'], 'Integer');
1290 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
1293 // This is called when processor_name is passed - passing processor_id instead is recommended.
1294 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1296 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1299 $args[2] = array($params['processor_name'], 'String');
1300 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
1303 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1305 // Check whether we found anything at all.
1307 CRM_Core_Error
::fatal($notFound);
1310 $method = 'handle' . $method;
1311 $extension_instance_found = FALSE;
1313 // In all likelihood, we'll just end up with the one instance returned here. But it's
1314 // possible we may get more. Hence, iterate through all instances ..
1316 while ($dao->fetch()) {
1317 // Check pp is extension - is this still required - surely the singleton below handles it.
1318 $ext = CRM_Extension_System
::singleton()->getMapper();
1319 if ($ext->isExtensionKey($dao->class_name
)) {
1320 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1321 require_once $ext->classToPath($paymentClass);
1324 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1326 // Should never be empty - we already established this processor_id exists and is active.
1327 if (empty($processorInstance)) {
1331 // Does PP implement this method, and can we call it?
1332 if (!method_exists($processorInstance, $method) ||
1333 !is_callable(array($processorInstance, $method))
1335 // on the off chance there is a double implementation of this processor we should keep looking for another
1336 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1340 // Everything, it seems, is ok - execute pp callback handler
1341 $processorInstance->$method();
1342 $extension_instance_found = TRUE;
1345 if (!$extension_instance_found) {
1346 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1347 "%2 method is unsupported in legacy payment processors.";
1348 CRM_Core_Error
::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
1353 * Check whether a method is present ( & supported ) by the payment processor object.
1355 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1357 * @param string $method
1358 * Method to check for.
1362 public function isSupported($method) {
1363 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1367 * Some processors replace the form submit button with their own.
1369 * Returning false here will leave the button off front end forms.
1371 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1373 public function isSuppressSubmitButtons() {
1378 * Checks to see if invoice_id already exists in db.
1380 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1381 * it is better to standardise to being here.
1383 * @param int $invoiceId The ID to check.
1385 * @param null $contributionID
1386 * If a contribution exists pass in the contribution ID.
1389 * True if invoice ID otherwise exists, else false
1391 protected function checkDupe($invoiceId, $contributionID = NULL) {
1392 $contribution = new CRM_Contribute_DAO_Contribution();
1393 $contribution->invoice_id
= $invoiceId;
1394 if ($contributionID) {
1395 $contribution->whereAdd("id <> $contributionID");
1397 return $contribution->find();
1401 * Get url for users to manage this recurring contribution for this processor.
1403 * @param int $entityID
1404 * @param null $entity
1405 * @param string $action
1409 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1413 $url = 'civicrm/contribute/unsubscribe';
1417 //in notify mode don't return the update billing url
1418 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
1421 $url = 'civicrm/contribute/updatebilling';
1425 $url = 'civicrm/contribute/updaterecur';
1429 $userId = CRM_Core_Session
::singleton()->get('userID');
1431 $checksumValue = '';
1434 // Find related Contact
1438 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1442 case 'contribution':
1443 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1444 $entityArg = 'coid';
1449 SELECT con.contact_id
1450 FROM civicrm_contribution_recur rec
1451 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1454 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
1455 $entityArg = 'crid';
1460 // Add entity arguments
1461 if ($entityArg != '') {
1462 // Add checksum argument
1463 if ($contactID != 0 && $userId != $contactID) {
1464 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1466 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1470 if ($this->isSupported('accountLoginURL')) {
1471 return $this->accountLoginURL();
1475 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1479 * Get description of payment to pass to processor.
1481 * This is often what people see in the interface so we want to get
1482 * as much unique information in as possible within the field length (& presumably the early part of the field)
1484 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1485 * having field names to clarify
1487 * @param array $params
1488 * @param int $length
1492 protected function getPaymentDescription($params, $length = 24) {
1493 $parts = array('contactID', 'contributionID', 'description', 'billing_first_name', 'billing_last_name');
1494 $validParts = array();
1495 if (isset($params['description'])) {
1496 $uninformativeStrings = array(ts('Online Event Registration: '), ts('Online Contribution: '));
1497 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1499 foreach ($parts as $part) {
1500 if ((!empty($params[$part]))) {
1501 $validParts[] = $params[$part];
1504 return substr(implode('-', $validParts), 0, $length);
1508 * Checks if backoffice recurring edit is allowed
1512 public function supportsEditRecurringContribution() {
1517 * Should a receipt be sent out for a pending payment.
1519 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1521 public function isSendReceiptForPending() {