3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
36 abstract class CRM_Core_Payment
{
39 * How are we getting billing information?
41 * FORM - we collect it on the same page
42 * BUTTON - the processor collects it and sends it back to us via some protocol
45 BILLING_MODE_FORM
= 1,
46 BILLING_MODE_BUTTON
= 2,
47 BILLING_MODE_NOTIFY
= 4;
50 * Which payment type(s) are we using?
58 PAYMENT_TYPE_CREDIT_CARD
= 1,
59 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
62 * Subscription / Recurring payment Status
67 RECURRING_PAYMENT_START
= 'START',
68 RECURRING_PAYMENT_END
= 'END';
71 * We only need one instance of this object. So we use the singleton
72 * pattern and cache the instance in this variable
77 static private $_singleton = NULL;
79 protected $_paymentProcessor;
84 protected $_paymentForm = NULL;
87 * Singleton function used to manage this object
90 * The mode of operation: live or test.
91 * @param array $paymentProcessor
92 * The details of the payment processor being invoked.
93 * @param object $paymentForm
94 * Deprecated - avoid referring to this if possible. If you have to use it document why as this is scary interaction.
96 * Should we force a reload of this payment object.
98 * @return CRM_Core_Payment
99 * @return \CRM_Core_Payment
100 * @throws \CRM_Core_Exception
103 public static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
104 // make sure paymentProcessor is not empty
106 if (empty($paymentProcessor)) {
107 return CRM_Core_DAO
::$_nullObject;
110 $cacheKey = "{$mode}_{$paymentProcessor['id']}_" . (int) isset($paymentForm);
112 if (!isset(self
::$_singleton[$cacheKey]) ||
$force) {
113 $config = CRM_Core_Config
::singleton();
114 $ext = CRM_Extension_System
::singleton()->getMapper();
115 if ($ext->isExtensionKey($paymentProcessor['class_name'])) {
116 $paymentClass = $ext->keyToClass($paymentProcessor['class_name'], 'payment');
117 require_once $ext->classToPath($paymentClass);
120 $paymentClass = 'CRM_Core_' . $paymentProcessor['class_name'];
121 if (empty($paymentClass)) {
122 throw new CRM_Core_Exception('no class provided');
124 require_once str_replace('_', DIRECTORY_SEPARATOR
, $paymentClass) . '.php';
128 self
::$_singleton[$cacheKey] = $paymentClass::singleton($mode, $paymentProcessor);
131 //load the payment form for required processor.
132 //if ($paymentForm !== NULL) {
133 //self::$_singleton[$cacheKey]->setForm($paymentForm);
136 return self
::$_singleton[$cacheKey];
140 * @param array $params
144 public static function logPaymentNotification($params) {
145 $message = 'payment_notification ';
146 if (!empty($params['processor_name'])) {
147 $message .= 'processor_name=' . $params['processor_name'];
149 if (!empty($params['processor_id'])) {
150 $message .= 'processor_id=' . $params['processor_id'];
153 $log = new CRM_Utils_SystemLogger();
154 $log->alert($message, $_REQUEST);
158 * Check if capability is supported
159 * @param string $capability
160 * E.g BackOffice, LiveMode, FutureRecurStartDate.
164 public function supports($capability) {
165 $function = 'supports' . ucfirst($capability);
166 if (method_exists($this, $function)) {
167 return $this->$function();
173 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
174 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to reach a 'stable' point we disable
177 protected function supportsBackOffice() {
178 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
187 * Are live payments supported - e.g dummy doesn't support this
190 protected function supportsLiveMode() {
195 * Are test payments supported
198 protected function supportsTestMode() {
203 * Should the first payment date be configurable when setting up back office recurring payments
204 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
207 protected function supportsFutureRecurStartDate() {
212 * Setter for the payment form that wants to use the processor
214 * @param CRM_Core_Form $paymentForm
217 public function setForm(&$paymentForm) {
218 $this->_paymentForm
= $paymentForm;
222 * Getter for payment form that is using the processor
224 * @return CRM_Core_Form A form object
226 public function getForm() {
227 return $this->_paymentForm
;
231 * Getter for accessing member vars
233 * @param string $name
237 public function getVar($name) {
238 return isset($this->$name) ?
$this->$name : NULL;
242 * Get name for the payment information type
246 public function getPaymentTypeName() {
247 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
251 * Get label for the payment information type
255 public function getPaymentTypeLabel() {
256 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
260 * Get array of fields that should be displayed on the payment form
261 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
263 * @throws CiviCRM_API3_Exception
265 public function getPaymentFormFields() {
266 if ($this->_paymentProcessor
['billing_mode'] == 4) {
269 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
273 * Get array of fields that should be displayed on the payment form for credit cards
277 protected function getCreditCardFormFields() {
280 'credit_card_number',
282 'credit_card_exp_date',
287 * Get array of fields that should be displayed on the payment form for direct debits
291 protected function getDirectDebitFormFields() {
294 'bank_account_number',
295 'bank_identification_number',
301 * Return an array of all the details about the fields potentially required for payment fields
302 * Only those determined by getPaymentFormFields will actually be assigned to the form
304 * @return array field metadata
306 public function getPaymentFormFieldsMetadata() {
307 //@todo convert credit card type into an option value
308 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
310 'credit_card_number' => array(
311 'htmlType' => 'text',
312 'name' => 'credit_card_number',
313 'title' => ts('Card Number'),
315 'attributes' => array(
318 'autocomplete' => 'off'
320 'is_required' => TRUE,
323 'htmlType' => 'text',
325 'title' => ts('Security Code'),
327 'attributes' => array(
330 'autocomplete' => 'off'
332 'is_required' => CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,
333 'cvv_backoffice_required',
339 '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.'),
340 'rule_name' => 'integer',
341 'rule_parameters' => NULL,
344 'credit_card_exp_date' => array(
345 'htmlType' => 'date',
346 'name' => 'credit_card_exp_date',
347 'title' => ts('Expiration Date'),
349 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
350 'is_required' => TRUE,
353 'rule_message' => ts('Card expiration date cannot be a past date.'),
354 'rule_name' => 'currentDate',
355 'rule_parameters' => TRUE,
358 'credit_card_type' => array(
359 'htmlType' => 'select',
360 'name' => 'credit_card_type',
361 'title' => ts('Card Type'),
363 'attributes' => $creditCardType,
364 'is_required' => FALSE,
366 'account_holder' => array(
367 'htmlType' => 'text',
368 'name' => 'account_holder',
369 'title' => ts('Account Holder'),
371 'attributes' => array(
374 'autocomplete' => 'on'
376 'is_required' => TRUE,
378 //e.g. IBAN can have maxlength of 34 digits
379 'bank_account_number' => array(
380 'htmlType' => 'text',
381 'name' => 'bank_account_number',
382 'title' => ts('Bank Account Number'),
384 'attributes' => array(
387 'autocomplete' => 'off'
391 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
392 'rule_name' => 'nopunctuation',
393 'rule_parameters' => NULL,
395 'is_required' => TRUE,
397 //e.g. SWIFT-BIC can have maxlength of 11 digits
398 'bank_identification_number' => array(
399 'htmlType' => 'text',
400 'name' => 'bank_identification_number',
401 'title' => ts('Bank Identification Number'),
403 'attributes' => array(
406 'autocomplete' => 'off'
408 'is_required' => TRUE,
411 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
412 'rule_name' => 'nopunctuation',
413 'rule_parameters' => NULL,
416 'bank_name' => array(
417 'htmlType' => 'text',
418 'name' => 'bank_name',
419 'title' => ts('Bank Name'),
421 'attributes' => array(
424 'autocomplete' => 'off'
426 'is_required' => TRUE,
433 * This function collects all the information from a web/api form and invokes
434 * the relevant payment processor specific functions to perform the transaction
436 * @param array $params
437 * Assoc array of input parameters for this transaction.
439 * @return array the result in an nice formatted array (or an error object)
442 abstract function doDirectPayment(&$params);
445 * Process payment - this function wraps around both doTransferPayment and doDirectPayment
446 * it ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms more agnostic
448 * @param array $params
452 * @throws CRM_Core_Exception
454 public function doPayment(&$params, $component) {
455 if ($this->_paymentProcessor
['billing_mode'] == 4) {
456 $result = $this->doTransferCheckout($params, $component);
459 $result = $this->doDirectPayment($params, $component);
461 if (is_a($result, 'CRM_Core_Error')) {
462 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
464 //CRM-15767 - Submit Credit Card Contribution not being saved
469 * This function checks to see if we have the right config values
471 * @return string the error message if any
473 abstract function checkConfig();
476 * @param $paymentProcessor
480 public static function paypalRedirect(&$paymentProcessor) {
481 if (!$paymentProcessor) {
485 if (isset($_GET['payment_date']) &&
486 isset($_GET['merchant_return_link']) &&
487 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
488 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
497 * Page callback for civicrm/payment/ipn
499 public static function handleIPN() {
500 self
::handlePaymentMethod(
501 'PaymentNotification',
503 'processor_name' => @$_GET['processor_name'],
504 'processor_id' => @$_GET['processor_id'],
505 'mode' => @$_GET['mode'],
511 * Payment callback handler. The processor_name or processor_id is passed in.
512 * Note that processor_id is more reliable as one site may have more than one instance of a
513 * processor & ideally the processor will be validating the results
514 * Load requested payment processor and call that processor's handle<$method> method
517 * @param array $params
519 public static function handlePaymentMethod($method, $params = array()) {
520 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
521 CRM_Core_Error
::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
523 self
::logPaymentNotification($params);
525 // Query db for processor ..
526 $mode = @$params['mode'];
528 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
529 FROM civicrm_payment_processor_type ppt
530 INNER JOIN civicrm_payment_processor pp
531 ON pp.payment_processor_type_id = ppt.id
533 AND pp.is_test = %1";
534 $args[1] = array($mode == 'test' ?
1 : 0, 'Integer');
536 if (isset($params['processor_id'])) {
537 $sql .= " WHERE pp.id = %2";
538 $args[2] = array($params['processor_id'], 'Integer');
539 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
542 $sql .= " WHERE ppt.name = %2";
543 $args[2] = array($params['processor_name'], 'String');
544 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
547 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
549 // Check whether we found anything at all ..
551 CRM_Core_Error
::fatal($notfound);
554 $method = 'handle' . $method;
555 $extension_instance_found = FALSE;
557 // In all likelihood, we'll just end up with the one instance returned here. But it's
558 // possible we may get more. Hence, iterate through all instances ..
560 while ($dao->fetch()) {
561 // Check pp is extension
562 $ext = CRM_Extension_System
::singleton()->getMapper();
563 if ($ext->isExtensionKey($dao->class_name
)) {
564 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
565 require_once $ext->classToPath($paymentClass);
568 // Legacy or extension as module instance
569 if (empty($paymentClass)) {
570 $paymentClass = 'CRM_Core_' . $dao->class_name
;
575 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($dao->processor_id
, $mode);
577 // Should never be empty - we already established this processor_id exists and is active.
578 if (empty($paymentProcessor)) {
583 $processorInstance = $paymentClass::singleton($mode, $paymentProcessor);
585 // Does PP implement this method, and can we call it?
586 if (!method_exists($processorInstance, $method) ||
587 !is_callable(array($processorInstance, $method))
589 // on the off chance there is a double implementation of this processor we should keep looking for another
590 // note that passing processor_id is more reliable & we should work to deprecate processor_name
594 // Everything, it seems, is ok - execute pp callback handler
595 $processorInstance->$method();
596 $extension_instance_found = TRUE;
599 if (!$extension_instance_found) { CRM_Core_Error
::fatal(
600 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
601 "$method method is unsupported in legacy payment processors."
605 // Exit here on web requests, allowing just the plain text response to be echoed
606 if ($method == 'handlePaymentNotification') {
607 CRM_Utils_System
::civiExit();
612 * Check whether a method is present ( & supported ) by the payment processor object.
614 * @param string $method
615 * Method to check for.
619 public function isSupported($method = 'cancelSubscription') {
620 return method_exists(CRM_Utils_System
::getClassName($this), $method);
624 * @param int $entityID
625 * @param null $entity
626 * @param string $action
630 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
634 $url = 'civicrm/contribute/unsubscribe';
638 //in notify mode don't return the update billing url
639 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
642 $url = 'civicrm/contribute/updatebilling';
646 $url = 'civicrm/contribute/updaterecur';
650 $session = CRM_Core_Session
::singleton();
651 $userId = $session->get('userID');
656 // Find related Contact
660 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
665 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
671 SELECT con.contact_id
672 FROM civicrm_contribution_recur rec
673 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
676 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
682 // Add entity arguments
683 if ($entityArg != '') {
684 // Add checksum argument
685 if ($contactID != 0 && $userId != $contactID) {
686 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
688 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
692 if ($this->isSupported('accountLoginURL')) {
693 return $this->accountLoginURL();
697 return $this->_paymentProcessor
['url_recur'];