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
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
93 * @return \CRM_Core_Payment
94 * @throws \CRM_Core_Exception
97 public static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
98 // make sure paymentProcessor is not empty
100 if (empty($paymentProcessor)) {
101 return CRM_Core_DAO
::$_nullObject;
104 $cacheKey = "{$mode}_{$paymentProcessor['id']}_" . (int)isset($paymentForm);
106 if (!isset(self
::$_singleton[$cacheKey]) ||
$force) {
107 $config = CRM_Core_Config
::singleton();
108 $ext = CRM_Extension_System
::singleton()->getMapper();
109 if ($ext->isExtensionKey($paymentProcessor['class_name'])) {
110 $paymentClass = $ext->keyToClass($paymentProcessor['class_name'], 'payment');
111 require_once ($ext->classToPath($paymentClass));
114 $paymentClass = 'CRM_Core_' . $paymentProcessor['class_name'];
115 if (empty($paymentClass)) {
116 throw new CRM_Core_Exception('no class provided');
118 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $paymentClass) . '.php');
122 self
::$_singleton[$cacheKey] = $paymentClass::singleton($mode, $paymentProcessor);
125 //load the payment form for required processor.
126 //if ($paymentForm !== NULL) {
127 //self::$_singleton[$cacheKey]->setForm($paymentForm);
130 return self
::$_singleton[$cacheKey];
134 * @param array $params
138 public static function logPaymentNotification($params) {
139 $message = 'payment_notification ';
140 if (!empty($params['processor_name'])) {
141 $message .= 'processor_name=' . $params['processor_name'];
143 if (!empty($params['processor_id'])) {
144 $message .= 'processor_id=' . $params['processor_id'];
147 $log = new CRM_Utils_SystemLogger();
148 $log->alert($message, $_REQUEST);
152 * Check if capability is supported
153 * @param string $capability e.g BackOffice, LiveMode, FutureRecurStartDate
157 public function supports($capability) {
158 $function = 'supports' . ucfirst($capability);
159 if (method_exists($this, $function)) {
160 return $this->$function();
166 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
167 * 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
170 protected function supportsBackOffice() {
171 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
180 * Are live payments supported - e.g dummy doesn't support this
183 protected function supportsLiveMode() {
188 * Are test payments supported
191 protected function supportsTestMode() {
196 * 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
200 protected function supportsFutureRecurStartDate() {
205 * Setter for the payment form that wants to use the processor
207 * @param CRM_Core_Form $paymentForm
210 public function setForm(&$paymentForm) {
211 $this->_paymentForm
= $paymentForm;
215 * Getter for payment form that is using the processor
217 * @return CRM_Core_Form A form object
219 public function getForm() {
220 return $this->_paymentForm
;
224 * Getter for accessing member vars
226 * @param string $name
230 public function getVar($name) {
231 return isset($this->$name) ?
$this->$name : NULL;
235 * Get name for the payment information type
239 public function getPaymentTypeName() {
240 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
244 * Get label for the payment information type
248 public function getPaymentTypeLabel() {
249 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
253 * Get array of fields that should be displayed on the payment form
254 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
256 * @throws CiviCRM_API3_Exception
258 public function getPaymentFormFields() {
259 if ($this->_paymentProcessor
['billing_mode'] == 4) {
262 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
266 * Get array of fields that should be displayed on the payment form for credit cards
270 protected function getCreditCardFormFields() {
273 'credit_card_number',
275 'credit_card_exp_date',
280 * Get array of fields that should be displayed on the payment form for direct debits
284 protected function getDirectDebitFormFields() {
287 'bank_account_number',
288 'bank_identification_number',
294 * Return an array of all the details about the fields potentially required for payment fields
295 * Only those determined by getPaymentFormFields will actually be assigned to the form
297 * @return array field metadata
299 public function getPaymentFormFieldsMetadata() {
300 //@todo convert credit card type into an option value
301 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
303 'credit_card_number' => array(
304 'htmlType' => 'text',
305 'name' => 'credit_card_number',
306 'title' => ts('Card Number'),
308 'attributes' => array(
311 'autocomplete' => 'off'
313 'is_required' => TRUE,
316 'htmlType' => 'text',
318 'title' => ts('Security Code'),
320 'attributes' => array(
323 'autocomplete' => 'off'
325 'is_required' => CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,
326 'cvv_backoffice_required',
332 '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.'),
333 'rule_name' => 'integer',
334 'rule_parameters' => NULL,
337 'credit_card_exp_date' => array(
338 'htmlType' => 'date',
339 'name' => 'credit_card_exp_date',
340 'title' => ts('Expiration Date'),
342 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
343 'is_required' => TRUE,
346 'rule_message' => ts('Card expiration date cannot be a past date.'),
347 'rule_name' => 'currentDate',
348 'rule_parameters' => TRUE,
351 'credit_card_type' => array(
352 'htmlType' => 'select',
353 'name' => 'credit_card_type',
354 'title' => ts('Card Type'),
356 'attributes' => $creditCardType,
357 'is_required' => FALSE,
359 'account_holder' => array(
360 'htmlType' => 'text',
361 'name' => 'account_holder',
362 'title' => ts('Account Holder'),
364 'attributes' => array(
367 'autocomplete' => 'on'
369 'is_required' => TRUE,
371 //e.g. IBAN can have maxlength of 34 digits
372 'bank_account_number' => array(
373 'htmlType' => 'text',
374 'name' => 'bank_account_number',
375 'title' => ts('Bank Account Number'),
377 'attributes' => array(
380 'autocomplete' => 'off'
384 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
385 'rule_name' => 'nopunctuation',
386 'rule_parameters' => NULL,
388 'is_required' => TRUE,
390 //e.g. SWIFT-BIC can have maxlength of 11 digits
391 'bank_identification_number' => array(
392 'htmlType' => 'text',
393 'name' => 'bank_identification_number',
394 'title' => ts('Bank Identification Number'),
396 'attributes' => array(
399 'autocomplete' => 'off'
401 'is_required' => TRUE,
404 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
405 'rule_name' => 'nopunctuation',
406 'rule_parameters' => NULL,
409 'bank_name' => array(
410 'htmlType' => 'text',
411 'name' => 'bank_name',
412 'title' => ts('Bank Name'),
414 'attributes' => array(
417 'autocomplete' => 'off'
419 'is_required' => TRUE,
426 * This function collects all the information from a web/api form and invokes
427 * the relevant payment processor specific functions to perform the transaction
429 * @param array $params assoc array of input parameters for this transaction
431 * @return array the result in an nice formatted array (or an error object)
434 abstract function doDirectPayment(&$params);
437 * Process payment - this function wraps around both doTransferPayment and doDirectPayment
438 * it ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms more agnostic
440 * @param array $params
444 * @throws CRM_Core_Exception
446 public function doPayment(&$params, $component) {
447 if ($this->_paymentProcessor
['billing_mode'] == 4) {
448 $result = $this->doTransferCheckout($params, $component);
451 $result = $this->doDirectPayment($params, $component);
453 if (is_a($result, 'CRM_Core_Error')) {
454 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
456 //CRM-15767 - Submit Credit Card Contribution not being saved
461 * This function checks to see if we have the right config values
463 * @return string the error message if any
465 abstract function checkConfig();
468 * @param $paymentProcessor
472 public static function paypalRedirect(&$paymentProcessor) {
473 if (!$paymentProcessor) {
477 if (isset($_GET['payment_date']) &&
478 isset($_GET['merchant_return_link']) &&
479 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
480 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
489 * Page callback for civicrm/payment/ipn
491 public static function handleIPN() {
492 self
::handlePaymentMethod(
493 'PaymentNotification',
495 'processor_name' => @$_GET['processor_name'],
496 'processor_id' => @$_GET['processor_id'],
497 'mode' => @$_GET['mode'],
503 * Payment callback handler. The processor_name or processor_id is passed in.
504 * Note that processor_id is more reliable as one site may have more than one instance of a
505 * processor & ideally the processor will be validating the results
506 * Load requested payment processor and call that processor's handle<$method> method
509 * @param array $params
511 public static function handlePaymentMethod($method, $params = array()) {
512 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
513 CRM_Core_Error
::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
515 self
::logPaymentNotification($params);
517 // Query db for processor ..
518 $mode = @$params['mode'];
520 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
521 FROM civicrm_payment_processor_type ppt
522 INNER JOIN civicrm_payment_processor pp
523 ON pp.payment_processor_type_id = ppt.id
525 AND pp.is_test = %1";
526 $args[1] = array($mode == 'test' ?
1 : 0, 'Integer');
528 if (isset($params['processor_id'])) {
529 $sql .= " WHERE pp.id = %2";
530 $args[2] = array($params['processor_id'], 'Integer');
531 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
534 $sql .= " WHERE ppt.name = %2";
535 $args[2] = array($params['processor_name'], 'String');
536 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
539 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
541 // Check whether we found anything at all ..
543 CRM_Core_Error
::fatal($notfound);
546 $method = 'handle' . $method;
547 $extension_instance_found = FALSE;
549 // In all likelihood, we'll just end up with the one instance returned here. But it's
550 // possible we may get more. Hence, iterate through all instances ..
552 while ($dao->fetch()) {
553 // Check pp is extension
554 $ext = CRM_Extension_System
::singleton()->getMapper();
555 if ($ext->isExtensionKey($dao->class_name
)) {
556 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
557 require_once $ext->classToPath($paymentClass);
560 // Legacy or extension as module instance
561 if (empty($paymentClass)) {
562 $paymentClass = 'CRM_Core_' . $dao->class_name
;
567 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($dao->processor_id
, $mode);
569 // Should never be empty - we already established this processor_id exists and is active.
570 if (empty($paymentProcessor)) {
575 $processorInstance = $paymentClass::singleton($mode, $paymentProcessor);
577 // Does PP implement this method, and can we call it?
578 if (!method_exists($processorInstance, $method) ||
579 !is_callable(array($processorInstance, $method))
581 // on the off chance there is a double implementation of this processor we should keep looking for another
582 // note that passing processor_id is more reliable & we should work to deprecate processor_name
586 // Everything, it seems, is ok - execute pp callback handler
587 $processorInstance->$method();
588 $extension_instance_found = TRUE;
591 if (!$extension_instance_found) CRM_Core_Error
::fatal(
592 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
593 "$method method is unsupported in legacy payment processors."
596 // Exit here on web requests, allowing just the plain text response to be echoed
597 if ($method == 'handlePaymentNotification') {
598 CRM_Utils_System
::civiExit();
603 * Check whether a method is present ( & supported ) by the payment processor object.
605 * @param string $method method to check for.
609 public function isSupported($method = 'cancelSubscription') {
610 return method_exists(CRM_Utils_System
::getClassName($this), $method);
614 * @param int $entityID
615 * @param null $entity
616 * @param string $action
620 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
624 $url = 'civicrm/contribute/unsubscribe';
627 //in notify mode don't return the update billing url
628 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
631 $url = 'civicrm/contribute/updatebilling';
634 $url = 'civicrm/contribute/updaterecur';
638 $session = CRM_Core_Session
::singleton();
639 $userId = $session->get('userID');
644 // Find related Contact
648 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
652 case 'contribution' :
653 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
659 SELECT con.contact_id
660 FROM civicrm_contribution_recur rec
661 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
664 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
670 // Add entity arguments
671 if ($entityArg != '') {
672 // Add checksum argument
673 if ($contactID != 0 && $userId != $contactID) {
674 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
676 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
680 if ($this->isSupported('accountLoginURL')) {
681 return $this->accountLoginURL();
685 return $this->_paymentProcessor
['url_recur'];