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 * Set base return path (offsite processors).
125 * This is only useful with an internal civicrm form.
128 * Internal civicrm path.
130 public function setBaseReturnUrl($url) {
131 $this->baseReturnUrl
= $url;
135 * Set success return URL (offsite processors).
137 * This overrides $baseReturnUrl
140 * Full url of site to return browser to upon success.
142 public function setSuccessUrl($url) {
143 $this->successUrl
= $url;
147 * Set cancel return URL (offsite processors).
149 * This overrides $baseReturnUrl
152 * Full url of site to return browser to upon failure.
154 public function setCancelUrl($url) {
155 $this->cancelUrl
= $url;
159 * Set the configured payment profile.
161 * @param int|string $value
163 public function setBillingProfile($value) {
164 $this->billingProfile
= $value;
168 * Opportunity for the payment processor to override the entire form build.
170 * @param CRM_Core_Form $form
173 * Should form building stop at this point?
175 public function buildForm(&$form) {
180 * Log payment notification message to forensic system log.
182 * @todo move to factory class \Civi\Payment\System (or similar)
184 * @param array $params
188 public static function logPaymentNotification($params) {
189 $message = 'payment_notification ';
190 if (!empty($params['processor_name'])) {
191 $message .= 'processor_name=' . $params['processor_name'];
193 if (!empty($params['processor_id'])) {
194 $message .= 'processor_id=' . $params['processor_id'];
197 $log = new CRM_Utils_SystemLogger();
198 $log->alert($message, $_REQUEST);
202 * Check if capability is supported.
204 * Capabilities have a one to one relationship with capability-related functions on this class.
206 * Payment processor classes should over-ride the capability-specific function rather than this one.
208 * @param string $capability
209 * E.g BackOffice, LiveMode, FutureRecurStartDate.
213 public function supports($capability) {
214 $function = 'supports' . ucfirst($capability);
215 if (method_exists($this, $function)) {
216 return $this->$function();
222 * Are back office payments supported.
224 * e.g paypal standard won't permit you to enter a credit card associated
225 * with someone else's login.
226 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
227 * reach a 'stable' point we disable.
231 protected function supportsBackOffice() {
232 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
241 * Can more than one transaction be processed at once?
243 * In general processors that process payment by server to server communication support this while others do not.
245 * In future we are likely to hit an issue where this depends on whether a token already exists.
249 protected function supportsMultipleConcurrentPayments() {
250 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
259 * Are live payments supported - e.g dummy doesn't support this.
263 protected function supportsLiveMode() {
268 * Are test payments supported.
272 protected function supportsTestMode() {
277 * Should the first payment date be configurable when setting up back office recurring payments.
279 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
283 protected function supportsFutureRecurStartDate() {
288 * Does this processor support cancelling recurring contributions through code.
290 * If the processor returns true it must be possible to take action from within CiviCRM
291 * that will result in no further payments being processed. In the case of token processors (e.g
292 * IATS, eWay) updating the contribution_recur table is probably sufficient.
296 protected function supportsCancelRecurring() {
297 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
301 * Does this processor support pre-approval.
303 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
305 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
306 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
307 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
311 protected function supportsPreApproval() {
316 * Can recurring contributions be set against pledges.
318 * In practice all processors that use the baseIPN function to finish transactions or
319 * call the completetransaction api support this by looking up previous contributions in the
320 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
321 * adding the new payment to the pledge.
323 * However, only enabling for processors it has been tested against.
327 protected function supportsRecurContributionsForPledges() {
332 * Function to action pre-approval if supported
334 * @param array $params
335 * Parameters from the form
337 * This function returns an array which should contain
338 * - pre_approval_parameters (this will be stored on the calling form & available later)
339 * - redirect_url (if set the browser will be redirected to this.
341 public function doPreApproval(&$params) {}
344 * Get any details that may be available to the payment processor due to an approval process having happened.
346 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
349 * @param array $storedDetails
353 public function getPreApprovalDetails($storedDetails) {
358 * Default payment instrument validation.
360 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
361 * Not a static function, because I need to check for payment_type.
363 * @param array $values
364 * @param array $errors
366 public function validatePaymentInstrument($values, &$errors) {
367 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
368 if ($this->_paymentProcessor
['payment_type'] == 1) {
369 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
374 * Getter for the payment processor.
376 * The payment processor array is based on the civicrm_payment_processor table entry.
379 * Payment processor array.
381 public function getPaymentProcessor() {
382 return $this->_paymentProcessor
;
386 * Setter for the payment processor.
388 * @param array $processor
390 public function setPaymentProcessor($processor) {
391 $this->_paymentProcessor
= $processor;
395 * Setter for the payment form that wants to use the processor.
399 * @param CRM_Core_Form $paymentForm
401 public function setForm(&$paymentForm) {
402 $this->_paymentForm
= $paymentForm;
406 * Getter for payment form that is using the processor.
408 * @return CRM_Core_Form
411 public function getForm() {
412 return $this->_paymentForm
;
416 * Get help text information (help, description, etc.) about this payment,
417 * to display to the user.
419 * @param string $context
420 * Context of the text.
421 * Only explicitly supported contexts are handled without error.
422 * Currently supported:
423 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
425 * @param array $params
426 * Parameters for the field, context specific.
430 public function getText($context, $params) {
431 // I have deliberately added a noisy fail here.
432 // The function is intended to be extendable, but not by changes
433 // not documented clearly above.
435 case 'contributionPageRecurringHelp':
436 // require exactly two parameters
437 if (array_keys($params) == array('is_recur_installments', 'is_email_receipt')) {
438 $gotText = ts('Your recurring contribution will be processed automatically.');
439 if ($params['is_recur_installments']) {
440 $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.');
442 if ($params['is_email_receipt']) {
443 $gotText .= ts(' You will receive an email receipt for each recurring contribution.');
452 * Getter for accessing member vars.
454 * @todo believe this is unused
456 * @param string $name
460 public function getVar($name) {
461 return isset($this->$name) ?
$this->$name : NULL;
465 * Get name for the payment information type.
466 * @todo - use option group + name field (like Omnipay does)
469 public function getPaymentTypeName() {
470 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
474 * Get label for the payment information type.
475 * @todo - use option group + labels (like Omnipay does)
478 public function getPaymentTypeLabel() {
479 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
483 * Get array of fields that should be displayed on the payment form.
484 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
486 * @throws CiviCRM_API3_Exception
488 public function getPaymentFormFields() {
489 if ($this->_paymentProcessor
['billing_mode'] == 4) {
492 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
496 * Get an array of the fields that can be edited on the recurring contribution.
498 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
499 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
500 * can be updated from the contribution recur edit screen.
502 * The fields are likely to be a subset of these
505 * - 'frequency_interval',
506 * - 'frequency_unit',
508 * - 'next_sched_contribution_date',
510 * - 'failure_retry_day',
512 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
513 * metadata is not defined in the xml for the field it will cause an error.
515 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
516 * form (UpdateSubscription).
520 public function getEditableRecurringScheduleFields() {
521 if (method_exists($this, 'changeSubscriptionAmount')) {
522 return array('amount');
527 * Get the help text to present on the recurring update page.
529 * This should reflect what can or cannot be edited.
533 public function getRecurringScheduleUpdateHelpText() {
534 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
535 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.');
537 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.');
541 * Get the metadata for all required fields.
545 protected function getMandatoryFields() {
546 $mandatoryFields = array();
547 foreach ($this->getAllFields() as $field_name => $field_spec) {
548 if (!empty($field_spec['is_required'])) {
549 $mandatoryFields[$field_name] = $field_spec;
552 return $mandatoryFields;
556 * Get the metadata of all the fields configured for this processor.
560 protected function getAllFields() {
561 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
562 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
563 return array_merge($paymentFields, $billingFields);
566 * Get array of fields that should be displayed on the payment form for credit cards.
570 protected function getCreditCardFormFields() {
573 'credit_card_number',
575 'credit_card_exp_date',
580 * Get array of fields that should be displayed on the payment form for direct debits.
584 protected function getDirectDebitFormFields() {
587 'bank_account_number',
588 'bank_identification_number',
594 * Return an array of all the details about the fields potentially required for payment fields.
596 * Only those determined by getPaymentFormFields will actually be assigned to the form
601 public function getPaymentFormFieldsMetadata() {
602 //@todo convert credit card type into an option value
603 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
605 'credit_card_number' => array(
606 'htmlType' => 'text',
607 'name' => 'credit_card_number',
608 'title' => ts('Card Number'),
610 'attributes' => array(
613 'autocomplete' => 'off',
614 'class' => 'creditcard',
616 'is_required' => TRUE,
619 'htmlType' => 'text',
621 'title' => ts('Security Code'),
623 'attributes' => array(
626 'autocomplete' => 'off',
628 'is_required' => Civi
::settings()->get('cvv_backoffice_required'),
631 '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.'),
632 'rule_name' => 'integer',
633 'rule_parameters' => NULL,
637 'credit_card_exp_date' => array(
638 'htmlType' => 'date',
639 'name' => 'credit_card_exp_date',
640 'title' => ts('Expiration Date'),
642 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
643 'is_required' => TRUE,
646 'rule_message' => ts('Card expiration date cannot be a past date.'),
647 'rule_name' => 'currentDate',
648 'rule_parameters' => TRUE,
652 'credit_card_type' => array(
653 'htmlType' => 'select',
654 'name' => 'credit_card_type',
655 'title' => ts('Card Type'),
657 'attributes' => $creditCardType,
658 'is_required' => FALSE,
660 'account_holder' => array(
661 'htmlType' => 'text',
662 'name' => 'account_holder',
663 'title' => ts('Account Holder'),
665 'attributes' => array(
668 'autocomplete' => 'on',
670 'is_required' => TRUE,
672 //e.g. IBAN can have maxlength of 34 digits
673 'bank_account_number' => array(
674 'htmlType' => 'text',
675 'name' => 'bank_account_number',
676 'title' => ts('Bank Account Number'),
678 'attributes' => array(
681 'autocomplete' => 'off',
685 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
686 'rule_name' => 'nopunctuation',
687 'rule_parameters' => NULL,
690 'is_required' => TRUE,
692 //e.g. SWIFT-BIC can have maxlength of 11 digits
693 'bank_identification_number' => array(
694 'htmlType' => 'text',
695 'name' => 'bank_identification_number',
696 'title' => ts('Bank Identification Number'),
698 'attributes' => array(
701 'autocomplete' => 'off',
703 'is_required' => TRUE,
706 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
707 'rule_name' => 'nopunctuation',
708 'rule_parameters' => NULL,
712 'bank_name' => array(
713 'htmlType' => 'text',
714 'name' => 'bank_name',
715 'title' => ts('Bank Name'),
717 'attributes' => array(
720 'autocomplete' => 'off',
722 'is_required' => TRUE,
729 * Get billing fields required for this processor.
731 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
734 * @param int $billingLocationID
738 public function getBillingAddressFields($billingLocationID = NULL) {
739 if (!$billingLocationID) {
740 // Note that although the billing id is passed around the forms the idea that it would be anything other than
741 // the result of the function below doesn't seem to have eventuated.
742 // So taking this as a param is possibly something to be removed in favour of the standard default.
743 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
745 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
749 'first_name' => 'billing_first_name',
750 'middle_name' => 'billing_middle_name',
751 'last_name' => 'billing_last_name',
752 'street_address' => "billing_street_address-{$billingLocationID}",
753 'city' => "billing_city-{$billingLocationID}",
754 'country' => "billing_country_id-{$billingLocationID}",
755 'state_province' => "billing_state_province_id-{$billingLocationID}",
756 'postal_code' => "billing_postal_code-{$billingLocationID}",
761 * Get form metadata for billing address fields.
763 * @param int $billingLocationID
766 * Array of metadata for address fields.
768 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
769 if (!$billingLocationID) {
770 // Note that although the billing id is passed around the forms the idea that it would be anything other than
771 // the result of the function below doesn't seem to have eventuated.
772 // So taking this as a param is possibly something to be removed in favour of the standard default.
773 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
776 $metadata['billing_first_name'] = array(
777 'htmlType' => 'text',
778 'name' => 'billing_first_name',
779 'title' => ts('Billing First Name'),
781 'attributes' => array(
784 'autocomplete' => 'off',
786 'is_required' => TRUE,
789 $metadata['billing_middle_name'] = array(
790 'htmlType' => 'text',
791 'name' => 'billing_middle_name',
792 'title' => ts('Billing Middle Name'),
794 'attributes' => array(
797 'autocomplete' => 'off',
799 'is_required' => FALSE,
802 $metadata['billing_last_name'] = array(
803 'htmlType' => 'text',
804 'name' => 'billing_last_name',
805 'title' => ts('Billing Last Name'),
807 'attributes' => array(
810 'autocomplete' => 'off',
812 'is_required' => TRUE,
815 $metadata["billing_street_address-{$billingLocationID}"] = array(
816 'htmlType' => 'text',
817 'name' => "billing_street_address-{$billingLocationID}",
818 'title' => ts('Street Address'),
820 'attributes' => array(
823 'autocomplete' => 'off',
825 'is_required' => TRUE,
828 $metadata["billing_city-{$billingLocationID}"] = array(
829 'htmlType' => 'text',
830 'name' => "billing_city-{$billingLocationID}",
831 'title' => ts('City'),
833 'attributes' => array(
836 'autocomplete' => 'off',
838 'is_required' => TRUE,
841 $metadata["billing_state_province_id-{$billingLocationID}"] = array(
842 'htmlType' => 'chainSelect',
843 'title' => ts('State/Province'),
844 'name' => "billing_state_province_id-{$billingLocationID}",
846 'is_required' => TRUE,
849 $metadata["billing_postal_code-{$billingLocationID}"] = array(
850 'htmlType' => 'text',
851 'name' => "billing_postal_code-{$billingLocationID}",
852 'title' => ts('Postal Code'),
854 'attributes' => array(
857 'autocomplete' => 'off',
859 'is_required' => TRUE,
862 $metadata["billing_country_id-{$billingLocationID}"] = array(
863 'htmlType' => 'select',
864 'name' => "billing_country_id-{$billingLocationID}",
865 'title' => ts('Country'),
867 'attributes' => array(
868 '' => ts('- select -'),
869 ) + CRM_Core_PseudoConstant
::country(),
870 'is_required' => TRUE,
876 * Get base url dependent on component.
878 * (or preferably set it using the setter function).
882 protected function getBaseReturnUrl() {
883 if ($this->baseReturnUrl
) {
884 return $this->baseReturnUrl
;
886 if ($this->_component
== 'event') {
887 $baseURL = 'civicrm/event/register';
890 $baseURL = 'civicrm/contribute/transact';
896 * Get url to return to after cancelled or failed transaction.
898 * @param string $qfKey
899 * @param int $participantID
901 * @return string cancel url
903 public function getCancelUrl($qfKey, $participantID) {
904 if (isset($this->cancelUrl
)) {
905 return $this->cancelUrl
;
908 if ($this->_component
== 'event') {
909 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
912 'participantId' => $participantID,
918 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
919 '_qf_Main_display' => 1,
928 * Get URL to return the browser to on success.
934 protected function getReturnSuccessUrl($qfKey) {
935 if (isset($this->successUrl
)) {
936 return $this->successUrl
;
939 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
940 '_qf_ThankYou_display' => 1,
948 * Get URL to return the browser to on failure.
951 * @param int $participantID
952 * @param int $eventID
955 * URL for a failing transactor to be redirected to.
957 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
958 if (isset($this->cancelUrl
)) {
959 return $this->cancelUrl
;
962 $test = $this->_is_test ?
'&action=preview' : '';
963 if ($this->_component
== "event") {
964 return CRM_Utils_System
::url('civicrm/event/register',
965 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
970 return CRM_Utils_System
::url('civicrm/contribute/transact',
971 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
978 * Get URl for when the back button is pressed.
984 protected function getGoBackUrl($qfKey) {
985 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
986 '_qf_Confirm_display' => 'true',
994 * Get the notify (aka ipn, web hook or silent post) url.
996 * If there is no '.' in it we assume that we are dealing with localhost or
997 * similar and it is unreachable from the web & hence invalid.
1000 * URL to notify outcome of transaction.
1002 protected function getNotifyUrl() {
1003 $url = CRM_Utils_System
::url(
1004 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
1010 return (stristr($url, '.')) ?
$url : '';
1014 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1016 * Does a server to server payment transaction.
1018 * @param array $params
1019 * Assoc array of input parameters for this transaction.
1022 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1024 protected function doDirectPayment(&$params) {
1029 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
1031 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
1034 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
1035 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
1036 * doTransferCheckout would not traditionally come back.
1038 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
1041 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
1042 * return Error objects
1044 * @param array $params
1046 * @param string $component
1051 * @throws \Civi\Payment\Exception\PaymentProcessorException
1053 public function doPayment(&$params, $component = 'contribute') {
1054 $this->_component
= $component;
1055 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1057 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1058 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1059 // have an example of that at the mome.
1060 if ($params['amount'] == 0) {
1061 $result['payment_status_id'] = array_search('Completed', $statuses);
1065 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1066 $result = $this->doTransferCheckout($params, $component);
1067 if (is_array($result) && !isset($result['payment_status_id'])) {
1068 $result['payment_status_id'] = array_search('Pending', $statuses);
1072 $result = $this->doDirectPayment($params, $component);
1073 if (is_array($result) && !isset($result['payment_status_id'])) {
1074 if (!empty($params['is_recur'])) {
1075 // See comment block.
1076 $result['payment_status_id'] = array_search('Pending', $statuses);
1079 $result['payment_status_id'] = array_search('Completed', $statuses);
1083 if (is_a($result, 'CRM_Core_Error')) {
1084 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1090 * Query payment processor for details about a transaction.
1092 * @param array $params
1093 * Array of parameters containing one of:
1094 * - trxn_id Id of an individual transaction.
1095 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1098 * Extra parameters retrieved.
1099 * Any parameters retrievable through this should be documented in the function comments at
1100 * CRM_Core_Payment::doQuery. Currently:
1101 * - fee_amount Amount of fee paid
1103 public function doQuery($params) {
1108 * This function checks to see if we have the right config values.
1111 * the error message if any
1113 abstract protected function checkConfig();
1116 * Redirect for paypal.
1118 * @todo move to paypal class or remove
1120 * @param $paymentProcessor
1124 public static function paypalRedirect(&$paymentProcessor) {
1125 if (!$paymentProcessor) {
1129 if (isset($_GET['payment_date']) &&
1130 isset($_GET['merchant_return_link']) &&
1131 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1132 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1141 * Handle incoming payment notification.
1143 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1145 * @todo move to0 \Civi\Payment\System factory method
1146 * Page callback for civicrm/payment/ipn
1148 public static function handleIPN() {
1149 self
::handlePaymentMethod(
1150 'PaymentNotification',
1152 'processor_name' => @$_GET['processor_name'],
1153 'processor_id' => @$_GET['processor_id'],
1154 'mode' => @$_GET['mode'],
1157 CRM_Utils_System
::civiExit();
1161 * Payment callback handler.
1163 * The processor_name or processor_id is passed in.
1164 * Note that processor_id is more reliable as one site may have more than one instance of a
1165 * processor & ideally the processor will be validating the results
1166 * Load requested payment processor and call that processor's handle<$method> method
1168 * @todo move to \Civi\Payment\System factory method
1170 * @param string $method
1171 * 'PaymentNotification' or 'PaymentCron'
1172 * @param array $params
1174 * @throws \CRM_Core_Exception
1175 * @throws \Exception
1177 public static function handlePaymentMethod($method, $params = array()) {
1178 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1179 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1180 $lastParam = array_pop($q);
1181 if (is_numeric($lastParam)) {
1182 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1185 self
::logPaymentNotification($params);
1186 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1190 self
::logPaymentNotification($params);
1192 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1193 FROM civicrm_payment_processor_type ppt
1194 INNER JOIN civicrm_payment_processor pp
1195 ON pp.payment_processor_type_id = ppt.id
1198 if (isset($params['processor_id'])) {
1199 $sql .= " WHERE pp.id = %2";
1200 $args[2] = array($params['processor_id'], 'Integer');
1201 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
1204 // This is called when processor_name is passed - passing processor_id instead is recommended.
1205 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1207 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1210 $args[2] = array($params['processor_name'], 'String');
1211 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
1214 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1216 // Check whether we found anything at all.
1218 CRM_Core_Error
::fatal($notFound);
1221 $method = 'handle' . $method;
1222 $extension_instance_found = FALSE;
1224 // In all likelihood, we'll just end up with the one instance returned here. But it's
1225 // possible we may get more. Hence, iterate through all instances ..
1227 while ($dao->fetch()) {
1228 // Check pp is extension - is this still required - surely the singleton below handles it.
1229 $ext = CRM_Extension_System
::singleton()->getMapper();
1230 if ($ext->isExtensionKey($dao->class_name
)) {
1231 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1232 require_once $ext->classToPath($paymentClass);
1235 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1237 // Should never be empty - we already established this processor_id exists and is active.
1238 if (empty($processorInstance)) {
1242 // Does PP implement this method, and can we call it?
1243 if (!method_exists($processorInstance, $method) ||
1244 !is_callable(array($processorInstance, $method))
1246 // on the off chance there is a double implementation of this processor we should keep looking for another
1247 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1251 // Everything, it seems, is ok - execute pp callback handler
1252 $processorInstance->$method();
1253 $extension_instance_found = TRUE;
1256 if (!$extension_instance_found) {
1257 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1258 "%2 method is unsupported in legacy payment processors.";
1259 CRM_Core_Error
::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
1264 * Check whether a method is present ( & supported ) by the payment processor object.
1266 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1268 * @param string $method
1269 * Method to check for.
1273 public function isSupported($method) {
1274 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1278 * Some processors replace the form submit button with their own.
1280 * Returning false here will leave the button off front end forms.
1282 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1284 public function isSuppressSubmitButtons() {
1289 * Checks to see if invoice_id already exists in db.
1291 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1292 * it is better to standardise to being here.
1294 * @param int $invoiceId The ID to check.
1296 * @param null $contributionID
1297 * If a contribution exists pass in the contribution ID.
1300 * True if invoice ID otherwise exists, else false
1302 protected function checkDupe($invoiceId, $contributionID = NULL) {
1303 $contribution = new CRM_Contribute_DAO_Contribution();
1304 $contribution->invoice_id
= $invoiceId;
1305 if ($contributionID) {
1306 $contribution->whereAdd("id <> $contributionID");
1308 return $contribution->find();
1312 * Get url for users to manage this recurring contribution for this processor.
1314 * @param int $entityID
1315 * @param null $entity
1316 * @param string $action
1320 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1324 $url = 'civicrm/contribute/unsubscribe';
1328 //in notify mode don't return the update billing url
1329 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
1332 $url = 'civicrm/contribute/updatebilling';
1336 $url = 'civicrm/contribute/updaterecur';
1340 $userId = CRM_Core_Session
::singleton()->get('userID');
1342 $checksumValue = '';
1345 // Find related Contact
1349 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1353 case 'contribution':
1354 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1355 $entityArg = 'coid';
1360 SELECT con.contact_id
1361 FROM civicrm_contribution_recur rec
1362 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1365 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
1366 $entityArg = 'crid';
1371 // Add entity arguments
1372 if ($entityArg != '') {
1373 // Add checksum argument
1374 if ($contactID != 0 && $userId != $contactID) {
1375 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1377 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1381 if ($this->isSupported('accountLoginURL')) {
1382 return $this->accountLoginURL();
1386 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1390 * Get description of payment to pass to processor.
1392 * This is often what people see in the interface so we want to get
1393 * as much unique information in as possible within the field length (& presumably the early part of the field)
1395 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1396 * having field names to clarify
1398 * @param array $params
1399 * @param int $length
1403 protected function getPaymentDescription($params, $length = 24) {
1404 $parts = array('contactID', 'contributionID', 'description', 'billing_first_name', 'billing_last_name');
1405 $validParts = array();
1406 if (isset($params['description'])) {
1407 $uninformativeStrings = array(ts('Online Event Registration: '), ts('Online Contribution: '));
1408 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1410 foreach ($parts as $part) {
1411 if ((!empty($params[$part]))) {
1412 $validParts[] = $params[$part];
1415 return substr(implode('-', $validParts), 0, $length);
1419 * Checks if backoffice recurring edit is allowed
1423 public function supportsEditRecurringContribution() {
1428 * Should a receipt be sent out for a pending payment.
1430 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1432 public function isSendReceiptForPending() {