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