3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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.
88 * This is used for processors that need to return the browser back to the CiviCRM site.
92 protected $baseReturnUrl;
95 * The profile configured to show on the billing form.
97 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
98 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
99 * requirements with the configured requirements.
101 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
104 * Note this change would probably include converting 'billing' to a reserved profile.
108 protected $billingProfile;
111 * Set Base return URL.
114 * Url of site to return browser to.
116 public function setBaseReturnUrl($url) {
117 $this->baseReturnUrl
= $url;
121 * Set the configured payment profile.
123 * @param int|string $value
125 public function setBillingProfile($value) {
126 $this->billingProfile
= $value;
130 * Opportunity for the payment processor to override the entire form build.
132 * @param CRM_Core_Form $form
135 * Should form building stop at this point?
137 public function buildForm(&$form) {
142 * Log payment notification message to forensic system log.
144 * @todo move to factory class \Civi\Payment\System (or similar)
146 * @param array $params
150 public static function logPaymentNotification($params) {
151 $message = 'payment_notification ';
152 if (!empty($params['processor_name'])) {
153 $message .= 'processor_name=' . $params['processor_name'];
155 if (!empty($params['processor_id'])) {
156 $message .= 'processor_id=' . $params['processor_id'];
159 $log = new CRM_Utils_SystemLogger();
160 $log->alert($message, $_REQUEST);
164 * Check if capability is supported.
166 * Capabilities have a one to one relationship with capability-related functions on this class.
168 * Payment processor classes should over-ride the capability-specific function rather than this one.
170 * @param string $capability
171 * E.g BackOffice, LiveMode, FutureRecurStartDate.
175 public function supports($capability) {
176 $function = 'supports' . ucfirst($capability);
177 if (method_exists($this, $function)) {
178 return $this->$function();
184 * Are back office payments supported.
186 * e.g paypal standard won't permit you to enter a credit card associated
187 * with someone else's login.
188 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
189 * reach a 'stable' point we disable.
193 protected function supportsBackOffice() {
194 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
203 * Can more than one transaction be processed at once?
205 * In general processors that process payment by server to server communication support this while others do not.
207 * In future we are likely to hit an issue where this depends on whether a token already exists.
211 protected function supportsMultipleConcurrentPayments() {
212 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
221 * Are live payments supported - e.g dummy doesn't support this.
225 protected function supportsLiveMode() {
230 * Are test payments supported.
234 protected function supportsTestMode() {
239 * Should the first payment date be configurable when setting up back office recurring payments.
241 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
245 protected function supportsFutureRecurStartDate() {
250 * Does this processor support cancelling recurring contributions through code.
254 protected function supportsCancelRecurring() {
255 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
259 * Does this processor support pre-approval.
261 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
263 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
264 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
265 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
269 protected function supportsPreApproval() {
274 * Can recurring contributions be set against pledges.
276 * In practice all processors that use the baseIPN function to finish transactions or
277 * call the completetransaction api support this by looking up previous contributions in the
278 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
279 * adding the new payment to the pledge.
281 * However, only enabling for processors it has been tested against.
285 protected function supportsRecurContributionsForPledges() {
290 * Function to action pre-approval if supported
292 * @param array $params
293 * Parameters from the form
295 * This function returns an array which should contain
296 * - pre_approval_parameters (this will be stored on the calling form & available later)
297 * - redirect_url (if set the browser will be redirected to this.
299 public function doPreApproval(&$params) {}
302 * Get any details that may be available to the payment processor due to an approval process having happened.
304 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
307 * @param array $storedDetails
311 public function getPreApprovalDetails($storedDetails) {
316 * Default payment instrument validation.
318 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
319 * Not a static function, because I need to check for payment_type.
321 * @param array $values
322 * @param array $errors
324 public function validatePaymentInstrument($values, &$errors) {
325 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
326 if ($this->_paymentProcessor
['payment_type'] == 1) {
327 CRM_Core_Payment_Form
::validateCreditCard($values, $errors);
332 * Getter for the payment processor.
334 * The payment processor array is based on the civicrm_payment_processor table entry.
337 * Payment processor array.
339 public function getPaymentProcessor() {
340 return $this->_paymentProcessor
;
344 * Setter for the payment processor.
346 * @param array $processor
348 public function setPaymentProcessor($processor) {
349 $this->_paymentProcessor
= $processor;
353 * Setter for the payment form that wants to use the processor.
357 * @param CRM_Core_Form $paymentForm
359 public function setForm(&$paymentForm) {
360 $this->_paymentForm
= $paymentForm;
364 * Getter for payment form that is using the processor.
366 * @return CRM_Core_Form
369 public function getForm() {
370 return $this->_paymentForm
;
374 * Getter for accessing member vars.
376 * @todo believe this is unused
378 * @param string $name
382 public function getVar($name) {
383 return isset($this->$name) ?
$this->$name : NULL;
387 * Get name for the payment information type.
388 * @todo - use option group + name field (like Omnipay does)
391 public function getPaymentTypeName() {
392 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
396 * Get label for the payment information type.
397 * @todo - use option group + labels (like Omnipay does)
400 public function getPaymentTypeLabel() {
401 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
405 * Get array of fields that should be displayed on the payment form.
406 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
408 * @throws CiviCRM_API3_Exception
410 public function getPaymentFormFields() {
411 if ($this->_paymentProcessor
['billing_mode'] == 4) {
414 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
418 * Get the metadata for all required fields.
422 protected function getMandatoryFields() {
423 $mandatoryFields = array();
424 foreach ($this->getAllFields() as $field_name => $field_spec) {
425 if (!empty($field_spec['is_required'])) {
426 $mandatoryFields[$field_name] = $field_spec;
429 return $mandatoryFields;
433 * Get the metadata of all the fields configured for this processor.
437 protected function getAllFields() {
438 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
439 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
440 return array_merge($paymentFields, $billingFields);
443 * Get array of fields that should be displayed on the payment form for credit cards.
447 protected function getCreditCardFormFields() {
450 'credit_card_number',
452 'credit_card_exp_date',
457 * Get array of fields that should be displayed on the payment form for direct debits.
461 protected function getDirectDebitFormFields() {
464 'bank_account_number',
465 'bank_identification_number',
471 * Return an array of all the details about the fields potentially required for payment fields.
473 * Only those determined by getPaymentFormFields will actually be assigned to the form
478 public function getPaymentFormFieldsMetadata() {
479 //@todo convert credit card type into an option value
480 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
482 'credit_card_number' => array(
483 'htmlType' => 'text',
484 'name' => 'credit_card_number',
485 'title' => ts('Card Number'),
487 'attributes' => array(
490 'autocomplete' => 'off',
491 'class' => 'creditcard',
493 'is_required' => TRUE,
496 'htmlType' => 'text',
498 'title' => ts('Security Code'),
500 'attributes' => array(
503 'autocomplete' => 'off',
505 'is_required' => Civi
::settings()->get('cvv_backoffice_required'),
508 '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.'),
509 'rule_name' => 'integer',
510 'rule_parameters' => NULL,
514 'credit_card_exp_date' => array(
515 'htmlType' => 'date',
516 'name' => 'credit_card_exp_date',
517 'title' => ts('Expiration Date'),
519 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
520 'is_required' => TRUE,
523 'rule_message' => ts('Card expiration date cannot be a past date.'),
524 'rule_name' => 'currentDate',
525 'rule_parameters' => TRUE,
529 'credit_card_type' => array(
530 'htmlType' => 'select',
531 'name' => 'credit_card_type',
532 'title' => ts('Card Type'),
534 'attributes' => $creditCardType,
535 'is_required' => FALSE,
537 'account_holder' => array(
538 'htmlType' => 'text',
539 'name' => 'account_holder',
540 'title' => ts('Account Holder'),
542 'attributes' => array(
545 'autocomplete' => 'on',
547 'is_required' => TRUE,
549 //e.g. IBAN can have maxlength of 34 digits
550 'bank_account_number' => array(
551 'htmlType' => 'text',
552 'name' => 'bank_account_number',
553 'title' => ts('Bank Account Number'),
555 'attributes' => array(
558 'autocomplete' => 'off',
562 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
563 'rule_name' => 'nopunctuation',
564 'rule_parameters' => NULL,
567 'is_required' => TRUE,
569 //e.g. SWIFT-BIC can have maxlength of 11 digits
570 'bank_identification_number' => array(
571 'htmlType' => 'text',
572 'name' => 'bank_identification_number',
573 'title' => ts('Bank Identification Number'),
575 'attributes' => array(
578 'autocomplete' => 'off',
580 'is_required' => TRUE,
583 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
584 'rule_name' => 'nopunctuation',
585 'rule_parameters' => NULL,
589 'bank_name' => array(
590 'htmlType' => 'text',
591 'name' => 'bank_name',
592 'title' => ts('Bank Name'),
594 'attributes' => array(
597 'autocomplete' => 'off',
599 'is_required' => TRUE,
606 * Get billing fields required for this processor.
608 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
611 * @param int $billingLocationID
615 public function getBillingAddressFields($billingLocationID = NULL) {
616 if (!$billingLocationID) {
617 // Note that although the billing id is passed around the forms the idea that it would be anything other than
618 // the result of the function below doesn't seem to have eventuated.
619 // So taking this as a param is possibly something to be removed in favour of the standard default.
620 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
622 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
626 'first_name' => 'billing_first_name',
627 'middle_name' => 'billing_middle_name',
628 'last_name' => 'billing_last_name',
629 'street_address' => "billing_street_address-{$billingLocationID}",
630 'city' => "billing_city-{$billingLocationID}",
631 'country' => "billing_country_id-{$billingLocationID}",
632 'state_province' => "billing_state_province_id-{$billingLocationID}",
633 'postal_code' => "billing_postal_code-{$billingLocationID}",
638 * Get form metadata for billing address fields.
640 * @param int $billingLocationID
643 * Array of metadata for address fields.
645 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
646 if (!$billingLocationID) {
647 // Note that although the billing id is passed around the forms the idea that it would be anything other than
648 // the result of the function below doesn't seem to have eventuated.
649 // So taking this as a param is possibly something to be removed in favour of the standard default.
650 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
653 $metadata['billing_first_name'] = array(
654 'htmlType' => 'text',
655 'name' => 'billing_first_name',
656 'title' => ts('Billing First Name'),
658 'attributes' => array(
661 'autocomplete' => 'off',
663 'is_required' => TRUE,
666 $metadata['billing_middle_name'] = array(
667 'htmlType' => 'text',
668 'name' => 'billing_middle_name',
669 'title' => ts('Billing Middle Name'),
671 'attributes' => array(
674 'autocomplete' => 'off',
676 'is_required' => FALSE,
679 $metadata['billing_last_name'] = array(
680 'htmlType' => 'text',
681 'name' => 'billing_last_name',
682 'title' => ts('Billing Last Name'),
684 'attributes' => array(
687 'autocomplete' => 'off',
689 'is_required' => TRUE,
692 $metadata["billing_street_address-{$billingLocationID}"] = array(
693 'htmlType' => 'text',
694 'name' => "billing_street_address-{$billingLocationID}",
695 'title' => ts('Street Address'),
697 'attributes' => array(
700 'autocomplete' => 'off',
702 'is_required' => TRUE,
705 $metadata["billing_city-{$billingLocationID}"] = array(
706 'htmlType' => 'text',
707 'name' => "billing_city-{$billingLocationID}",
708 'title' => ts('City'),
710 'attributes' => array(
713 'autocomplete' => 'off',
715 'is_required' => TRUE,
718 $metadata["billing_state_province_id-{$billingLocationID}"] = array(
719 'htmlType' => 'chainSelect',
720 'title' => ts('State/Province'),
721 'name' => "billing_state_province_id-{$billingLocationID}",
723 'is_required' => TRUE,
726 $metadata["billing_postal_code-{$billingLocationID}"] = array(
727 'htmlType' => 'text',
728 'name' => "billing_postal_code-{$billingLocationID}",
729 'title' => ts('Postal Code'),
731 'attributes' => array(
734 'autocomplete' => 'off',
736 'is_required' => TRUE,
739 $metadata["billing_country_id-{$billingLocationID}"] = array(
740 'htmlType' => 'select',
741 'name' => "billing_country_id-{$billingLocationID}",
742 'title' => ts('Country'),
744 'attributes' => array(
745 '' => ts('- select -'),
746 ) + CRM_Core_PseudoConstant
::country(),
747 'is_required' => TRUE,
753 * Get base url dependent on component.
755 * (or preferably set it using the setter function).
759 protected function getBaseReturnUrl() {
760 if ($this->baseReturnUrl
) {
761 return $this->baseReturnUrl
;
763 if ($this->_component
== 'event') {
764 $baseURL = 'civicrm/event/register';
767 $baseURL = 'civicrm/contribute/transact';
773 * Get url to return to after cancelled or failed transaction
776 * @param $participantID
778 * @return string cancel url
780 public function getCancelUrl($qfKey, $participantID) {
781 if ($this->_component
== 'event') {
782 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
785 'participantId' => $participantID,
791 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
792 '_qf_Main_display' => 1,
801 * Get URL to return the browser to on success.
807 protected function getReturnSuccessUrl($qfKey) {
808 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
809 '_qf_ThankYou_display' => 1,
817 * Get URL to return the browser to on failure.
820 * @param int $participantID
821 * @param int $eventID
824 * URL for a failing transactor to be redirected to.
826 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
827 $test = $this->_is_test ?
'&action=preview' : '';
828 if ($this->_component
== "event") {
829 return CRM_Utils_System
::url('civicrm/event/register',
830 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
835 return CRM_Utils_System
::url('civicrm/contribute/transact',
836 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
843 * Get URl for when the back button is pressed.
849 protected function getGoBackUrl($qfKey) {
850 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
851 '_qf_Confirm_display' => 'true',
859 * Get the notify (aka ipn, web hook or silent post) url.
861 * If there is no '.' in it we assume that we are dealing with localhost or
862 * similar and it is unreachable from the web & hence invalid.
865 * URL to notify outcome of transaction.
867 protected function getNotifyUrl() {
868 $url = CRM_Utils_System
::url(
869 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
873 return (stristr($url, '.')) ?
$url : '';
877 * Calling this from outside the payment subsystem is deprecated - use doPayment.
879 * Does a server to server payment transaction.
881 * @param array $params
882 * Assoc array of input parameters for this transaction.
885 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
887 protected function doDirectPayment(&$params) {
892 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
894 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
897 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
898 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
899 * doTransferCheckout would not traditionally come back.
901 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
904 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
905 * return Error objects
907 * @param array $params
909 * @param string $component
914 * @throws \Civi\Payment\Exception\PaymentProcessorException
916 public function doPayment(&$params, $component = 'contribute') {
917 $this->_component
= $component;
918 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
919 if ($this->_paymentProcessor
['billing_mode'] == 4) {
920 $result = $this->doTransferCheckout($params, $component);
921 if (is_array($result) && !isset($result['payment_status_id'])) {
922 $result['payment_status_id'] = array_search('Pending', $statuses);
926 $result = $this->doDirectPayment($params, $component);
927 if (is_array($result) && !isset($result['payment_status_id'])) {
928 if (!empty($params['is_recur'])) {
929 // See comment block.
930 $result['payment_status_id'] = array_search('Pending', $statuses);
933 $result['payment_status_id'] = array_search('Completed', $statuses);
937 if (is_a($result, 'CRM_Core_Error')) {
938 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
944 * Query payment processor for details about a transaction.
946 * @param array $params
947 * Array of parameters containing one of:
948 * - trxn_id Id of an individual transaction.
949 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
952 * Extra parameters retrieved.
953 * Any parameters retrievable through this should be documented in the function comments at
954 * CRM_Core_Payment::doQuery. Currently:
955 * - fee_amount Amount of fee paid
957 public function doQuery($params) {
962 * This function checks to see if we have the right config values.
965 * the error message if any
967 abstract protected function checkConfig();
970 * Redirect for paypal.
972 * @todo move to paypal class or remove
974 * @param $paymentProcessor
978 public static function paypalRedirect(&$paymentProcessor) {
979 if (!$paymentProcessor) {
983 if (isset($_GET['payment_date']) &&
984 isset($_GET['merchant_return_link']) &&
985 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
986 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
995 * Handle incoming payment notification.
997 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
999 * @todo move to0 \Civi\Payment\System factory method
1000 * Page callback for civicrm/payment/ipn
1002 public static function handleIPN() {
1003 self
::handlePaymentMethod(
1004 'PaymentNotification',
1006 'processor_name' => @$_GET['processor_name'],
1007 'processor_id' => @$_GET['processor_id'],
1008 'mode' => @$_GET['mode'],
1012 CRM_Utils_System
::civiExit();
1016 * Payment callback handler.
1018 * The processor_name or processor_id is passed in.
1019 * Note that processor_id is more reliable as one site may have more than one instance of a
1020 * processor & ideally the processor will be validating the results
1021 * Load requested payment processor and call that processor's handle<$method> method
1023 * @todo move to \Civi\Payment\System factory method
1025 * @param string $method
1026 * 'PaymentNotification' or 'PaymentCron'
1027 * @param array $params
1029 * @throws \CRM_Core_Exception
1030 * @throws \Exception
1032 public static function handlePaymentMethod($method, $params = array()) {
1033 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1034 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
1035 $lastParam = array_pop($q);
1036 if (is_numeric($lastParam)) {
1037 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1040 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1044 self
::logPaymentNotification($params);
1046 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1047 FROM civicrm_payment_processor_type ppt
1048 INNER JOIN civicrm_payment_processor pp
1049 ON pp.payment_processor_type_id = ppt.id
1052 if (isset($params['processor_id'])) {
1053 $sql .= " WHERE pp.id = %2";
1054 $args[2] = array($params['processor_id'], 'Integer');
1055 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
1058 // This is called when processor_name is passed - passing processor_id instead is recommended.
1059 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1061 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1064 $args[2] = array($params['processor_name'], 'String');
1065 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
1068 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1070 // Check whether we found anything at all.
1072 CRM_Core_Error
::fatal($notFound);
1075 $method = 'handle' . $method;
1076 $extension_instance_found = FALSE;
1078 // In all likelihood, we'll just end up with the one instance returned here. But it's
1079 // possible we may get more. Hence, iterate through all instances ..
1081 while ($dao->fetch()) {
1082 // Check pp is extension - is this still required - surely the singleton below handles it.
1083 $ext = CRM_Extension_System
::singleton()->getMapper();
1084 if ($ext->isExtensionKey($dao->class_name
)) {
1085 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1086 require_once $ext->classToPath($paymentClass);
1089 $processorInstance = Civi\Payment\System
::singleton()->getById($dao->processor_id
);
1091 // Should never be empty - we already established this processor_id exists and is active.
1092 if (empty($processorInstance)) {
1096 // Does PP implement this method, and can we call it?
1097 if (!method_exists($processorInstance, $method) ||
1098 !is_callable(array($processorInstance, $method))
1100 // on the off chance there is a double implementation of this processor we should keep looking for another
1101 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1105 // Everything, it seems, is ok - execute pp callback handler
1106 $processorInstance->$method();
1107 $extension_instance_found = TRUE;
1110 if (!$extension_instance_found) {
1111 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1112 "%2 method is unsupported in legacy payment processors.";
1113 CRM_Core_Error
::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
1118 * Check whether a method is present ( & supported ) by the payment processor object.
1120 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1122 * @param string $method
1123 * Method to check for.
1127 public function isSupported($method = 'cancelSubscription') {
1128 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1132 * Some processors replace the form submit button with their own.
1134 * Returning false here will leave the button off front end forms.
1136 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1138 public function isSuppressSubmitButtons() {
1143 * Checks to see if invoice_id already exists in db.
1145 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1146 * it is better to standardise to being here.
1148 * @param int $invoiceId The ID to check.
1150 * @param null $contributionID
1151 * If a contribution exists pass in the contribution ID.
1154 * True if invoice ID otherwise exists, else false
1156 protected function checkDupe($invoiceId, $contributionID = NULL) {
1157 $contribution = new CRM_Contribute_DAO_Contribution();
1158 $contribution->invoice_id
= $invoiceId;
1159 if ($contributionID) {
1160 $contribution->whereAdd("id <> $contributionID");
1162 return $contribution->find();
1166 * Get url for users to manage this recurring contribution for this processor.
1168 * @param int $entityID
1169 * @param null $entity
1170 * @param string $action
1174 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1178 $url = 'civicrm/contribute/unsubscribe';
1182 //in notify mode don't return the update billing url
1183 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
1186 $url = 'civicrm/contribute/updatebilling';
1190 $url = 'civicrm/contribute/updaterecur';
1194 $session = CRM_Core_Session
::singleton();
1195 $userId = $session->get('userID');
1197 $checksumValue = '';
1200 // Find related Contact
1204 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1208 case 'contribution':
1209 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1210 $entityArg = 'coid';
1215 SELECT con.contact_id
1216 FROM civicrm_contribution_recur rec
1217 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1220 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
1221 $entityArg = 'crid';
1226 // Add entity arguments
1227 if ($entityArg != '') {
1228 // Add checksum argument
1229 if ($contactID != 0 && $userId != $contactID) {
1230 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1232 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1236 if ($this->isSupported('accountLoginURL')) {
1237 return $this->accountLoginURL();
1241 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1245 * Get description of payment to pass to processor.
1247 * This is often what people see in the interface so we want to get
1248 * as much unique information in as possible within the field length (& presumably the early part of the field)
1250 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1251 * having field names to clarify
1253 * @param array $params
1254 * @param int $length
1258 protected function getPaymentDescription($params, $length = 24) {
1259 $parts = array('contactID', 'contributionID', 'description', 'billing_first_name', 'billing_last_name');
1260 $validParts = array();
1261 if (isset($params['description'])) {
1262 $uninformativeStrings = array(ts('Online Event Registration: '), ts('Online Contribution: '));
1263 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1265 foreach ($parts as $part) {
1266 if ((!empty($params[$part]))) {
1267 $validParts[] = $params[$part];
1270 return substr(implode('-', $validParts), 0, $length);