phpdoc params is always an array in api
[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 * @static
90 */
91 public static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
92 // make sure paymentProcessor is not empty
93 // CRM-7424
94 if (empty($paymentProcessor)) {
95 return CRM_Core_DAO::$_nullObject;
96 }
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);
100 return $object;
101 }
102
103 /**
104 * @param array $params
105 * @todo move to factory class \Civi\Payment\System (or similar)
106 * @return mixed
107 */
108 public static function logPaymentNotification($params) {
109 $message = 'payment_notification ';
110 if (!empty($params['processor_name'])) {
111 $message .= 'processor_name=' . $params['processor_name'];
112 }
113 if (!empty($params['processor_id'])) {
114 $message .= 'processor_id=' . $params['processor_id'];
115 }
116
117 $log = new CRM_Utils_SystemLogger();
118 $log->alert($message, $_REQUEST);
119 }
120
121 /**
122 * Check if capability is supported
123 * @param string $capability
124 * E.g BackOffice, LiveMode, FutureRecurStartDate.
125 *
126 * @return bool
127 */
128 public function supports($capability) {
129 $function = 'supports' . ucfirst($capability);
130 if (method_exists($this, $function)) {
131 return $this->$function();
132 }
133 return FALSE;
134 }
135
136 /**
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
139 * @return bool
140 */
141 protected function supportsBackOffice() {
142 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
143 return FALSE;
144 }
145 else {
146 return TRUE;
147 }
148 }
149
150 /**
151 * Are live payments supported - e.g dummy doesn't support this
152 * @return bool
153 */
154 protected function supportsLiveMode() {
155 return TRUE;
156 }
157
158 /**
159 * Are test payments supported
160 * @return bool
161 */
162 protected function supportsTestMode() {
163 return TRUE;
164 }
165
166 /**
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
169 * @return bool
170 */
171 protected function supportsFutureRecurStartDate() {
172 return FALSE;
173 }
174
175 /**
176 * Setter for the payment form that wants to use the processor
177 * @deprecated
178 * @param CRM_Core_Form $paymentForm
179 */
180 public function setForm(&$paymentForm) {
181 $this->_paymentForm = $paymentForm;
182 }
183
184 /**
185 * Getter for payment form that is using the processor
186 * @deprecated
187 * @return CRM_Core_Form
188 * A form object
189 */
190 public function getForm() {
191 return $this->_paymentForm;
192 }
193
194 /**
195 * Getter for accessing member vars
196 * @todo believe this is unused
197 * @param string $name
198 *
199 * @return null
200 */
201 public function getVar($name) {
202 return isset($this->$name) ? $this->$name : NULL;
203 }
204
205 /**
206 * Get name for the payment information type
207 * @todo - use option group + name field (like Omnipay does)
208 * @return string
209 */
210 public function getPaymentTypeName() {
211 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
212 }
213
214 /**
215 * Get label for the payment information type
216 * @todo - use option group + labels (like Omnipay does)
217 * @return string
218 */
219 public function getPaymentTypeLabel() {
220 return $this->_paymentProcessor['payment_type'] == 1 ? 'Credit Card' : 'Direct Debit';
221 }
222
223 /**
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
226 * @return array
227 * @throws CiviCRM_API3_Exception
228 */
229 public function getPaymentFormFields() {
230 if ($this->_paymentProcessor['billing_mode'] == 4) {
231 return array();
232 }
233 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
234 }
235
236 /**
237 * Get array of fields that should be displayed on the payment form for credit cards
238 *
239 * @return array
240 */
241 protected function getCreditCardFormFields() {
242 return array(
243 'credit_card_type',
244 'credit_card_number',
245 'cvv2',
246 'credit_card_exp_date',
247 );
248 }
249
250 /**
251 * Get array of fields that should be displayed on the payment form for direct debits
252 *
253 * @return array
254 */
255 protected function getDirectDebitFormFields() {
256 return array(
257 'account_holder',
258 'bank_account_number',
259 'bank_identification_number',
260 'bank_name',
261 );
262 }
263
264 /**
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
267 *
268 * @return array
269 * field metadata
270 */
271 public function getPaymentFormFieldsMetadata() {
272 //@todo convert credit card type into an option value
273 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
274 return array(
275 'credit_card_number' => array(
276 'htmlType' => 'text',
277 'name' => 'credit_card_number',
278 'title' => ts('Card Number'),
279 'cc_field' => TRUE,
280 'attributes' => array(
281 'size' => 20,
282 'maxlength' => 20,
283 'autocomplete' => 'off',
284 ),
285 'is_required' => TRUE,
286 ),
287 'cvv2' => array(
288 'htmlType' => 'text',
289 'name' => 'cvv2',
290 'title' => ts('Security Code'),
291 'cc_field' => TRUE,
292 'attributes' => array(
293 'size' => 5,
294 'maxlength' => 10,
295 'autocomplete' => 'off',
296 ),
297 'is_required' => CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
298 'cvv_backoffice_required',
299 NULL,
300 1
301 ),
302 'rules' => array(
303 array(
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,
307 )
308 ),
309 ),
310 'credit_card_exp_date' => array(
311 'htmlType' => 'date',
312 'name' => 'credit_card_exp_date',
313 'title' => ts('Expiration Date'),
314 'cc_field' => TRUE,
315 'attributes' => CRM_Core_SelectValues::date('creditCard'),
316 'is_required' => TRUE,
317 'rules' => array(
318 array(
319 'rule_message' => ts('Card expiration date cannot be a past date.'),
320 'rule_name' => 'currentDate',
321 'rule_parameters' => TRUE,
322 )
323 ),
324 ),
325 'credit_card_type' => array(
326 'htmlType' => 'select',
327 'name' => 'credit_card_type',
328 'title' => ts('Card Type'),
329 'cc_field' => TRUE,
330 'attributes' => $creditCardType,
331 'is_required' => FALSE,
332 ),
333 'account_holder' => array(
334 'htmlType' => 'text',
335 'name' => 'account_holder',
336 'title' => ts('Account Holder'),
337 'cc_field' => TRUE,
338 'attributes' => array(
339 'size' => 20,
340 'maxlength' => 34,
341 'autocomplete' => 'on',
342 ),
343 'is_required' => TRUE,
344 ),
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'),
350 'cc_field' => TRUE,
351 'attributes' => array(
352 'size' => 20,
353 'maxlength' => 34,
354 'autocomplete' => 'off',
355 ),
356 'rules' => array(
357 array(
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,
361 )
362 ),
363 'is_required' => TRUE,
364 ),
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'),
370 'cc_field' => TRUE,
371 'attributes' => array(
372 'size' => 20,
373 'maxlength' => 11,
374 'autocomplete' => 'off',
375 ),
376 'is_required' => TRUE,
377 'rules' => array(
378 array(
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,
382 )
383 ),
384 ),
385 'bank_name' => array(
386 'htmlType' => 'text',
387 'name' => 'bank_name',
388 'title' => ts('Bank Name'),
389 'cc_field' => TRUE,
390 'attributes' => array(
391 'size' => 20,
392 'maxlength' => 64,
393 'autocomplete' => 'off',
394 ),
395 'is_required' => TRUE,
396
397 ),
398 );
399 }
400
401 /**
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
404 *
405 * @param array $params
406 * Assoc array of input parameters for this transaction.
407 *
408 * @return array
409 * the result in an nice formatted array (or an error object)
410 * @abstract
411 */
412 abstract function doDirectPayment(&$params);
413
414 /**
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
417 *
418 * @param array $params
419 *
420 * @param $component
421 *
422 * @return array
423 * (modified)
424 * @throws CRM_Core_Exception
425 */
426 public function doPayment(&$params, $component) {
427 if ($this->_paymentProcessor['billing_mode'] == 4) {
428 $result = $this->doTransferCheckout($params, $component);
429 }
430 else {
431 $result = $this->doDirectPayment($params, $component);
432 }
433 if (is_a($result, 'CRM_Core_Error')) {
434 throw new CRM_Core_Exception(CRM_Core_Error::getMessages($result));
435 }
436 //CRM-15767 - Submit Credit Card Contribution not being saved
437 return $result;
438 }
439
440 /**
441 * This function checks to see if we have the right config values
442 *
443 * @return string
444 * the error message if any
445 */
446 abstract function checkConfig();
447
448 /**
449 * @param $paymentProcessor
450 * @todo move to paypal class or remover
451 * @return bool
452 */
453 public static function paypalRedirect(&$paymentProcessor) {
454 if (!$paymentProcessor) {
455 return FALSE;
456 }
457
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"
462 ) {
463 return TRUE;
464 }
465
466 return FALSE;
467 }
468
469 /**
470 * @todo move to0 \Civi\Payment\System factory method
471 * Page callback for civicrm/payment/ipn
472 */
473 public static function handleIPN() {
474 self::handlePaymentMethod(
475 'PaymentNotification',
476 array(
477 'processor_name' => @$_GET['processor_name'],
478 'processor_id' => @$_GET['processor_id'],
479 'mode' => @$_GET['mode'],
480 )
481 );
482 }
483
484 /**
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
490 *
491 * @param $method
492 * @param array $params
493 */
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");
497 }
498 self::logPaymentNotification($params);
499
500 // Query db for processor ..
501 $mode = @$params['mode'];
502
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
507 AND pp.is_active
508 AND pp.is_test = %1";
509 $args[1] = array($mode == 'test' ? 1 : 0, 'Integer');
510
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.";
515 }
516 else {
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.";
520 }
521
522 $dao = CRM_Core_DAO::executeQuery($sql, $args);
523
524 // Check whether we found anything at all ..
525 if (!$dao->N) {
526 CRM_Core_Error::fatal($notfound);
527 }
528
529 $method = 'handle' . $method;
530 $extension_instance_found = FALSE;
531
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 ..
534
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);
541 }
542 else {
543 // Legacy or extension as module instance
544 if (empty($paymentClass)) {
545 $paymentClass = 'CRM_Core_' . $dao->class_name;
546
547 }
548 }
549
550 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($dao->processor_id, $mode);
551
552 // Should never be empty - we already established this processor_id exists and is active.
553 if (empty($paymentProcessor)) {
554 continue;
555 }
556
557 // Instantiate PP
558 $processorInstance = new $paymentClass($mode, $paymentProcessor);
559
560 // Does PP implement this method, and can we call it?
561 if (!method_exists($processorInstance, $method) ||
562 !is_callable(array($processorInstance, $method))
563 ) {
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
566 continue;
567 }
568
569 // Everything, it seems, is ok - execute pp callback handler
570 $processorInstance->$method();
571 $extension_instance_found = TRUE;
572 }
573
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."
578 );
579 }
580
581 // Exit here on web requests, allowing just the plain text response to be echoed
582 if ($method == 'handlePaymentNotification') {
583 CRM_Utils_System::civiExit();
584 }
585 }
586
587 /**
588 * Check whether a method is present ( & supported ) by the payment processor object.
589 *
590 * @param string $method
591 * Method to check for.
592 *
593 * @return boolean
594 */
595 public function isSupported($method = 'cancelSubscription') {
596 return method_exists(CRM_Utils_System::getClassName($this), $method);
597 }
598
599 /**
600 * @param int $entityID
601 * @param null $entity
602 * @param string $action
603 *
604 * @return string
605 */
606 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
607 // Set URL
608 switch ($action) {
609 case 'cancel':
610 $url = 'civicrm/contribute/unsubscribe';
611 break;
612
613 case 'billing':
614 //in notify mode don't return the update billing url
615 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
616 return NULL;
617 }
618 $url = 'civicrm/contribute/updatebilling';
619 break;
620
621 case 'update':
622 $url = 'civicrm/contribute/updaterecur';
623 break;
624 }
625
626 $session = CRM_Core_Session::singleton();
627 $userId = $session->get('userID');
628 $contactID = 0;
629 $checksumValue = '';
630 $entityArg = '';
631
632 // Find related Contact
633 if ($entityID) {
634 switch ($entity) {
635 case 'membership':
636 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
637 $entityArg = 'mid';
638 break;
639
640 case 'contribution':
641 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
642 $entityArg = 'coid';
643 break;
644
645 case 'recur':
646 $sql = "
647 SELECT con.contact_id
648 FROM civicrm_contribution_recur rec
649 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
650 WHERE rec.id = %1
651 GROUP BY rec.id";
652 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
653 $entityArg = 'crid';
654 break;
655 }
656 }
657
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');
663 }
664 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
665 }
666
667 // Else login URL
668 if ($this->isSupported('accountLoginURL')) {
669 return $this->accountLoginURL();
670 }
671
672 // Else default
673 return $this->_paymentProcessor['url_recur'];
674 }
675 }