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