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 +--------------------------------------------------------------------+
28 use Civi\Payment\System
;
31 * Class CRM_Core_Payment.
33 * This class is the main class for the payment processor subsystem.
35 * It is the parent class for payment processors. It also holds some IPN related functions
36 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
38 abstract class CRM_Core_Payment
{
41 * How are we getting billing information?
43 * FORM - we collect it on the same page
44 * BUTTON - the processor collects it and sends it back to us via some protocol
47 BILLING_MODE_FORM
= 1,
48 BILLING_MODE_BUTTON
= 2,
49 BILLING_MODE_NOTIFY
= 4;
52 * Which payment type(s) are we using?
57 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
60 PAYMENT_TYPE_CREDIT_CARD
= 1,
61 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
64 * Subscription / Recurring payment Status
68 RECURRING_PAYMENT_START
= 'START',
69 RECURRING_PAYMENT_END
= 'END';
71 protected $_paymentProcessor;
74 * Singleton function used to manage this object.
76 * We will migrate to calling Civi\Payment\System::singleton()->getByProcessor($paymentProcessor)
77 * & Civi\Payment\System::singleton()->getById($paymentProcessor) directly as the main access methods & work
78 * to remove this function all together
81 * The mode of operation: live or test.
82 * @param array $paymentProcessor
83 * The details of the payment processor being invoked.
84 * @param object $paymentForm
85 * Deprecated - avoid referring to this if possible. If you have to use it document why as this is scary interaction.
87 * Should we force a reload of this payment object.
89 * @return CRM_Core_Payment
90 * @throws \CRM_Core_Exception
92 public static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
93 // make sure paymentProcessor is not empty
95 if (empty($paymentProcessor)) {
96 return CRM_Core_DAO
::$_nullObject;
98 //we use two lines because we can't remove the '&singleton' without risking breakage
99 //of extension classes that extend this one
100 $object = Civi\Payment\System
::singleton()->getByProcessor($paymentProcessor);
105 * Log payment notification message to forensic system log.
107 * @todo move to factory class \Civi\Payment\System (or similar)
109 * @param array $params
113 public static function logPaymentNotification($params) {
114 $message = 'payment_notification ';
115 if (!empty($params['processor_name'])) {
116 $message .= 'processor_name=' . $params['processor_name'];
118 if (!empty($params['processor_id'])) {
119 $message .= 'processor_id=' . $params['processor_id'];
122 $log = new CRM_Utils_SystemLogger();
123 $log->alert($message, $_REQUEST);
127 * Check if capability is supported.
129 * Capabilities have a one to one relationship with capability-related functions on this class.
131 * Payment processor classes should over-ride the capability-specific function rather than this one.
133 * @param string $capability
134 * E.g BackOffice, LiveMode, FutureRecurStartDate.
138 public function supports($capability) {
139 $function = 'supports' . ucfirst($capability);
140 if (method_exists($this, $function)) {
141 return $this->$function();
147 * Are back office payments supported.
149 * e.g paypal standard won't permit you to enter a credit card associated
150 * with someone else's login.
151 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
152 * reach a 'stable' point we disable.
156 protected function supportsBackOffice() {
157 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
166 * Are live payments supported - e.g dummy doesn't support this.
170 protected function supportsLiveMode() {
175 * Are test payments supported.
179 protected function supportsTestMode() {
184 * Should the first payment date be configurable when setting up back office recurring payments.
186 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
190 protected function supportsFutureRecurStartDate() {
195 * Default payment instrument validation.
197 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
198 * Not a static function, because I need to check for payment_type.
200 * @param array $values
201 * @param array $errors
203 public function validatePaymentInstrument($values, &$errors) {
204 if ($this->_paymentProcessor
['payment_type'] == 1) {
205 CRM_Core_Payment_Form
::validateCreditCard($values, $errors);
210 * Setter for the payment form that wants to use the processor.
214 * @param CRM_Core_Form $paymentForm
216 public function setForm(&$paymentForm) {
217 $this->_paymentForm
= $paymentForm;
221 * Getter for payment form that is using the processor.
223 * @return CRM_Core_Form
226 public function getForm() {
227 return $this->_paymentForm
;
231 * Getter for accessing member vars.
233 * @todo believe this is unused
235 * @param string $name
239 public function getVar($name) {
240 return isset($this->$name) ?
$this->$name : NULL;
244 * Get name for the payment information type.
245 * @todo - use option group + name field (like Omnipay does)
248 public function getPaymentTypeName() {
249 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
253 * Get label for the payment information type.
254 * @todo - use option group + labels (like Omnipay does)
257 public function getPaymentTypeLabel() {
258 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
262 * Get array of fields that should be displayed on the payment form.
263 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
265 * @throws CiviCRM_API3_Exception
267 public function getPaymentFormFields() {
268 if ($this->_paymentProcessor
['billing_mode'] == 4) {
271 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
275 * Get array of fields that should be displayed on the payment form for credit cards.
279 protected function getCreditCardFormFields() {
282 'credit_card_number',
284 'credit_card_exp_date',
289 * Get array of fields that should be displayed on the payment form for direct debits.
293 protected function getDirectDebitFormFields() {
296 'bank_account_number',
297 'bank_identification_number',
303 * Return an array of all the details about the fields potentially required for payment fields.
305 * Only those determined by getPaymentFormFields will actually be assigned to the form
310 public function getPaymentFormFieldsMetadata() {
311 //@todo convert credit card type into an option value
312 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
314 'credit_card_number' => array(
315 'htmlType' => 'text',
316 'name' => 'credit_card_number',
317 'title' => ts('Card Number'),
319 'attributes' => array(
322 'autocomplete' => 'off',
323 'class' => 'creditcard',
325 'is_required' => TRUE,
328 'htmlType' => 'text',
330 'title' => ts('Security Code'),
332 'attributes' => array(
335 'autocomplete' => 'off',
337 'is_required' => CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,
338 'cvv_backoffice_required',
344 '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.'),
345 'rule_name' => 'integer',
346 'rule_parameters' => NULL,
350 'credit_card_exp_date' => array(
351 'htmlType' => 'date',
352 'name' => 'credit_card_exp_date',
353 'title' => ts('Expiration Date'),
355 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
356 'is_required' => TRUE,
359 'rule_message' => ts('Card expiration date cannot be a past date.'),
360 'rule_name' => 'currentDate',
361 'rule_parameters' => TRUE,
365 'credit_card_type' => array(
366 'htmlType' => 'select',
367 'name' => 'credit_card_type',
368 'title' => ts('Card Type'),
370 'attributes' => $creditCardType,
371 'is_required' => FALSE,
373 'account_holder' => array(
374 'htmlType' => 'text',
375 'name' => 'account_holder',
376 'title' => ts('Account Holder'),
378 'attributes' => array(
381 'autocomplete' => 'on',
383 'is_required' => TRUE,
385 //e.g. IBAN can have maxlength of 34 digits
386 'bank_account_number' => array(
387 'htmlType' => 'text',
388 'name' => 'bank_account_number',
389 'title' => ts('Bank Account Number'),
391 'attributes' => array(
394 'autocomplete' => 'off',
398 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
399 'rule_name' => 'nopunctuation',
400 'rule_parameters' => NULL,
403 'is_required' => TRUE,
405 //e.g. SWIFT-BIC can have maxlength of 11 digits
406 'bank_identification_number' => array(
407 'htmlType' => 'text',
408 'name' => 'bank_identification_number',
409 'title' => ts('Bank Identification Number'),
411 'attributes' => array(
414 'autocomplete' => 'off',
416 'is_required' => TRUE,
419 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
420 'rule_name' => 'nopunctuation',
421 'rule_parameters' => NULL,
425 'bank_name' => array(
426 'htmlType' => 'text',
427 'name' => 'bank_name',
428 'title' => ts('Bank Name'),
430 'attributes' => array(
433 'autocomplete' => 'off',
435 'is_required' => TRUE,
442 * Calling this from outside the payment subsystem is deprecated - use doPayment.
444 * Does a server to server payment transaction.
446 * Note that doPayment will throw an exception so the code may need to be modified
448 * @param array $params
449 * Assoc array of input parameters for this transaction.
452 * the result in an nice formatted array (or an error object)
455 abstract protected function doDirectPayment(&$params);
458 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
460 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
463 * @param array $params
469 * @throws CRM_Core_Exception
471 public function doPayment(&$params, $component = 'contribute') {
472 if ($this->_paymentProcessor
['billing_mode'] == 4) {
473 $result = $this->doTransferCheckout($params, $component);
476 $result = $this->doDirectPayment($params, $component);
478 if (is_a($result, 'CRM_Core_Error')) {
479 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
481 //CRM-15767 - Submit Credit Card Contribution not being saved
486 * This function checks to see if we have the right config values.
489 * the error message if any
491 abstract protected function checkConfig();
494 * Redirect for paypal.
496 * @todo move to paypal class or remove
498 * @param $paymentProcessor
502 public static function paypalRedirect(&$paymentProcessor) {
503 if (!$paymentProcessor) {
507 if (isset($_GET['payment_date']) &&
508 isset($_GET['merchant_return_link']) &&
509 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
510 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
519 * Handle incoming payment notification.
521 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
523 * @todo move to0 \Civi\Payment\System factory method
524 * Page callback for civicrm/payment/ipn
526 public static function handleIPN() {
527 self
::handlePaymentMethod(
528 'PaymentNotification',
530 'processor_name' => @$_GET['processor_name'],
531 'processor_id' => @$_GET['processor_id'],
532 'mode' => @$_GET['mode'],
535 CRM_Utils_System
::civiExit();
539 * Payment callback handler.
541 * The processor_name or processor_id is passed in.
542 * Note that processor_id is more reliable as one site may have more than one instance of a
543 * processor & ideally the processor will be validating the results
544 * Load requested payment processor and call that processor's handle<$method> method
546 * @todo move to \Civi\Payment\System factory method
548 * @param string $method
549 * 'PaymentNotification' or 'PaymentCron'
550 * @param array $params
552 public static function handlePaymentMethod($method, $params = array()) {
553 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
554 CRM_Core_Error
::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
556 self
::logPaymentNotification($params);
558 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
559 FROM civicrm_payment_processor_type ppt
560 INNER JOIN civicrm_payment_processor pp
561 ON pp.payment_processor_type_id = ppt.id
564 if (isset($params['processor_id'])) {
565 $sql .= " WHERE pp.id = %2";
566 $args[2] = array($params['processor_id'], 'Integer');
567 $notFound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
570 // This is called when processor_name is passed - passing processor_id instead is recommended.
571 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
573 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
576 $args[2] = array($params['processor_name'], 'String');
577 $notFound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
580 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
582 // Check whether we found anything at all.
584 CRM_Core_Error
::fatal($notFound);
587 $method = 'handle' . $method;
588 $extension_instance_found = FALSE;
590 // In all likelihood, we'll just end up with the one instance returned here. But it's
591 // possible we may get more. Hence, iterate through all instances ..
593 while ($dao->fetch()) {
594 // Check pp is extension
595 $ext = CRM_Extension_System
::singleton()->getMapper();
596 if ($ext->isExtensionKey($dao->class_name
)) {
597 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
598 require_once $ext->classToPath($paymentClass);
601 // Legacy or extension as module instance
602 if (empty($paymentClass)) {
603 $paymentClass = 'CRM_Core_' . $dao->class_name
;
608 $processorInstance = Civi\Payment\System
::singleton()->getById($dao->processor_id
);
610 // Should never be empty - we already established this processor_id exists and is active.
611 if (empty($processorInstance)) {
615 // Does PP implement this method, and can we call it?
616 if (!method_exists($processorInstance, $method) ||
617 !is_callable(array($processorInstance, $method))
619 // on the off chance there is a double implementation of this processor we should keep looking for another
620 // note that passing processor_id is more reliable & we should work to deprecate processor_name
624 // Everything, it seems, is ok - execute pp callback handler
625 $processorInstance->$method();
626 $extension_instance_found = TRUE;
629 if (!$extension_instance_found) {
630 CRM_Core_Error
::fatal(
631 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
632 "$method method is unsupported in legacy payment processors."
638 * Check whether a method is present ( & supported ) by the payment processor object.
640 * @param string $method
641 * Method to check for.
645 public function isSupported($method = 'cancelSubscription') {
646 return method_exists(CRM_Utils_System
::getClassName($this), $method);
650 * Get url for users to manage this recurring contribution for this processor.
652 * @param int $entityID
653 * @param null $entity
654 * @param string $action
658 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
662 $url = 'civicrm/contribute/unsubscribe';
666 //in notify mode don't return the update billing url
667 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
670 $url = 'civicrm/contribute/updatebilling';
674 $url = 'civicrm/contribute/updaterecur';
678 $session = CRM_Core_Session
::singleton();
679 $userId = $session->get('userID');
684 // Find related Contact
688 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
693 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
699 SELECT con.contact_id
700 FROM civicrm_contribution_recur rec
701 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
704 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
710 // Add entity arguments
711 if ($entityArg != '') {
712 // Add checksum argument
713 if ($contactID != 0 && $userId != $contactID) {
714 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
716 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
720 if ($this->isSupported('accountLoginURL')) {
721 return $this->accountLoginURL();
725 return $this->_paymentProcessor
['url_recur'];