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
;
33 * @copyright CiviCRM LLC (c) 2004-2014
37 abstract class CRM_Core_Payment
{
40 * How are we getting billing information?
42 * FORM - we collect it on the same page
43 * BUTTON - the processor collects it and sends it back to us via some protocol
46 BILLING_MODE_FORM
= 1,
47 BILLING_MODE_BUTTON
= 2,
48 BILLING_MODE_NOTIFY
= 4;
51 * Which payment type(s) are we using?
56 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
59 PAYMENT_TYPE_CREDIT_CARD
= 1,
60 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
63 * Subscription / Recurring payment Status
67 RECURRING_PAYMENT_START
= 'START',
68 RECURRING_PAYMENT_END
= 'END';
70 protected $_paymentProcessor;
73 * Singleton function used to manage this object
74 * We will migrate to calling Civi\Payment\System::singleton()->getByProcessor($paymentProcessor)
75 * & Civi\Payment\System::singleton()->getById($paymentProcessor) directly as the main access methods & work
76 * to remove this function all together
79 * The mode of operation: live or test.
80 * @param array $paymentProcessor
81 * The details of the payment processor being invoked.
82 * @param object $paymentForm
83 * Deprecated - avoid referring to this if possible. If you have to use it document why as this is scary interaction.
85 * Should we force a reload of this payment object.
87 * @return CRM_Core_Payment
88 * @throws \CRM_Core_Exception
91 public static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
92 // make sure paymentProcessor is not empty
94 if (empty($paymentProcessor)) {
95 return CRM_Core_DAO
::$_nullObject;
97 //we use two lines because we can't remove the '&singleton' without risking breakage
98 //of extension classes that extend this one
99 $object = Civi\Payment\System
::singleton()->getByProcessor($paymentProcessor);
104 * @param array $params
105 * @todo move to factory class \Civi\Payment\System (or similar)
108 public static function logPaymentNotification($params) {
109 $message = 'payment_notification ';
110 if (!empty($params['processor_name'])) {
111 $message .= 'processor_name=' . $params['processor_name'];
113 if (!empty($params['processor_id'])) {
114 $message .= 'processor_id=' . $params['processor_id'];
117 $log = new CRM_Utils_SystemLogger();
118 $log->alert($message, $_REQUEST);
122 * Check if capability is supported
123 * @param string $capability
124 * E.g BackOffice, LiveMode, FutureRecurStartDate.
128 public function supports($capability) {
129 $function = 'supports' . ucfirst($capability);
130 if (method_exists($this, $function)) {
131 return $this->$function();
137 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
138 * 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
141 protected function supportsBackOffice() {
142 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
151 * Are live payments supported - e.g dummy doesn't support this
154 protected function supportsLiveMode() {
159 * Are test payments supported
162 protected function supportsTestMode() {
167 * Should the first payment date be configurable when setting up back office recurring payments
168 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
171 protected function supportsFutureRecurStartDate() {
176 * Setter for the payment form that wants to use the processor
178 * @param CRM_Core_Form $paymentForm
180 public function setForm(&$paymentForm) {
181 $this->_paymentForm
= $paymentForm;
185 * Getter for payment form that is using the processor
187 * @return CRM_Core_Form
190 public function getForm() {
191 return $this->_paymentForm
;
195 * Getter for accessing member vars
196 * @todo believe this is unused
197 * @param string $name
201 public function getVar($name) {
202 return isset($this->$name) ?
$this->$name : NULL;
206 * Get name for the payment information type
207 * @todo - use option group + name field (like Omnipay does)
210 public function getPaymentTypeName() {
211 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
215 * Get label for the payment information type
216 * @todo - use option group + labels (like Omnipay does)
219 public function getPaymentTypeLabel() {
220 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
224 * Get array of fields that should be displayed on the payment form
225 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
227 * @throws CiviCRM_API3_Exception
229 public function getPaymentFormFields() {
230 if ($this->_paymentProcessor
['billing_mode'] == 4) {
233 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
237 * Get array of fields that should be displayed on the payment form for credit cards
241 protected function getCreditCardFormFields() {
244 'credit_card_number',
246 'credit_card_exp_date',
251 * Get array of fields that should be displayed on the payment form for direct debits
255 protected function getDirectDebitFormFields() {
258 'bank_account_number',
259 'bank_identification_number',
265 * Return an array of all the details about the fields potentially required for payment fields
266 * Only those determined by getPaymentFormFields will actually be assigned to the form
271 public function getPaymentFormFieldsMetadata() {
272 //@todo convert credit card type into an option value
273 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
275 'credit_card_number' => array(
276 'htmlType' => 'text',
277 'name' => 'credit_card_number',
278 'title' => ts('Card Number'),
280 'attributes' => array(
283 'autocomplete' => 'off',
285 'is_required' => TRUE,
288 'htmlType' => 'text',
290 'title' => ts('Security Code'),
292 'attributes' => array(
295 'autocomplete' => 'off',
297 'is_required' => CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,
298 'cvv_backoffice_required',
304 '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.'),
305 'rule_name' => 'integer',
306 'rule_parameters' => NULL,
310 'credit_card_exp_date' => array(
311 'htmlType' => 'date',
312 'name' => 'credit_card_exp_date',
313 'title' => ts('Expiration Date'),
315 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
316 'is_required' => TRUE,
319 'rule_message' => ts('Card expiration date cannot be a past date.'),
320 'rule_name' => 'currentDate',
321 'rule_parameters' => TRUE,
325 'credit_card_type' => array(
326 'htmlType' => 'select',
327 'name' => 'credit_card_type',
328 'title' => ts('Card Type'),
330 'attributes' => $creditCardType,
331 'is_required' => FALSE,
333 'account_holder' => array(
334 'htmlType' => 'text',
335 'name' => 'account_holder',
336 'title' => ts('Account Holder'),
338 'attributes' => array(
341 'autocomplete' => 'on',
343 'is_required' => TRUE,
345 //e.g. IBAN can have maxlength of 34 digits
346 'bank_account_number' => array(
347 'htmlType' => 'text',
348 'name' => 'bank_account_number',
349 'title' => ts('Bank Account Number'),
351 'attributes' => array(
354 'autocomplete' => 'off',
358 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
359 'rule_name' => 'nopunctuation',
360 'rule_parameters' => NULL,
363 'is_required' => TRUE,
365 //e.g. SWIFT-BIC can have maxlength of 11 digits
366 'bank_identification_number' => array(
367 'htmlType' => 'text',
368 'name' => 'bank_identification_number',
369 'title' => ts('Bank Identification Number'),
371 'attributes' => array(
374 'autocomplete' => 'off',
376 'is_required' => TRUE,
379 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
380 'rule_name' => 'nopunctuation',
381 'rule_parameters' => NULL,
385 'bank_name' => array(
386 'htmlType' => 'text',
387 'name' => 'bank_name',
388 'title' => ts('Bank Name'),
390 'attributes' => array(
393 'autocomplete' => 'off',
395 'is_required' => TRUE,
402 * This function collects all the information from a web/api form and invokes
403 * the relevant payment processor specific functions to perform the transaction
405 * @param array $params
406 * Assoc array of input parameters for this transaction.
409 * the result in an nice formatted array (or an error object)
412 abstract function doDirectPayment(&$params);
415 * Process payment - this function wraps around both doTransferPayment and doDirectPayment
416 * it ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms more agnostic
418 * @param array $params
424 * @throws CRM_Core_Exception
426 public function doPayment(&$params, $component) {
427 if ($this->_paymentProcessor
['billing_mode'] == 4) {
428 $result = $this->doTransferCheckout($params, $component);
431 $result = $this->doDirectPayment($params, $component);
433 if (is_a($result, 'CRM_Core_Error')) {
434 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
436 //CRM-15767 - Submit Credit Card Contribution not being saved
441 * This function checks to see if we have the right config values
444 * the error message if any
446 abstract function checkConfig();
449 * @param $paymentProcessor
450 * @todo move to paypal class or remover
453 public static function paypalRedirect(&$paymentProcessor) {
454 if (!$paymentProcessor) {
458 if (isset($_GET['payment_date']) &&
459 isset($_GET['merchant_return_link']) &&
460 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
461 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
470 * @todo move to0 \Civi\Payment\System factory method
471 * Page callback for civicrm/payment/ipn
473 public static function handleIPN() {
474 self
::handlePaymentMethod(
475 'PaymentNotification',
477 'processor_name' => @$_GET['processor_name'],
478 'processor_id' => @$_GET['processor_id'],
479 'mode' => @$_GET['mode'],
485 * Payment callback handler. The processor_name or processor_id is passed in.
486 * Note that processor_id is more reliable as one site may have more than one instance of a
487 * processor & ideally the processor will be validating the results
488 * Load requested payment processor and call that processor's handle<$method> method
489 * @todo move to0 \Civi\Payment\System factory method
492 * @param array $params
494 public static function handlePaymentMethod($method, $params = array()) {
495 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
496 CRM_Core_Error
::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
498 self
::logPaymentNotification($params);
500 // Query db for processor ..
501 $mode = @$params['mode'];
503 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
504 FROM civicrm_payment_processor_type ppt
505 INNER JOIN civicrm_payment_processor pp
506 ON pp.payment_processor_type_id = ppt.id
508 AND pp.is_test = %1";
509 $args[1] = array($mode == 'test' ?
1 : 0, 'Integer');
511 if (isset($params['processor_id'])) {
512 $sql .= " WHERE pp.id = %2";
513 $args[2] = array($params['processor_id'], 'Integer');
514 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
517 $sql .= " WHERE ppt.name = %2";
518 $args[2] = array($params['processor_name'], 'String');
519 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
522 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
524 // Check whether we found anything at all ..
526 CRM_Core_Error
::fatal($notfound);
529 $method = 'handle' . $method;
530 $extension_instance_found = FALSE;
532 // In all likelihood, we'll just end up with the one instance returned here. But it's
533 // possible we may get more. Hence, iterate through all instances ..
535 while ($dao->fetch()) {
536 // Check pp is extension
537 $ext = CRM_Extension_System
::singleton()->getMapper();
538 if ($ext->isExtensionKey($dao->class_name
)) {
539 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
540 require_once $ext->classToPath($paymentClass);
543 // Legacy or extension as module instance
544 if (empty($paymentClass)) {
545 $paymentClass = 'CRM_Core_' . $dao->class_name
;
550 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($dao->processor_id
, $mode);
552 // Should never be empty - we already established this processor_id exists and is active.
553 if (empty($paymentProcessor)) {
558 $processorInstance = new $paymentClass($mode, $paymentProcessor);
560 // Does PP implement this method, and can we call it?
561 if (!method_exists($processorInstance, $method) ||
562 !is_callable(array($processorInstance, $method))
564 // on the off chance there is a double implementation of this processor we should keep looking for another
565 // note that passing processor_id is more reliable & we should work to deprecate processor_name
569 // Everything, it seems, is ok - execute pp callback handler
570 $processorInstance->$method();
571 $extension_instance_found = TRUE;
574 if (!$extension_instance_found) {
575 CRM_Core_Error
::fatal(
576 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
577 "$method method is unsupported in legacy payment processors."
581 // Exit here on web requests, allowing just the plain text response to be echoed
582 if ($method == 'handlePaymentNotification') {
583 CRM_Utils_System
::civiExit();
588 * Check whether a method is present ( & supported ) by the payment processor object.
590 * @param string $method
591 * Method to check for.
595 public function isSupported($method = 'cancelSubscription') {
596 return method_exists(CRM_Utils_System
::getClassName($this), $method);
600 * @param int $entityID
601 * @param null $entity
602 * @param string $action
606 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
610 $url = 'civicrm/contribute/unsubscribe';
614 //in notify mode don't return the update billing url
615 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
618 $url = 'civicrm/contribute/updatebilling';
622 $url = 'civicrm/contribute/updaterecur';
626 $session = CRM_Core_Session
::singleton();
627 $userId = $session->get('userID');
632 // Find related Contact
636 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
641 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
647 SELECT con.contact_id
648 FROM civicrm_contribution_recur rec
649 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
652 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
658 // Add entity arguments
659 if ($entityArg != '') {
660 // Add checksum argument
661 if ($contactID != 0 && $userId != $contactID) {
662 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
664 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
668 if ($this->isSupported('accountLoginURL')) {
669 return $this->accountLoginURL();
673 return $this->_paymentProcessor
['url_recur'];