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 * How are we getting billing information?
44 * FORM - we collect it on the same page
45 * BUTTON - the processor collects it and sends it back to us via some protocol
48 BILLING_MODE_FORM
= 1,
49 BILLING_MODE_BUTTON
= 2,
50 BILLING_MODE_NOTIFY
= 4;
53 * Which payment type(s) are we using?
58 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
61 PAYMENT_TYPE_CREDIT_CARD
= 1,
62 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
65 * Subscription / Recurring payment Status
69 RECURRING_PAYMENT_START
= 'START',
70 RECURRING_PAYMENT_END
= 'END';
72 protected $_paymentProcessor;
75 * Singleton function used to manage this object.
77 * We will migrate to calling Civi\Payment\System::singleton()->getByProcessor($paymentProcessor)
78 * & Civi\Payment\System::singleton()->getById($paymentProcessor) directly as the main access methods & work
79 * to remove this function all together
82 * The mode of operation: live or test.
83 * @param array $paymentProcessor
84 * The details of the payment processor being invoked.
85 * @param object $paymentForm
86 * Deprecated - avoid referring to this if possible. If you have to use it document why as this is scary interaction.
88 * Should we force a reload of this payment object.
90 * @return CRM_Core_Payment
91 * @throws \CRM_Core_Exception
93 public static function singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
94 // make sure paymentProcessor is not empty
96 if (empty($paymentProcessor)) {
97 return CRM_Core_DAO
::$_nullObject;
99 //we use two lines because we can't remove the '&singleton' without risking breakage
100 //of extension classes that extend this one
101 $object = Civi\Payment\System
::singleton()->getByProcessor($paymentProcessor);
106 * Opportunity for the payment processor to override the entire form build.
108 * @param CRM_Core_Form $form
111 * Should form building stop at this point?
113 public function buildForm(&$form) {
118 * Log payment notification message to forensic system log.
120 * @todo move to factory class \Civi\Payment\System (or similar)
122 * @param array $params
126 public static function logPaymentNotification($params) {
127 $message = 'payment_notification ';
128 if (!empty($params['processor_name'])) {
129 $message .= 'processor_name=' . $params['processor_name'];
131 if (!empty($params['processor_id'])) {
132 $message .= 'processor_id=' . $params['processor_id'];
135 $log = new CRM_Utils_SystemLogger();
136 $log->alert($message, $_REQUEST);
140 * Check if capability is supported.
142 * Capabilities have a one to one relationship with capability-related functions on this class.
144 * Payment processor classes should over-ride the capability-specific function rather than this one.
146 * @param string $capability
147 * E.g BackOffice, LiveMode, FutureRecurStartDate.
151 public function supports($capability) {
152 $function = 'supports' . ucfirst($capability);
153 if (method_exists($this, $function)) {
154 return $this->$function();
160 * Are back office payments supported.
162 * e.g paypal standard won't permit you to enter a credit card associated
163 * with someone else's login.
164 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
165 * reach a 'stable' point we disable.
169 protected function supportsBackOffice() {
170 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
179 * Can more than one transaction be processed at once?
181 * In general processors that process payment by server to server communication support this while others do not.
183 * In future we are likely to hit an issue where this depends on whether a token already exists.
187 protected function supportsMultipleConcurrentPayments() {
188 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
197 * Are live payments supported - e.g dummy doesn't support this.
201 protected function supportsLiveMode() {
206 * Are test payments supported.
210 protected function supportsTestMode() {
215 * Should the first payment date be configurable when setting up back office recurring payments.
217 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
221 protected function supportsFutureRecurStartDate() {
226 * Default payment instrument validation.
228 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
229 * Not a static function, because I need to check for payment_type.
231 * @param array $values
232 * @param array $errors
234 public function validatePaymentInstrument($values, &$errors) {
235 if ($this->_paymentProcessor
['payment_type'] == 1) {
236 CRM_Core_Payment_Form
::validateCreditCard($values, $errors);
241 * Getter for the payment processor.
243 * The payment processor array is based on the civicrm_payment_processor table entry.
246 * Payment processor array.
248 public function getPaymentProcessor() {
249 return $this->_paymentProcessor
;
253 * Setter for the payment processor.
255 * @param array $processor
257 public function setPaymentProcessor($processor) {
258 $this->_paymentProcessor
= $processor;
262 * Setter for the payment form that wants to use the processor.
266 * @param CRM_Core_Form $paymentForm
268 public function setForm(&$paymentForm) {
269 $this->_paymentForm
= $paymentForm;
273 * Getter for payment form that is using the processor.
275 * @return CRM_Core_Form
278 public function getForm() {
279 return $this->_paymentForm
;
283 * Getter for accessing member vars.
285 * @todo believe this is unused
287 * @param string $name
291 public function getVar($name) {
292 return isset($this->$name) ?
$this->$name : NULL;
296 * Get name for the payment information type.
297 * @todo - use option group + name field (like Omnipay does)
300 public function getPaymentTypeName() {
301 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
305 * Get label for the payment information type.
306 * @todo - use option group + labels (like Omnipay does)
309 public function getPaymentTypeLabel() {
310 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
314 * Get array of fields that should be displayed on the payment form.
315 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
317 * @throws CiviCRM_API3_Exception
319 public function getPaymentFormFields() {
320 if ($this->_paymentProcessor
['billing_mode'] == 4) {
323 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
327 * Get array of fields that should be displayed on the payment form for credit cards.
331 protected function getCreditCardFormFields() {
334 'credit_card_number',
336 'credit_card_exp_date',
341 * Get array of fields that should be displayed on the payment form for direct debits.
345 protected function getDirectDebitFormFields() {
348 'bank_account_number',
349 'bank_identification_number',
355 * Return an array of all the details about the fields potentially required for payment fields.
357 * Only those determined by getPaymentFormFields will actually be assigned to the form
362 public function getPaymentFormFieldsMetadata() {
363 //@todo convert credit card type into an option value
364 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
366 'credit_card_number' => array(
367 'htmlType' => 'text',
368 'name' => 'credit_card_number',
369 'title' => ts('Card Number'),
371 'attributes' => array(
374 'autocomplete' => 'off',
375 'class' => 'creditcard',
377 'is_required' => TRUE,
380 'htmlType' => 'text',
382 'title' => ts('Security Code'),
384 'attributes' => array(
387 'autocomplete' => 'off',
389 'is_required' => CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,
390 'cvv_backoffice_required',
396 '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.'),
397 'rule_name' => 'integer',
398 'rule_parameters' => NULL,
402 'credit_card_exp_date' => array(
403 'htmlType' => 'date',
404 'name' => 'credit_card_exp_date',
405 'title' => ts('Expiration Date'),
407 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
408 'is_required' => TRUE,
411 'rule_message' => ts('Card expiration date cannot be a past date.'),
412 'rule_name' => 'currentDate',
413 'rule_parameters' => TRUE,
417 'credit_card_type' => array(
418 'htmlType' => 'select',
419 'name' => 'credit_card_type',
420 'title' => ts('Card Type'),
422 'attributes' => $creditCardType,
423 'is_required' => FALSE,
425 'account_holder' => array(
426 'htmlType' => 'text',
427 'name' => 'account_holder',
428 'title' => ts('Account Holder'),
430 'attributes' => array(
433 'autocomplete' => 'on',
435 'is_required' => TRUE,
437 //e.g. IBAN can have maxlength of 34 digits
438 'bank_account_number' => array(
439 'htmlType' => 'text',
440 'name' => 'bank_account_number',
441 'title' => ts('Bank Account Number'),
443 'attributes' => array(
446 'autocomplete' => 'off',
450 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
451 'rule_name' => 'nopunctuation',
452 'rule_parameters' => NULL,
455 'is_required' => TRUE,
457 //e.g. SWIFT-BIC can have maxlength of 11 digits
458 'bank_identification_number' => array(
459 'htmlType' => 'text',
460 'name' => 'bank_identification_number',
461 'title' => ts('Bank Identification Number'),
463 'attributes' => array(
466 'autocomplete' => 'off',
468 'is_required' => TRUE,
471 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
472 'rule_name' => 'nopunctuation',
473 'rule_parameters' => NULL,
477 'bank_name' => array(
478 'htmlType' => 'text',
479 'name' => 'bank_name',
480 'title' => ts('Bank Name'),
482 'attributes' => array(
485 'autocomplete' => 'off',
487 'is_required' => TRUE,
494 * Calling this from outside the payment subsystem is deprecated - use doPayment.
496 * Does a server to server payment transaction.
498 * Note that doPayment will throw an exception so the code may need to be modified
500 * @param array $params
501 * Assoc array of input parameters for this transaction.
504 * the result in an nice formatted array (or an error object)
507 abstract protected function doDirectPayment(&$params);
510 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
512 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
515 * Payment processors should set contribution_status_id. This function adds some historical defaults ie. the
516 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
517 * doTransferCheckout would not traditionally come back.
519 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
522 * @param array $params
524 * @param string $component
529 * @throws \Civi\Payment\Exception\PaymentProcessorException
531 public function doPayment(&$params, $component = 'contribute') {
532 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
533 if ($this->_paymentProcessor
['billing_mode'] == 4) {
534 $result = $this->doTransferCheckout($params, $component);
535 if (is_array($result) && !isset($result['contribution_status_id'])) {
536 $result['contribution_status_id'] = array_search('Pending', $statuses);
540 $result = $this->doDirectPayment($params, $component);
541 if (is_array($result) && !isset($result['contribution_status_id'])) {
542 if (!empty($params['is_recur'])) {
543 // See comment block.
544 $paymentParams['contribution_status_id'] = array_search('Pending', $statuses);
547 $result['contribution_status_id'] = array_search('Completed', $statuses);
551 if (is_a($result, 'CRM_Core_Error')) {
552 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
558 * This function checks to see if we have the right config values.
561 * the error message if any
563 abstract protected function checkConfig();
566 * Redirect for paypal.
568 * @todo move to paypal class or remove
570 * @param $paymentProcessor
574 public static function paypalRedirect(&$paymentProcessor) {
575 if (!$paymentProcessor) {
579 if (isset($_GET['payment_date']) &&
580 isset($_GET['merchant_return_link']) &&
581 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
582 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
591 * Handle incoming payment notification.
593 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
595 * @todo move to0 \Civi\Payment\System factory method
596 * Page callback for civicrm/payment/ipn
598 public static function handleIPN() {
599 self
::handlePaymentMethod(
600 'PaymentNotification',
602 'processor_name' => @$_GET['processor_name'],
603 'processor_id' => @$_GET['processor_id'],
604 'mode' => @$_GET['mode'],
608 CRM_Utils_System
::civiExit();
612 * Payment callback handler.
614 * The processor_name or processor_id is passed in.
615 * Note that processor_id is more reliable as one site may have more than one instance of a
616 * processor & ideally the processor will be validating the results
617 * Load requested payment processor and call that processor's handle<$method> method
619 * @todo move to \Civi\Payment\System factory method
621 * @param string $method
622 * 'PaymentNotification' or 'PaymentCron'
623 * @param array $params
625 public static function handlePaymentMethod($method, $params = array()) {
626 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
627 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
628 $lastParam = array_pop($q);
629 if (is_numeric($lastParam)) {
630 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
633 throw new CRM_Core_Exception("Either 'processor_id' or 'processor_name' param is required for payment callback");
637 self
::logPaymentNotification($params);
639 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
640 FROM civicrm_payment_processor_type ppt
641 INNER JOIN civicrm_payment_processor pp
642 ON pp.payment_processor_type_id = ppt.id
645 if (isset($params['processor_id'])) {
646 $sql .= " WHERE pp.id = %2";
647 $args[2] = array($params['processor_id'], 'Integer');
648 $notFound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
651 // This is called when processor_name is passed - passing processor_id instead is recommended.
652 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
654 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
657 $args[2] = array($params['processor_name'], 'String');
658 $notFound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
661 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
663 // Check whether we found anything at all.
665 CRM_Core_Error
::fatal($notFound);
668 $method = 'handle' . $method;
669 $extension_instance_found = FALSE;
671 // In all likelihood, we'll just end up with the one instance returned here. But it's
672 // possible we may get more. Hence, iterate through all instances ..
674 while ($dao->fetch()) {
675 // Check pp is extension
676 $ext = CRM_Extension_System
::singleton()->getMapper();
677 if ($ext->isExtensionKey($dao->class_name
)) {
678 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
679 require_once $ext->classToPath($paymentClass);
682 // Legacy or extension as module instance
683 $paymentClass = 'CRM_Core_' . $dao->class_name
;
686 $processorInstance = Civi\Payment\System
::singleton()->getById($dao->processor_id
);
688 // Should never be empty - we already established this processor_id exists and is active.
689 if (empty($processorInstance)) {
693 // Does PP implement this method, and can we call it?
694 if (!method_exists($processorInstance, $method) ||
695 !is_callable(array($processorInstance, $method))
697 // on the off chance there is a double implementation of this processor we should keep looking for another
698 // note that passing processor_id is more reliable & we should work to deprecate processor_name
702 // Everything, it seems, is ok - execute pp callback handler
703 $processorInstance->$method();
704 $extension_instance_found = TRUE;
707 if (!$extension_instance_found) {
708 CRM_Core_Error
::fatal(
709 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
710 "$method method is unsupported in legacy payment processors."
716 * Check whether a method is present ( & supported ) by the payment processor object.
718 * @param string $method
719 * Method to check for.
723 public function isSupported($method = 'cancelSubscription') {
724 return method_exists(CRM_Utils_System
::getClassName($this), $method);
728 * Some processors replace the form submit button with their own.
730 * Returning false here will leave the button off front end forms.
732 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
734 public function isSuppressSubmitButtons() {
739 * Get url for users to manage this recurring contribution for this processor.
741 * @param int $entityID
742 * @param null $entity
743 * @param string $action
747 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
751 $url = 'civicrm/contribute/unsubscribe';
755 //in notify mode don't return the update billing url
756 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
759 $url = 'civicrm/contribute/updatebilling';
763 $url = 'civicrm/contribute/updaterecur';
767 $session = CRM_Core_Session
::singleton();
768 $userId = $session->get('userID');
773 // Find related Contact
777 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
782 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
788 SELECT con.contact_id
789 FROM civicrm_contribution_recur rec
790 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
793 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
799 // Add entity arguments
800 if ($entityArg != '') {
801 // Add checksum argument
802 if ($contactID != 0 && $userId != $contactID) {
803 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
805 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
809 if ($this->isSupported('accountLoginURL')) {
810 return $this->accountLoginURL();
814 return $this->_paymentProcessor
['url_recur'];