3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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
89 * @param string $mode the mode of operation: live or test
90 * @param array $paymentProcessor the details of the payment processor being invoked
91 * @param object $paymentForm deprecated - avoid referring to this if possible. If you have to use it document why as this is scary interaction
92 * @param boolean $force should we force a reload of this payment object
94 * @return CRM_Core_Payment
98 static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
99 // make sure paymentProcessor is not empty
101 if (empty($paymentProcessor)) {
102 return CRM_Core_DAO
::$_nullObject;
105 $cacheKey = "{$mode}_{$paymentProcessor['id']}_" . (int)isset($paymentForm);
107 if (!isset(self
::$_singleton[$cacheKey]) ||
$force) {
108 $config = CRM_Core_Config
::singleton();
109 $ext = CRM_Extension_System
::singleton()->getMapper();
110 if ($ext->isExtensionKey($paymentProcessor['class_name'])) {
111 $paymentClass = $ext->keyToClass($paymentProcessor['class_name'], 'payment');
112 require_once ($ext->classToPath($paymentClass));
115 $paymentClass = 'CRM_Core_' . $paymentProcessor['class_name'];
116 if (empty($paymentClass)) {
117 throw new CRM_Core_Exception('no class provided');
119 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $paymentClass) . '.php');
123 self
::$_singleton[$cacheKey] = $paymentClass::singleton($mode, $paymentProcessor);
126 //load the payment form for required processor.
127 //if ($paymentForm !== NULL) {
128 //self::$_singleton[$cacheKey]->setForm($paymentForm);
131 return self
::$_singleton[$cacheKey];
135 * @param array $params
139 public static function logPaymentNotification($params) {
140 $message = 'payment_notification ';
141 if (!empty($params['processor_name'])) {
142 $message .= 'processor_name=' . $params['processor_name'];
144 if (!empty($params['processor_id'])) {
145 $message .= 'processor_id=' . $params['processor_id'];
148 $log = new CRM_Utils_SystemLogger();
149 $log->alert($message, $_REQUEST);
153 * Check if capability is supported
154 * @param string $capability e.g BackOffice, LiveMode, FutureRecurStartDate
158 public function supports($capability) {
159 $function = 'supports' . ucfirst($capability);
160 if (method_exists($this, $function)) {
161 return $this->$function();
167 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
168 * 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
171 protected function supportsBackOffice() {
172 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
181 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
184 protected function supportsLiveMode() {
189 * Should the first payment date be configurable when setting up back office recurring payments
190 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
193 protected function supportsFutureRecurStartDate() {
198 * Setter for the payment form that wants to use the processor
200 * @param CRM_Core_Form $paymentForm
203 function setForm(&$paymentForm) {
204 $this->_paymentForm
= $paymentForm;
208 * Getter for payment form that is using the processor
210 * @return CRM_Core_Form A form object
213 return $this->_paymentForm
;
217 * Getter for accessing member vars
219 * @param string $name
223 function getVar($name) {
224 return isset($this->$name) ?
$this->$name : NULL;
228 * Get name for the payment information type
232 public function getPaymentTypeName() {
233 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
237 * Get label for the payment information type
241 public function getPaymentTypeLabel() {
242 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
246 * Get array of fields that should be displayed on the payment form
247 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
249 * @throws CiviCRM_API3_Exception
251 public function getPaymentFormFields() {
252 if ($this->_paymentProcessor
['billing_mode'] == 4) {
255 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
259 * Get array of fields that should be displayed on the payment form for credit cards
263 protected function getCreditCardFormFields() {
266 'credit_card_number',
268 'credit_card_exp_date',
273 * Get array of fields that should be displayed on the payment form for direct debits
277 protected function getDirectDebitFormFields() {
280 'bank_account_number',
281 'bank_identification_number',
287 * Return an array of all the details about the fields potentially required for payment fields
288 * Only those determined by getPaymentFormFields will actually be assigned to the form
290 * @return array field metadata
292 public function getPaymentFormFieldsMetadata() {
293 //@todo convert credit card type into an option value
294 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
296 'credit_card_number' => array(
297 'htmlType' => 'text',
298 'name' => 'credit_card_number',
299 'title' => ts('Card Number'),
301 'attributes' => array(
304 'autocomplete' => 'off'
306 'is_required' => TRUE,
309 'htmlType' => 'text',
311 'title' => ts('Security Code'),
313 'attributes' => array(
316 'autocomplete' => 'off'
318 'is_required' => CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,
319 'cvv_backoffice_required',
325 '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.'),
326 'rule_name' => 'integer',
327 'rule_parameters' => NULL,
330 'credit_card_exp_date' => array(
331 'htmlType' => 'date',
332 'name' => 'credit_card_exp_date',
333 'title' => ts('Expiration Date'),
335 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
336 'is_required' => TRUE,
339 'rule_message' => ts('Card expiration date cannot be a past date.'),
340 'rule_name' => 'currentDate',
341 'rule_parameters' => TRUE,
344 'credit_card_type' => array(
345 'htmlType' => 'select',
346 'name' => 'credit_card_type',
347 'title' => ts('Card Type'),
349 'attributes' => $creditCardType,
350 'is_required' => FALSE,
352 'account_holder' => array(
353 'htmlType' => 'text',
354 'name' => 'account_holder',
355 'title' => ts('Account Holder'),
357 'attributes' => array(
360 'autocomplete' => 'on'
362 'is_required' => TRUE,
364 //e.g. IBAN can have maxlength of 34 digits
365 'bank_account_number' => array(
366 'htmlType' => 'text',
367 'name' => 'bank_account_number',
368 'title' => ts('Bank Account Number'),
370 'attributes' => array(
373 'autocomplete' => 'off'
377 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
378 'rule_name' => 'nopunctuation',
379 'rule_parameters' => NULL,
381 'is_required' => TRUE,
383 //e.g. SWIFT-BIC can have maxlength of 11 digits
384 'bank_identification_number' => array(
385 'htmlType' => 'text',
386 'name' => 'bank_identification_number',
387 'title' => ts('Bank Identification Number'),
389 'attributes' => array(
392 'autocomplete' => 'off'
394 'is_required' => TRUE,
397 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
398 'rule_name' => 'nopunctuation',
399 'rule_parameters' => NULL,
402 'bank_name' => array(
403 'htmlType' => 'text',
404 'name' => 'bank_name',
405 'title' => ts('Bank Name'),
407 'attributes' => array(
410 'autocomplete' => 'off'
412 'is_required' => TRUE,
419 * This function collects all the information from a web/api form and invokes
420 * the relevant payment processor specific functions to perform the transaction
422 * @param array $params assoc array of input parameters for this transaction
424 * @return array the result in an nice formatted array (or an error object)
427 abstract function doDirectPayment(&$params);
430 * Process payment - this function wraps around both doTransferPayment and doDirectPayment
431 * it ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms more agnostic
433 * @param array $params
437 * @throws CRM_Core_Exception
439 public function doPayment(&$params, $component) {
440 if ($this->_paymentProcessor
['billing_mode'] == 4) {
441 $result = $this->doTransferCheckout($params, $component);
444 $result = $this->doDirectPayment($params, $component);
446 if (is_a($result, 'CRM_Core_Error')) {
447 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
452 * This function checks to see if we have the right config values
454 * @return string the error message if any
457 abstract function checkConfig();
460 * @param $paymentProcessor
464 static function paypalRedirect(&$paymentProcessor) {
465 if (!$paymentProcessor) {
469 if (isset($_GET['payment_date']) &&
470 isset($_GET['merchant_return_link']) &&
471 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
472 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
481 * Page callback for civicrm/payment/ipn
484 static function handleIPN() {
485 self
::handlePaymentMethod(
486 'PaymentNotification',
488 'processor_name' => @$_GET['processor_name'],
489 'processor_id' => @$_GET['processor_id'],
490 'mode' => @$_GET['mode'],
496 * Payment callback handler. The processor_name or processor_id is passed in.
497 * Note that processor_id is more reliable as one site may have more than one instance of a
498 * processor & ideally the processor will be validating the results
499 * Load requested payment processor and call that processor's handle<$method> method
503 * @param array $params
505 static function handlePaymentMethod($method, $params = array()) {
506 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
507 CRM_Core_Error
::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
509 self
::logPaymentNotification($params);
511 // Query db for processor ..
512 $mode = @$params['mode'];
514 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
515 FROM civicrm_payment_processor_type ppt
516 INNER JOIN civicrm_payment_processor pp
517 ON pp.payment_processor_type_id = ppt.id
519 AND pp.is_test = %1";
520 $args[1] = array($mode == 'test' ?
1 : 0, 'Integer');
522 if (isset($params['processor_id'])) {
523 $sql .= " WHERE pp.id = %2";
524 $args[2] = array($params['processor_id'], 'Integer');
525 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
528 $sql .= " WHERE ppt.name = %2";
529 $args[2] = array($params['processor_name'], 'String');
530 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
533 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
535 // Check whether we found anything at all ..
537 CRM_Core_Error
::fatal($notfound);
540 $method = 'handle' . $method;
541 $extension_instance_found = FALSE;
543 // In all likelihood, we'll just end up with the one instance returned here. But it's
544 // possible we may get more. Hence, iterate through all instances ..
546 while ($dao->fetch()) {
547 // Check pp is extension
548 $ext = CRM_Extension_System
::singleton()->getMapper();
549 if ($ext->isExtensionKey($dao->class_name
)) {
550 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
551 require_once $ext->classToPath($paymentClass);
554 // Legacy or extension as module instance
555 if (empty($paymentClass)) {
556 $paymentClass = 'CRM_Core_' . $dao->class_name
;
561 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($dao->processor_id
, $mode);
563 // Should never be empty - we already established this processor_id exists and is active.
564 if (empty($paymentProcessor)) {
569 $processorInstance = $paymentClass::singleton($mode, $paymentProcessor);
571 // Does PP implement this method, and can we call it?
572 if (!method_exists($processorInstance, $method) ||
573 !is_callable(array($processorInstance, $method))
575 // on the off chance there is a double implementation of this processor we should keep looking for another
576 // note that passing processor_id is more reliable & we should work to deprecate processor_name
580 // Everything, it seems, is ok - execute pp callback handler
581 $processorInstance->$method();
582 $extension_instance_found = TRUE;
585 if (!$extension_instance_found) CRM_Core_Error
::fatal(
586 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
587 "$method method is unsupported in legacy payment processors."
590 // Exit here on web requests, allowing just the plain text response to be echoed
591 if ($method == 'handlePaymentNotification') {
592 CRM_Utils_System
::civiExit();
597 * Check whether a method is present ( & supported ) by the payment processor object.
599 * @param string $method method to check for.
604 function isSupported($method = 'cancelSubscription') {
605 return method_exists(CRM_Utils_System
::getClassName($this), $method);
609 * @param int $entityID
610 * @param null $entity
611 * @param string $action
615 function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
619 $url = 'civicrm/contribute/unsubscribe';
622 //in notify mode don't return the update billing url
623 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
626 $url = 'civicrm/contribute/updatebilling';
629 $url = 'civicrm/contribute/updaterecur';
633 $session = CRM_Core_Session
::singleton();
634 $userId = $session->get('userID');
639 // Find related Contact
643 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
647 case 'contribution' :
648 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
654 SELECT con.contact_id
655 FROM civicrm_contribution_recur rec
656 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
659 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
665 // Add entity arguments
666 if ($entityArg != '') {
667 // Add checksum argument
668 if ($contactID != 0 && $userId != $contactID) {
669 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
671 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
675 if ($this->isSupported('accountLoginURL')) {
676 return $this->accountLoginURL();
680 return $this->_paymentProcessor
['url_recur'];