3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 * Opportunity for the payment processor to override the entire form build.
88 * @param CRM_Core_Form $form
91 * Should form building stop at this point?
93 public function buildForm(&$form) {
98 * Log payment notification message to forensic system log.
100 * @todo move to factory class \Civi\Payment\System (or similar)
102 * @param array $params
106 public static function logPaymentNotification($params) {
107 $message = 'payment_notification ';
108 if (!empty($params['processor_name'])) {
109 $message .= 'processor_name=' . $params['processor_name'];
111 if (!empty($params['processor_id'])) {
112 $message .= 'processor_id=' . $params['processor_id'];
115 $log = new CRM_Utils_SystemLogger();
116 $log->alert($message, $_REQUEST);
120 * Check if capability is supported.
122 * Capabilities have a one to one relationship with capability-related functions on this class.
124 * Payment processor classes should over-ride the capability-specific function rather than this one.
126 * @param string $capability
127 * E.g BackOffice, LiveMode, FutureRecurStartDate.
131 public function supports($capability) {
132 $function = 'supports' . ucfirst($capability);
133 if (method_exists($this, $function)) {
134 return $this->$function();
140 * Are back office payments supported.
142 * e.g paypal standard won't permit you to enter a credit card associated
143 * with someone else's login.
144 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
145 * reach a 'stable' point we disable.
149 protected function supportsBackOffice() {
150 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
159 * Can more than one transaction be processed at once?
161 * In general processors that process payment by server to server communication support this while others do not.
163 * In future we are likely to hit an issue where this depends on whether a token already exists.
167 protected function supportsMultipleConcurrentPayments() {
168 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
177 * Are live payments supported - e.g dummy doesn't support this.
181 protected function supportsLiveMode() {
186 * Are test payments supported.
190 protected function supportsTestMode() {
195 * Should the first payment date be configurable when setting up back office recurring payments.
197 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
201 protected function supportsFutureRecurStartDate() {
206 * Does this processor support cancelling recurring contributions through code.
210 protected function supportsCancelRecurring() {
211 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
215 * Does this processor support pre-approval.
217 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
219 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
220 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
221 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
225 protected function supportsPreApproval() {
230 * Can recurring contributions be set against pledges.
232 * In practice all processors that use the baseIPN function to finish transactions or
233 * call the completetransaction api support this by looking up previous contributions in the
234 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
235 * adding the new payment to the pledge.
237 * However, only enabling for processors it has been tested against.
241 protected function supportsRecurContributionsForPledges() {
246 * Function to action pre-approval if supported
248 * @param array $params
249 * Parameters from the form
251 * This function returns an array which should contain
252 * - pre_approval_parameters (this will be stored on the calling form & available later)
253 * - redirect_url (if set the browser will be redirected to this.
255 public function doPreApproval(&$params) {}
258 * Get any details that may be available to the payment processor due to an approval process having happened.
260 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
263 * @param array $storedDetails
267 public function getPreApprovalDetails($storedDetails) {
272 * Default payment instrument validation.
274 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
275 * Not a static function, because I need to check for payment_type.
277 * @param array $values
278 * @param array $errors
280 public function validatePaymentInstrument($values, &$errors) {
281 if ($this->_paymentProcessor
['payment_type'] == 1) {
282 CRM_Core_Payment_Form
::validateCreditCard($values, $errors);
287 * Getter for the payment processor.
289 * The payment processor array is based on the civicrm_payment_processor table entry.
292 * Payment processor array.
294 public function getPaymentProcessor() {
295 return $this->_paymentProcessor
;
299 * Setter for the payment processor.
301 * @param array $processor
303 public function setPaymentProcessor($processor) {
304 $this->_paymentProcessor
= $processor;
308 * Setter for the payment form that wants to use the processor.
312 * @param CRM_Core_Form $paymentForm
314 public function setForm(&$paymentForm) {
315 $this->_paymentForm
= $paymentForm;
319 * Getter for payment form that is using the processor.
321 * @return CRM_Core_Form
324 public function getForm() {
325 return $this->_paymentForm
;
329 * Getter for accessing member vars.
331 * @todo believe this is unused
333 * @param string $name
337 public function getVar($name) {
338 return isset($this->$name) ?
$this->$name : NULL;
342 * Get name for the payment information type.
343 * @todo - use option group + name field (like Omnipay does)
346 public function getPaymentTypeName() {
347 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
351 * Get label for the payment information type.
352 * @todo - use option group + labels (like Omnipay does)
355 public function getPaymentTypeLabel() {
356 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
360 * Get array of fields that should be displayed on the payment form.
361 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
363 * @throws CiviCRM_API3_Exception
365 public function getPaymentFormFields() {
366 if ($this->_paymentProcessor
['billing_mode'] == 4) {
369 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
373 * Get array of fields that should be displayed on the payment form for credit cards.
377 protected function getCreditCardFormFields() {
380 'credit_card_number',
382 'credit_card_exp_date',
387 * Get array of fields that should be displayed on the payment form for direct debits.
391 protected function getDirectDebitFormFields() {
394 'bank_account_number',
395 'bank_identification_number',
401 * Return an array of all the details about the fields potentially required for payment fields.
403 * Only those determined by getPaymentFormFields will actually be assigned to the form
408 public function getPaymentFormFieldsMetadata() {
409 //@todo convert credit card type into an option value
410 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
412 'credit_card_number' => array(
413 'htmlType' => 'text',
414 'name' => 'credit_card_number',
415 'title' => ts('Card Number'),
417 'attributes' => array(
420 'autocomplete' => 'off',
421 'class' => 'creditcard',
423 'is_required' => TRUE,
426 'htmlType' => 'text',
428 'title' => ts('Security Code'),
430 'attributes' => array(
433 'autocomplete' => 'off',
435 'is_required' => CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,
436 'cvv_backoffice_required',
442 '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.'),
443 'rule_name' => 'integer',
444 'rule_parameters' => NULL,
448 'credit_card_exp_date' => array(
449 'htmlType' => 'date',
450 'name' => 'credit_card_exp_date',
451 'title' => ts('Expiration Date'),
453 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
454 'is_required' => TRUE,
457 'rule_message' => ts('Card expiration date cannot be a past date.'),
458 'rule_name' => 'currentDate',
459 'rule_parameters' => TRUE,
463 'credit_card_type' => array(
464 'htmlType' => 'select',
465 'name' => 'credit_card_type',
466 'title' => ts('Card Type'),
468 'attributes' => $creditCardType,
469 'is_required' => FALSE,
471 'account_holder' => array(
472 'htmlType' => 'text',
473 'name' => 'account_holder',
474 'title' => ts('Account Holder'),
476 'attributes' => array(
479 'autocomplete' => 'on',
481 'is_required' => TRUE,
483 //e.g. IBAN can have maxlength of 34 digits
484 'bank_account_number' => array(
485 'htmlType' => 'text',
486 'name' => 'bank_account_number',
487 'title' => ts('Bank Account Number'),
489 'attributes' => array(
492 'autocomplete' => 'off',
496 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
497 'rule_name' => 'nopunctuation',
498 'rule_parameters' => NULL,
501 'is_required' => TRUE,
503 //e.g. SWIFT-BIC can have maxlength of 11 digits
504 'bank_identification_number' => array(
505 'htmlType' => 'text',
506 'name' => 'bank_identification_number',
507 'title' => ts('Bank Identification Number'),
509 'attributes' => array(
512 'autocomplete' => 'off',
514 'is_required' => TRUE,
517 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
518 'rule_name' => 'nopunctuation',
519 'rule_parameters' => NULL,
523 'bank_name' => array(
524 'htmlType' => 'text',
525 'name' => 'bank_name',
526 'title' => ts('Bank Name'),
528 'attributes' => array(
531 'autocomplete' => 'off',
533 'is_required' => TRUE,
540 * Get base url dependent on component.
542 * @return string|void
544 protected function getBaseReturnUrl() {
545 if ($this->_component
== 'event') {
546 $baseURL = 'civicrm/event/register';
549 $baseURL = 'civicrm/contribute/transact';
555 * Get url to return to after cancelled or failed transaction
558 * @param $participantID
560 * @return string cancel url
562 protected function getCancelUrl($qfKey, $participantID) {
563 if ($this->_component
== 'event') {
564 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
567 'participantId' => $participantID,
573 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
574 '_qf_Main_display' => 1,
583 * Get URL to return the browser to on success.
589 protected function getReturnSuccessUrl($qfKey) {
590 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
591 '_qf_ThankYou_display' => 1,
599 * Get URL to return the browser to on failure.
602 * @param int $participantID
603 * @param int $eventID
606 * URL for a failing transactor to be redirected to.
608 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
609 $test = $this->_is_test ?
'&action=preview' : '';
610 if ($this->_component
== "event") {
611 return CRM_Utils_System
::url('civicrm/event/register',
612 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
617 return CRM_Utils_System
::url('civicrm/contribute/transact',
618 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
625 * Get URl for when the back button is pressed.
631 protected function getGoBackUrl($qfKey) {
632 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
633 '_qf_Confirm_display' => 'true',
641 * Get the notify (aka ipn, web hook or silent post) url.
643 * If there is no '.' in it we assume that we are dealing with localhost or
644 * similar and it is unreachable from the web & hence invalid.
647 * URL to notify outcome of transaction.
649 protected function getNotifyUrl() {
650 $url = CRM_Utils_System
::url(
651 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
655 return (stristr($url, '.')) ?
$url : '';
659 * Calling this from outside the payment subsystem is deprecated - use doPayment.
661 * Does a server to server payment transaction.
663 * @param array $params
664 * Assoc array of input parameters for this transaction.
667 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
669 protected function doDirectPayment(&$params) {
674 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
676 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
679 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
680 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
681 * doTransferCheckout would not traditionally come back.
683 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
686 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
687 * return Error objects
689 * @param array $params
691 * @param string $component
696 * @throws \Civi\Payment\Exception\PaymentProcessorException
698 public function doPayment(&$params, $component = 'contribute') {
699 $this->_component
= $component;
700 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
701 if ($this->_paymentProcessor
['billing_mode'] == 4) {
702 $result = $this->doTransferCheckout($params, $component);
703 if (is_array($result) && !isset($result['payment_status_id'])) {
704 $result['payment_status_id'] = array_search('Pending', $statuses);
708 if ($this->_paymentProcessor
['billing_mode'] == 1) {
709 $result = $this->doDirectPayment($params, $component);
712 $result = $this->doExpressCheckout($params);
714 if (is_array($result) && !isset($result['payment_status_id'])) {
715 if (!empty($params['is_recur'])) {
716 // See comment block.
717 $result['payment_status_id'] = array_search('Pending', $statuses);
720 $result['payment_status_id'] = array_search('Completed', $statuses);
724 if (is_a($result, 'CRM_Core_Error')) {
725 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
731 * This function checks to see if we have the right config values.
734 * the error message if any
736 abstract protected function checkConfig();
739 * Redirect for paypal.
741 * @todo move to paypal class or remove
743 * @param $paymentProcessor
747 public static function paypalRedirect(&$paymentProcessor) {
748 if (!$paymentProcessor) {
752 if (isset($_GET['payment_date']) &&
753 isset($_GET['merchant_return_link']) &&
754 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
755 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
764 * Handle incoming payment notification.
766 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
768 * @todo move to0 \Civi\Payment\System factory method
769 * Page callback for civicrm/payment/ipn
771 public static function handleIPN() {
772 self
::handlePaymentMethod(
773 'PaymentNotification',
775 'processor_name' => @$_GET['processor_name'],
776 'processor_id' => @$_GET['processor_id'],
777 'mode' => @$_GET['mode'],
781 CRM_Utils_System
::civiExit();
785 * Payment callback handler.
787 * The processor_name or processor_id is passed in.
788 * Note that processor_id is more reliable as one site may have more than one instance of a
789 * processor & ideally the processor will be validating the results
790 * Load requested payment processor and call that processor's handle<$method> method
792 * @todo move to \Civi\Payment\System factory method
794 * @param string $method
795 * 'PaymentNotification' or 'PaymentCron'
796 * @param array $params
798 * @throws \CRM_Core_Exception
801 public static function handlePaymentMethod($method, $params = array()) {
802 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
803 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
804 $lastParam = array_pop($q);
805 if (is_numeric($lastParam)) {
806 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
809 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
813 self
::logPaymentNotification($params);
815 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
816 FROM civicrm_payment_processor_type ppt
817 INNER JOIN civicrm_payment_processor pp
818 ON pp.payment_processor_type_id = ppt.id
821 if (isset($params['processor_id'])) {
822 $sql .= " WHERE pp.id = %2";
823 $args[2] = array($params['processor_id'], 'Integer');
824 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
827 // This is called when processor_name is passed - passing processor_id instead is recommended.
828 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
830 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
833 $args[2] = array($params['processor_name'], 'String');
834 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
837 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
839 // Check whether we found anything at all.
841 CRM_Core_Error
::fatal($notFound);
844 $method = 'handle' . $method;
845 $extension_instance_found = FALSE;
847 // In all likelihood, we'll just end up with the one instance returned here. But it's
848 // possible we may get more. Hence, iterate through all instances ..
850 while ($dao->fetch()) {
851 // Check pp is extension - is this still required - surely the singleton below handles it.
852 $ext = CRM_Extension_System
::singleton()->getMapper();
853 if ($ext->isExtensionKey($dao->class_name
)) {
854 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
855 require_once $ext->classToPath($paymentClass);
858 $processorInstance = Civi\Payment\System
::singleton()->getById($dao->processor_id
);
860 // Should never be empty - we already established this processor_id exists and is active.
861 if (empty($processorInstance)) {
865 // Does PP implement this method, and can we call it?
866 if (!method_exists($processorInstance, $method) ||
867 !is_callable(array($processorInstance, $method))
869 // on the off chance there is a double implementation of this processor we should keep looking for another
870 // note that passing processor_id is more reliable & we should work to deprecate processor_name
874 // Everything, it seems, is ok - execute pp callback handler
875 $processorInstance->$method();
876 $extension_instance_found = TRUE;
879 if (!$extension_instance_found) {
880 $message = "No extension instances of the '%1' payment processor were found.<br />" .
881 "%2 method is unsupported in legacy payment processors.";
882 CRM_Core_Error
::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
887 * Check whether a method is present ( & supported ) by the payment processor object.
889 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
891 * @param string $method
892 * Method to check for.
896 public function isSupported($method = 'cancelSubscription') {
897 return method_exists(CRM_Utils_System
::getClassName($this), $method);
901 * Some processors replace the form submit button with their own.
903 * Returning false here will leave the button off front end forms.
905 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
907 public function isSuppressSubmitButtons() {
912 * Checks to see if invoice_id already exists in db.
914 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
915 * it is better to standardise to being here.
917 * @param int $invoiceId The ID to check.
919 * @param null $contributionID
920 * If a contribution exists pass in the contribution ID.
923 * True if invoice ID otherwise exists, else false
925 protected function checkDupe($invoiceId, $contributionID = NULL) {
926 $contribution = new CRM_Contribute_DAO_Contribution();
927 $contribution->invoice_id
= $invoiceId;
928 if ($contributionID) {
929 $contribution->whereAdd("id <> $contributionID");
931 return $contribution->find();
935 * Get url for users to manage this recurring contribution for this processor.
937 * @param int $entityID
938 * @param null $entity
939 * @param string $action
943 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
947 $url = 'civicrm/contribute/unsubscribe';
951 //in notify mode don't return the update billing url
952 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
955 $url = 'civicrm/contribute/updatebilling';
959 $url = 'civicrm/contribute/updaterecur';
963 $session = CRM_Core_Session
::singleton();
964 $userId = $session->get('userID');
969 // Find related Contact
973 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
978 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
984 SELECT con.contact_id
985 FROM civicrm_contribution_recur rec
986 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
989 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
995 // Add entity arguments
996 if ($entityArg != '') {
997 // Add checksum argument
998 if ($contactID != 0 && $userId != $contactID) {
999 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1001 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1005 if ($this->isSupported('accountLoginURL')) {
1006 return $this->accountLoginURL();
1010 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';