Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-02-09-11-44-07
[civicrm-core.git] / CRM / Core / Payment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 use Civi\Payment\System;
29
30 /**
31 *
32 * @package CRM
33 * @copyright CiviCRM LLC (c) 2004-2014
34 * $Id$
35 *
36 */
37 abstract class CRM_Core_Payment {
38
39 /**
40 * How are we getting billing information?
41 *
42 * FORM - we collect it on the same page
43 * BUTTON - the processor collects it and sends it back to us via some protocol
44 */
45 const
46 BILLING_MODE_FORM = 1,
47 BILLING_MODE_BUTTON = 2,
48 BILLING_MODE_NOTIFY = 4;
49
50 /**
51 * Which payment type(s) are we using?
52 *
53 * credit card
54 * direct debit
55 * or both
56 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
57 */
58 const
59 PAYMENT_TYPE_CREDIT_CARD = 1,
60 PAYMENT_TYPE_DIRECT_DEBIT = 2;
61
62 /**
63 * Subscription / Recurring payment Status
64 * START, END
65 */
66 const
67 RECURRING_PAYMENT_START = 'START',
68 RECURRING_PAYMENT_END = 'END';
69
70 protected $_paymentProcessor;
71
72 /**
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
77 *
78 * @param string $mode
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.
84 * @param bool $force
85 * Should we force a reload of this payment object.
86 *
87 * @return CRM_Core_Payment
88 * @throws \CRM_Core_Exception
89 */
90 public static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
91 // make sure paymentProcessor is not empty
92 // CRM-7424
93 if (empty($paymentProcessor)) {
94 return CRM_Core_DAO::$_nullObject;
95 }
96 //we use two lines because we can't remove the '&singleton' without risking breakage
97 //of extension classes that extend this one
98 $object = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
99 return $object;
100 }
101
102 /**
103 * @param array $params
104 * @todo move to factory class \Civi\Payment\System (or similar)
105 * @return mixed
106 */
107 public static function logPaymentNotification($params) {
108 $message = 'payment_notification ';
109 if (!empty($params['processor_name'])) {
110 $message .= 'processor_name=' . $params['processor_name'];
111 }
112 if (!empty($params['processor_id'])) {
113 $message .= 'processor_id=' . $params['processor_id'];
114 }
115
116 $log = new CRM_Utils_SystemLogger();
117 $log->alert($message, $_REQUEST);
118 }
119
120 /**
121 * Check if capability is supported.
122 * @param string $capability
123 * E.g BackOffice, LiveMode, FutureRecurStartDate.
124 *
125 * @return bool
126 */
127 public function supports($capability) {
128 $function = 'supports' . ucfirst($capability);
129 if (method_exists($this, $function)) {
130 return $this->$function();
131 }
132 return FALSE;
133 }
134
135 /**
136 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
137 * 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
138 * @return bool
139 */
140 protected function supportsBackOffice() {
141 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
142 return FALSE;
143 }
144 else {
145 return TRUE;
146 }
147 }
148
149 /**
150 * Are live payments supported - e.g dummy doesn't support this
151 * @return bool
152 */
153 protected function supportsLiveMode() {
154 return TRUE;
155 }
156
157 /**
158 * Are test payments supported.
159 * @return bool
160 */
161 protected function supportsTestMode() {
162 return TRUE;
163 }
164
165 /**
166 * Should the first payment date be configurable when setting up back office recurring payments.
167 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
168 * @return bool
169 */
170 protected function supportsFutureRecurStartDate() {
171 return FALSE;
172 }
173
174 /**
175 * Default payment instrument validation
176 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
177 * Not a static function, because I need to check for payment_type
178 */
179 public function validatePaymentInstrument($values, &$errors) {
180 if ($this->_paymentProcessor['payment_type'] == 1) {
181 CRM_Core_Payment_Form::validateCreditCard($values, $errors);
182 }
183 }
184
185 /**
186 * Setter for the payment form that wants to use the processor
187 * @deprecated
188 * @param CRM_Core_Form $paymentForm
189 */
190 public function setForm(&$paymentForm) {
191 $this->_paymentForm = $paymentForm;
192 }
193
194 /**
195 * Getter for payment form that is using the processor.
196 * @deprecated
197 * @return CRM_Core_Form
198 * A form object
199 */
200 public function getForm() {
201 return $this->_paymentForm;
202 }
203
204 /**
205 * Getter for accessing member vars.
206 * @todo believe this is unused
207 * @param string $name
208 *
209 * @return null
210 */
211 public function getVar($name) {
212 return isset($this->$name) ? $this->$name : NULL;
213 }
214
215 /**
216 * Get name for the payment information type.
217 * @todo - use option group + name field (like Omnipay does)
218 * @return string
219 */
220 public function getPaymentTypeName() {
221 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
222 }
223
224 /**
225 * Get label for the payment information type.
226 * @todo - use option group + labels (like Omnipay does)
227 * @return string
228 */
229 public function getPaymentTypeLabel() {
230 return $this->_paymentProcessor['payment_type'] == 1 ? 'Credit Card' : 'Direct Debit';
231 }
232
233 /**
234 * Get array of fields that should be displayed on the payment form.
235 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
236 * @return array
237 * @throws CiviCRM_API3_Exception
238 */
239 public function getPaymentFormFields() {
240 if ($this->_paymentProcessor['billing_mode'] == 4) {
241 return array();
242 }
243 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
244 }
245
246 /**
247 * Get array of fields that should be displayed on the payment form for credit cards.
248 *
249 * @return array
250 */
251 protected function getCreditCardFormFields() {
252 return array(
253 'credit_card_type',
254 'credit_card_number',
255 'cvv2',
256 'credit_card_exp_date',
257 );
258 }
259
260 /**
261 * Get array of fields that should be displayed on the payment form for direct debits.
262 *
263 * @return array
264 */
265 protected function getDirectDebitFormFields() {
266 return array(
267 'account_holder',
268 'bank_account_number',
269 'bank_identification_number',
270 'bank_name',
271 );
272 }
273
274 /**
275 * Return an array of all the details about the fields potentially required for payment fields.
276 * Only those determined by getPaymentFormFields will actually be assigned to the form
277 *
278 * @return array
279 * field metadata
280 */
281 public function getPaymentFormFieldsMetadata() {
282 //@todo convert credit card type into an option value
283 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
284 return array(
285 'credit_card_number' => array(
286 'htmlType' => 'text',
287 'name' => 'credit_card_number',
288 'title' => ts('Card Number'),
289 'cc_field' => TRUE,
290 'attributes' => array(
291 'size' => 20,
292 'maxlength' => 20,
293 'autocomplete' => 'off',
294 ),
295 'is_required' => TRUE,
296 ),
297 'cvv2' => array(
298 'htmlType' => 'text',
299 'name' => 'cvv2',
300 'title' => ts('Security Code'),
301 'cc_field' => TRUE,
302 'attributes' => array(
303 'size' => 5,
304 'maxlength' => 10,
305 'autocomplete' => 'off',
306 ),
307 'is_required' => CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
308 'cvv_backoffice_required',
309 NULL,
310 1
311 ),
312 'rules' => array(
313 array(
314 '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.'),
315 'rule_name' => 'integer',
316 'rule_parameters' => NULL,
317 ),
318 ),
319 ),
320 'credit_card_exp_date' => array(
321 'htmlType' => 'date',
322 'name' => 'credit_card_exp_date',
323 'title' => ts('Expiration Date'),
324 'cc_field' => TRUE,
325 'attributes' => CRM_Core_SelectValues::date('creditCard'),
326 'is_required' => TRUE,
327 'rules' => array(
328 array(
329 'rule_message' => ts('Card expiration date cannot be a past date.'),
330 'rule_name' => 'currentDate',
331 'rule_parameters' => TRUE,
332 ),
333 ),
334 ),
335 'credit_card_type' => array(
336 'htmlType' => 'select',
337 'name' => 'credit_card_type',
338 'title' => ts('Card Type'),
339 'cc_field' => TRUE,
340 'attributes' => $creditCardType,
341 'is_required' => FALSE,
342 ),
343 'account_holder' => array(
344 'htmlType' => 'text',
345 'name' => 'account_holder',
346 'title' => ts('Account Holder'),
347 'cc_field' => TRUE,
348 'attributes' => array(
349 'size' => 20,
350 'maxlength' => 34,
351 'autocomplete' => 'on',
352 ),
353 'is_required' => TRUE,
354 ),
355 //e.g. IBAN can have maxlength of 34 digits
356 'bank_account_number' => array(
357 'htmlType' => 'text',
358 'name' => 'bank_account_number',
359 'title' => ts('Bank Account Number'),
360 'cc_field' => TRUE,
361 'attributes' => array(
362 'size' => 20,
363 'maxlength' => 34,
364 'autocomplete' => 'off',
365 ),
366 'rules' => array(
367 array(
368 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
369 'rule_name' => 'nopunctuation',
370 'rule_parameters' => NULL,
371 ),
372 ),
373 'is_required' => TRUE,
374 ),
375 //e.g. SWIFT-BIC can have maxlength of 11 digits
376 'bank_identification_number' => array(
377 'htmlType' => 'text',
378 'name' => 'bank_identification_number',
379 'title' => ts('Bank Identification Number'),
380 'cc_field' => TRUE,
381 'attributes' => array(
382 'size' => 20,
383 'maxlength' => 11,
384 'autocomplete' => 'off',
385 ),
386 'is_required' => TRUE,
387 'rules' => array(
388 array(
389 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
390 'rule_name' => 'nopunctuation',
391 'rule_parameters' => NULL,
392 ),
393 ),
394 ),
395 'bank_name' => array(
396 'htmlType' => 'text',
397 'name' => 'bank_name',
398 'title' => ts('Bank Name'),
399 'cc_field' => TRUE,
400 'attributes' => array(
401 'size' => 20,
402 'maxlength' => 64,
403 'autocomplete' => 'off',
404 ),
405 'is_required' => TRUE,
406
407 ),
408 );
409 }
410
411 /**
412 * Calling this from outside the payment subsystem is deprecated - use doPayment.
413 *
414 * Does a server to server payment transaction.
415 *
416 * Note that doPayment will throw an exception so the code may need to be modified
417 *
418 * @param array $params
419 * Assoc array of input parameters for this transaction.
420 *
421 * @return array
422 * the result in an nice formatted array (or an error object)
423 * @abstract
424 */
425 abstract protected function doDirectPayment(&$params);
426
427 /**
428 * Process payment - this function wraps around both doTransferPayment and doDirectPayment
429 * it ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms more agnostic
430 *
431 * @param array $params
432 *
433 * @param $component
434 *
435 * @return array
436 * (modified)
437 * @throws CRM_Core_Exception
438 */
439 public function doPayment(&$params, $component = 'contribute') {
440 if ($this->_paymentProcessor['billing_mode'] == 4) {
441 $result = $this->doTransferCheckout($params, $component);
442 }
443 else {
444 $result = $this->doDirectPayment($params, $component);
445 }
446 if (is_a($result, 'CRM_Core_Error')) {
447 throw new CRM_Core_Exception(CRM_Core_Error::getMessages($result));
448 }
449 //CRM-15767 - Submit Credit Card Contribution not being saved
450 return $result;
451 }
452
453 /**
454 * This function checks to see if we have the right config values.
455 *
456 * @return string
457 * the error message if any
458 */
459 abstract protected function checkConfig();
460
461 /**
462 * @param $paymentProcessor
463 * @todo move to paypal class or remover
464 * @return bool
465 */
466 public static function paypalRedirect(&$paymentProcessor) {
467 if (!$paymentProcessor) {
468 return FALSE;
469 }
470
471 if (isset($_GET['payment_date']) &&
472 isset($_GET['merchant_return_link']) &&
473 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
474 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
475 ) {
476 return TRUE;
477 }
478
479 return FALSE;
480 }
481
482 /**
483 * @todo move to0 \Civi\Payment\System factory method
484 * Page callback for civicrm/payment/ipn
485 */
486 public static function handleIPN() {
487 self::handlePaymentMethod(
488 'PaymentNotification',
489 array(
490 'processor_name' => @$_GET['processor_name'],
491 'processor_id' => @$_GET['processor_id'],
492 'mode' => @$_GET['mode'],
493 )
494 );
495 }
496
497 /**
498 * Payment callback handler. The processor_name or processor_id is passed in.
499 * Note that processor_id is more reliable as one site may have more than one instance of a
500 * processor & ideally the processor will be validating the results
501 * Load requested payment processor and call that processor's handle<$method> method
502 * @todo move to0 \Civi\Payment\System factory method
503 *
504 * @param $method
505 * @param array $params
506 */
507 public static function handlePaymentMethod($method, $params = array()) {
508 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
509 CRM_Core_Error::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
510 }
511 self::logPaymentNotification($params);
512
513 // Query db for processor ..
514 $mode = @$params['mode'];
515
516 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
517 FROM civicrm_payment_processor_type ppt
518 INNER JOIN civicrm_payment_processor pp
519 ON pp.payment_processor_type_id = ppt.id
520 AND pp.is_active
521 AND pp.is_test = %1";
522 $args[1] = array($mode == 'test' ? 1 : 0, 'Integer');
523
524 if (isset($params['processor_id'])) {
525 $sql .= " WHERE pp.id = %2";
526 $args[2] = array($params['processor_id'], 'Integer');
527 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
528 }
529 else {
530 $sql .= " WHERE ppt.name = %2";
531 $args[2] = array($params['processor_name'], 'String');
532 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
533 }
534
535 $dao = CRM_Core_DAO::executeQuery($sql, $args);
536
537 // Check whether we found anything at all ..
538 if (!$dao->N) {
539 CRM_Core_Error::fatal($notfound);
540 }
541
542 $method = 'handle' . $method;
543 $extension_instance_found = FALSE;
544
545 // In all likelihood, we'll just end up with the one instance returned here. But it's
546 // possible we may get more. Hence, iterate through all instances ..
547
548 while ($dao->fetch()) {
549 // Check pp is extension
550 $ext = CRM_Extension_System::singleton()->getMapper();
551 if ($ext->isExtensionKey($dao->class_name)) {
552 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
553 require_once $ext->classToPath($paymentClass);
554 }
555 else {
556 // Legacy or extension as module instance
557 if (empty($paymentClass)) {
558 $paymentClass = 'CRM_Core_' . $dao->class_name;
559
560 }
561 }
562
563 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($dao->processor_id, $mode);
564
565 // Should never be empty - we already established this processor_id exists and is active.
566 if (empty($paymentProcessor)) {
567 continue;
568 }
569
570 // Instantiate PP
571 $processorInstance = new $paymentClass($mode, $paymentProcessor);
572
573 // Does PP implement this method, and can we call it?
574 if (!method_exists($processorInstance, $method) ||
575 !is_callable(array($processorInstance, $method))
576 ) {
577 // on the off chance there is a double implementation of this processor we should keep looking for another
578 // note that passing processor_id is more reliable & we should work to deprecate processor_name
579 continue;
580 }
581
582 // Everything, it seems, is ok - execute pp callback handler
583 $processorInstance->$method();
584 $extension_instance_found = TRUE;
585 }
586
587 if (!$extension_instance_found) {
588 CRM_Core_Error::fatal(
589 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
590 "$method method is unsupported in legacy payment processors."
591 );
592 }
593
594 // Exit here on web requests, allowing just the plain text response to be echoed
595 if ($method == 'handlePaymentNotification') {
596 CRM_Utils_System::civiExit();
597 }
598 }
599
600 /**
601 * Check whether a method is present ( & supported ) by the payment processor object.
602 *
603 * @param string $method
604 * Method to check for.
605 *
606 * @return bool
607 */
608 public function isSupported($method = 'cancelSubscription') {
609 return method_exists(CRM_Utils_System::getClassName($this), $method);
610 }
611
612 /**
613 * @param int $entityID
614 * @param null $entity
615 * @param string $action
616 *
617 * @return string
618 */
619 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
620 // Set URL
621 switch ($action) {
622 case 'cancel':
623 $url = 'civicrm/contribute/unsubscribe';
624 break;
625
626 case 'billing':
627 //in notify mode don't return the update billing url
628 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
629 return NULL;
630 }
631 $url = 'civicrm/contribute/updatebilling';
632 break;
633
634 case 'update':
635 $url = 'civicrm/contribute/updaterecur';
636 break;
637 }
638
639 $session = CRM_Core_Session::singleton();
640 $userId = $session->get('userID');
641 $contactID = 0;
642 $checksumValue = '';
643 $entityArg = '';
644
645 // Find related Contact
646 if ($entityID) {
647 switch ($entity) {
648 case 'membership':
649 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
650 $entityArg = 'mid';
651 break;
652
653 case 'contribution':
654 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
655 $entityArg = 'coid';
656 break;
657
658 case 'recur':
659 $sql = "
660 SELECT con.contact_id
661 FROM civicrm_contribution_recur rec
662 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
663 WHERE rec.id = %1
664 GROUP BY rec.id";
665 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
666 $entityArg = 'crid';
667 break;
668 }
669 }
670
671 // Add entity arguments
672 if ($entityArg != '') {
673 // Add checksum argument
674 if ($contactID != 0 && $userId != $contactID) {
675 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
676 }
677 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
678 }
679
680 // Else login URL
681 if ($this->isSupported('accountLoginURL')) {
682 return $this->accountLoginURL();
683 }
684
685 // Else default
686 return $this->_paymentProcessor['url_recur'];
687 }
688
689 }