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
;
32 * @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 A form object
189 public function getForm() {
190 return $this->_paymentForm
;
194 * Getter for accessing member vars
195 * @todo believe this is unused
196 * @param string $name
200 public function getVar($name) {
201 return isset($this->$name) ?
$this->$name : NULL;
205 * Get name for the payment information type
206 * @todo - use option group + name field (like Omnipay does)
209 public function getPaymentTypeName() {
210 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
214 * Get label for the payment information type
215 * @todo - use option group + labels (like Omnipay does)
218 public function getPaymentTypeLabel() {
219 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
223 * Get array of fields that should be displayed on the payment form
224 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
226 * @throws CiviCRM_API3_Exception
228 public function getPaymentFormFields() {
229 if ($this->_paymentProcessor
['billing_mode'] == 4) {
232 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
236 * Get array of fields that should be displayed on the payment form for credit cards
240 protected function getCreditCardFormFields() {
243 'credit_card_number',
245 'credit_card_exp_date',
250 * Get array of fields that should be displayed on the payment form for direct debits
254 protected function getDirectDebitFormFields() {
257 'bank_account_number',
258 'bank_identification_number',
264 * Return an array of all the details about the fields potentially required for payment fields
265 * Only those determined by getPaymentFormFields will actually be assigned to the form
270 public function getPaymentFormFieldsMetadata() {
271 //@todo convert credit card type into an option value
272 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
274 'credit_card_number' => array(
275 'htmlType' => 'text',
276 'name' => 'credit_card_number',
277 'title' => ts('Card Number'),
279 'attributes' => array(
282 'autocomplete' => 'off',
284 'is_required' => TRUE,
287 'htmlType' => 'text',
289 'title' => ts('Security Code'),
291 'attributes' => array(
294 'autocomplete' => 'off',
296 'is_required' => CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,
297 'cvv_backoffice_required',
303 '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.'),
304 'rule_name' => 'integer',
305 'rule_parameters' => NULL,
308 'credit_card_exp_date' => array(
309 'htmlType' => 'date',
310 'name' => 'credit_card_exp_date',
311 'title' => ts('Expiration Date'),
313 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
314 'is_required' => TRUE,
317 'rule_message' => ts('Card expiration date cannot be a past date.'),
318 'rule_name' => 'currentDate',
319 'rule_parameters' => TRUE,
322 'credit_card_type' => array(
323 'htmlType' => 'select',
324 'name' => 'credit_card_type',
325 'title' => ts('Card Type'),
327 'attributes' => $creditCardType,
328 'is_required' => FALSE,
330 'account_holder' => array(
331 'htmlType' => 'text',
332 'name' => 'account_holder',
333 'title' => ts('Account Holder'),
335 'attributes' => array(
338 'autocomplete' => 'on',
340 'is_required' => TRUE,
342 //e.g. IBAN can have maxlength of 34 digits
343 'bank_account_number' => array(
344 'htmlType' => 'text',
345 'name' => 'bank_account_number',
346 'title' => ts('Bank Account Number'),
348 'attributes' => array(
351 'autocomplete' => 'off',
355 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
356 'rule_name' => 'nopunctuation',
357 'rule_parameters' => NULL,
359 'is_required' => TRUE,
361 //e.g. SWIFT-BIC can have maxlength of 11 digits
362 'bank_identification_number' => array(
363 'htmlType' => 'text',
364 'name' => 'bank_identification_number',
365 'title' => ts('Bank Identification Number'),
367 'attributes' => array(
370 'autocomplete' => 'off',
372 'is_required' => TRUE,
375 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
376 'rule_name' => 'nopunctuation',
377 'rule_parameters' => NULL,
380 'bank_name' => array(
381 'htmlType' => 'text',
382 'name' => 'bank_name',
383 'title' => ts('Bank Name'),
385 'attributes' => array(
388 'autocomplete' => 'off',
390 'is_required' => TRUE,
397 * This function collects all the information from a web/api form and invokes
398 * the relevant payment processor specific functions to perform the transaction
400 * @param array $params
401 * Assoc array of input parameters for this transaction.
404 * the result in an nice formatted array (or an error object)
407 abstract function doDirectPayment(&$params);
410 * Process payment - this function wraps around both doTransferPayment and doDirectPayment
411 * it ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms more agnostic
413 * @param array $params
419 * @throws CRM_Core_Exception
421 public function doPayment(&$params, $component) {
422 if ($this->_paymentProcessor
['billing_mode'] == 4) {
423 $result = $this->doTransferCheckout($params, $component);
426 $result = $this->doDirectPayment($params, $component);
428 if (is_a($result, 'CRM_Core_Error')) {
429 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
431 //CRM-15767 - Submit Credit Card Contribution not being saved
436 * This function checks to see if we have the right config values
439 * the error message if any
441 abstract function checkConfig();
444 * @param $paymentProcessor
445 * @todo move to paypal class or remover
448 public static function paypalRedirect(&$paymentProcessor) {
449 if (!$paymentProcessor) {
453 if (isset($_GET['payment_date']) &&
454 isset($_GET['merchant_return_link']) &&
455 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
456 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
465 * @todo move to0 \Civi\Payment\System factory method
466 * Page callback for civicrm/payment/ipn
468 public static function handleIPN() {
469 self
::handlePaymentMethod(
470 'PaymentNotification',
472 'processor_name' => @$_GET['processor_name'],
473 'processor_id' => @$_GET['processor_id'],
474 'mode' => @$_GET['mode'],
480 * Payment callback handler. The processor_name or processor_id is passed in.
481 * Note that processor_id is more reliable as one site may have more than one instance of a
482 * processor & ideally the processor will be validating the results
483 * Load requested payment processor and call that processor's handle<$method> method
484 * @todo move to0 \Civi\Payment\System factory method
487 * @param array $params
489 public static function handlePaymentMethod($method, $params = array()) {
490 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
491 CRM_Core_Error
::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
493 self
::logPaymentNotification($params);
495 // Query db for processor ..
496 $mode = @$params['mode'];
498 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
499 FROM civicrm_payment_processor_type ppt
500 INNER JOIN civicrm_payment_processor pp
501 ON pp.payment_processor_type_id = ppt.id
503 AND pp.is_test = %1";
504 $args[1] = array($mode == 'test' ?
1 : 0, 'Integer');
506 if (isset($params['processor_id'])) {
507 $sql .= " WHERE pp.id = %2";
508 $args[2] = array($params['processor_id'], 'Integer');
509 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
512 $sql .= " WHERE ppt.name = %2";
513 $args[2] = array($params['processor_name'], 'String');
514 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
517 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
519 // Check whether we found anything at all ..
521 CRM_Core_Error
::fatal($notfound);
524 $method = 'handle' . $method;
525 $extension_instance_found = FALSE;
527 // In all likelihood, we'll just end up with the one instance returned here. But it's
528 // possible we may get more. Hence, iterate through all instances ..
530 while ($dao->fetch()) {
531 // Check pp is extension
532 $ext = CRM_Extension_System
::singleton()->getMapper();
533 if ($ext->isExtensionKey($dao->class_name
)) {
534 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
535 require_once $ext->classToPath($paymentClass);
538 // Legacy or extension as module instance
539 if (empty($paymentClass)) {
540 $paymentClass = 'CRM_Core_' . $dao->class_name
;
545 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($dao->processor_id
, $mode);
547 // Should never be empty - we already established this processor_id exists and is active.
548 if (empty($paymentProcessor)) {
553 $processorInstance = new $paymentClass($mode, $paymentProcessor);
555 // Does PP implement this method, and can we call it?
556 if (!method_exists($processorInstance, $method) ||
557 !is_callable(array($processorInstance, $method))
559 // on the off chance there is a double implementation of this processor we should keep looking for another
560 // note that passing processor_id is more reliable & we should work to deprecate processor_name
564 // Everything, it seems, is ok - execute pp callback handler
565 $processorInstance->$method();
566 $extension_instance_found = TRUE;
569 if (!$extension_instance_found) {
570 CRM_Core_Error
::fatal(
571 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
572 "$method method is unsupported in legacy payment processors."
576 // Exit here on web requests, allowing just the plain text response to be echoed
577 if ($method == 'handlePaymentNotification') {
578 CRM_Utils_System
::civiExit();
583 * Check whether a method is present ( & supported ) by the payment processor object.
585 * @param string $method
586 * Method to check for.
590 public function isSupported($method = 'cancelSubscription') {
591 return method_exists(CRM_Utils_System
::getClassName($this), $method);
595 * @param int $entityID
596 * @param null $entity
597 * @param string $action
601 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
605 $url = 'civicrm/contribute/unsubscribe';
609 //in notify mode don't return the update billing url
610 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
613 $url = 'civicrm/contribute/updatebilling';
617 $url = 'civicrm/contribute/updaterecur';
621 $session = CRM_Core_Session
::singleton();
622 $userId = $session->get('userID');
627 // Find related Contact
631 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
636 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
642 SELECT con.contact_id
643 FROM civicrm_contribution_recur rec
644 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
647 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
653 // Add entity arguments
654 if ($entityArg != '') {
655 // Add checksum argument
656 if ($contactID != 0 && $userId != $contactID) {
657 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
659 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
663 if ($this->isSupported('accountLoginURL')) {
664 return $this->accountLoginURL();
668 return $this->_paymentProcessor
['url_recur'];