d9550928d8d6055281255a2c776fb1affc4eff95
[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 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
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 A form object
188 */
189 public function getForm() {
190 return $this->_paymentForm;
191 }
192
193 /**
194 * Getter for accessing member vars
195 * @todo believe this is unused
196 * @param string $name
197 *
198 * @return null
199 */
200 public function getVar($name) {
201 return isset($this->$name) ? $this->$name : NULL;
202 }
203
204 /**
205 * Get name for the payment information type
206 * @todo - use option group + name field (like Omnipay does)
207 * @return string
208 */
209 public function getPaymentTypeName() {
210 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
211 }
212
213 /**
214 * Get label for the payment information type
215 * @todo - use option group + labels (like Omnipay does)
216 * @return string
217 */
218 public function getPaymentTypeLabel() {
219 return $this->_paymentProcessor['payment_type'] == 1 ? 'Credit Card' : 'Direct Debit';
220 }
221
222 /**
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
225 * @return array
226 * @throws CiviCRM_API3_Exception
227 */
228 public function getPaymentFormFields() {
229 if ($this->_paymentProcessor['billing_mode'] == 4) {
230 return array();
231 }
232 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
233 }
234
235 /**
236 * Get array of fields that should be displayed on the payment form for credit cards
237 *
238 * @return array
239 */
240 protected function getCreditCardFormFields() {
241 return array(
242 'credit_card_type',
243 'credit_card_number',
244 'cvv2',
245 'credit_card_exp_date',
246 );
247 }
248
249 /**
250 * Get array of fields that should be displayed on the payment form for direct debits
251 *
252 * @return array
253 */
254 protected function getDirectDebitFormFields() {
255 return array(
256 'account_holder',
257 'bank_account_number',
258 'bank_identification_number',
259 'bank_name',
260 );
261 }
262
263 /**
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
266 *
267 * @return array
268 * field metadata
269 */
270 public function getPaymentFormFieldsMetadata() {
271 //@todo convert credit card type into an option value
272 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
273 return array(
274 'credit_card_number' => array(
275 'htmlType' => 'text',
276 'name' => 'credit_card_number',
277 'title' => ts('Card Number'),
278 'cc_field' => TRUE,
279 'attributes' => array(
280 'size' => 20,
281 'maxlength' => 20,
282 'autocomplete' => 'off',
283 ),
284 'is_required' => TRUE,
285 ),
286 'cvv2' => array(
287 'htmlType' => 'text',
288 'name' => 'cvv2',
289 'title' => ts('Security Code'),
290 'cc_field' => TRUE,
291 'attributes' => array(
292 'size' => 5,
293 'maxlength' => 10,
294 'autocomplete' => 'off',
295 ),
296 'is_required' => CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
297 'cvv_backoffice_required',
298 NULL,
299 1
300 ),
301 'rules' => array(
302 array(
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,
306 )),
307 ),
308 'credit_card_exp_date' => array(
309 'htmlType' => 'date',
310 'name' => 'credit_card_exp_date',
311 'title' => ts('Expiration Date'),
312 'cc_field' => TRUE,
313 'attributes' => CRM_Core_SelectValues::date('creditCard'),
314 'is_required' => TRUE,
315 'rules' => array(
316 array(
317 'rule_message' => ts('Card expiration date cannot be a past date.'),
318 'rule_name' => 'currentDate',
319 'rule_parameters' => TRUE,
320 )),
321 ),
322 'credit_card_type' => array(
323 'htmlType' => 'select',
324 'name' => 'credit_card_type',
325 'title' => ts('Card Type'),
326 'cc_field' => TRUE,
327 'attributes' => $creditCardType,
328 'is_required' => FALSE,
329 ),
330 'account_holder' => array(
331 'htmlType' => 'text',
332 'name' => 'account_holder',
333 'title' => ts('Account Holder'),
334 'cc_field' => TRUE,
335 'attributes' => array(
336 'size' => 20,
337 'maxlength' => 34,
338 'autocomplete' => 'on',
339 ),
340 'is_required' => TRUE,
341 ),
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'),
347 'cc_field' => TRUE,
348 'attributes' => array(
349 'size' => 20,
350 'maxlength' => 34,
351 'autocomplete' => 'off',
352 ),
353 'rules' => array(
354 array(
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,
358 )),
359 'is_required' => TRUE,
360 ),
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'),
366 'cc_field' => TRUE,
367 'attributes' => array(
368 'size' => 20,
369 'maxlength' => 11,
370 'autocomplete' => 'off',
371 ),
372 'is_required' => TRUE,
373 'rules' => array(
374 array(
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,
378 )),
379 ),
380 'bank_name' => array(
381 'htmlType' => 'text',
382 'name' => 'bank_name',
383 'title' => ts('Bank Name'),
384 'cc_field' => TRUE,
385 'attributes' => array(
386 'size' => 20,
387 'maxlength' => 64,
388 'autocomplete' => 'off',
389 ),
390 'is_required' => TRUE,
391
392 ),
393 );
394 }
395
396 /**
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
399 *
400 * @param array $params
401 * Assoc array of input parameters for this transaction.
402 *
403 * @return array
404 * the result in an nice formatted array (or an error object)
405 * @abstract
406 */
407 abstract function doDirectPayment(&$params);
408
409 /**
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
412 *
413 * @param array $params
414 *
415 * @param $component
416 *
417 * @return array
418 * (modified)
419 * @throws CRM_Core_Exception
420 */
421 public function doPayment(&$params, $component) {
422 if ($this->_paymentProcessor['billing_mode'] == 4) {
423 $result = $this->doTransferCheckout($params, $component);
424 }
425 else {
426 $result = $this->doDirectPayment($params, $component);
427 }
428 if (is_a($result, 'CRM_Core_Error')) {
429 throw new CRM_Core_Exception(CRM_Core_Error::getMessages($result));
430 }
431 //CRM-15767 - Submit Credit Card Contribution not being saved
432 return $result;
433 }
434
435 /**
436 * This function checks to see if we have the right config values
437 *
438 * @return string
439 * the error message if any
440 */
441 abstract function checkConfig();
442
443 /**
444 * @param $paymentProcessor
445 * @todo move to paypal class or remover
446 * @return bool
447 */
448 public static function paypalRedirect(&$paymentProcessor) {
449 if (!$paymentProcessor) {
450 return FALSE;
451 }
452
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"
457 ) {
458 return TRUE;
459 }
460
461 return FALSE;
462 }
463
464 /**
465 * @todo move to0 \Civi\Payment\System factory method
466 * Page callback for civicrm/payment/ipn
467 */
468 public static function handleIPN() {
469 self::handlePaymentMethod(
470 'PaymentNotification',
471 array(
472 'processor_name' => @$_GET['processor_name'],
473 'processor_id' => @$_GET['processor_id'],
474 'mode' => @$_GET['mode'],
475 )
476 );
477 }
478
479 /**
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
485 *
486 * @param $method
487 * @param array $params
488 */
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");
492 }
493 self::logPaymentNotification($params);
494
495 // Query db for processor ..
496 $mode = @$params['mode'];
497
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
502 AND pp.is_active
503 AND pp.is_test = %1";
504 $args[1] = array($mode == 'test' ? 1 : 0, 'Integer');
505
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.";
510 }
511 else {
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.";
515 }
516
517 $dao = CRM_Core_DAO::executeQuery($sql, $args);
518
519 // Check whether we found anything at all ..
520 if (!$dao->N) {
521 CRM_Core_Error::fatal($notfound);
522 }
523
524 $method = 'handle' . $method;
525 $extension_instance_found = FALSE;
526
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 ..
529
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);
536 }
537 else {
538 // Legacy or extension as module instance
539 if (empty($paymentClass)) {
540 $paymentClass = 'CRM_Core_' . $dao->class_name;
541
542 }
543 }
544
545 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($dao->processor_id, $mode);
546
547 // Should never be empty - we already established this processor_id exists and is active.
548 if (empty($paymentProcessor)) {
549 continue;
550 }
551
552 // Instantiate PP
553 $processorInstance = new $paymentClass($mode, $paymentProcessor);
554
555 // Does PP implement this method, and can we call it?
556 if (!method_exists($processorInstance, $method) ||
557 !is_callable(array($processorInstance, $method))
558 ) {
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
561 continue;
562 }
563
564 // Everything, it seems, is ok - execute pp callback handler
565 $processorInstance->$method();
566 $extension_instance_found = TRUE;
567 }
568
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."
573 );
574 }
575
576 // Exit here on web requests, allowing just the plain text response to be echoed
577 if ($method == 'handlePaymentNotification') {
578 CRM_Utils_System::civiExit();
579 }
580 }
581
582 /**
583 * Check whether a method is present ( & supported ) by the payment processor object.
584 *
585 * @param string $method
586 * Method to check for.
587 *
588 * @return boolean
589 */
590 public function isSupported($method = 'cancelSubscription') {
591 return method_exists(CRM_Utils_System::getClassName($this), $method);
592 }
593
594 /**
595 * @param int $entityID
596 * @param null $entity
597 * @param string $action
598 *
599 * @return string
600 */
601 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
602 // Set URL
603 switch ($action) {
604 case 'cancel':
605 $url = 'civicrm/contribute/unsubscribe';
606 break;
607
608 case 'billing':
609 //in notify mode don't return the update billing url
610 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
611 return NULL;
612 }
613 $url = 'civicrm/contribute/updatebilling';
614 break;
615
616 case 'update':
617 $url = 'civicrm/contribute/updaterecur';
618 break;
619 }
620
621 $session = CRM_Core_Session::singleton();
622 $userId = $session->get('userID');
623 $contactID = 0;
624 $checksumValue = '';
625 $entityArg = '';
626
627 // Find related Contact
628 if ($entityID) {
629 switch ($entity) {
630 case 'membership':
631 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
632 $entityArg = 'mid';
633 break;
634
635 case 'contribution':
636 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
637 $entityArg = 'coid';
638 break;
639
640 case 'recur':
641 $sql = "
642 SELECT con.contact_id
643 FROM civicrm_contribution_recur rec
644 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
645 WHERE rec.id = %1
646 GROUP BY rec.id";
647 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
648 $entityArg = 'crid';
649 break;
650 }
651 }
652
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');
658 }
659 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
660 }
661
662 // Else login URL
663 if ($this->isSupported('accountLoginURL')) {
664 return $this->accountLoginURL();
665 }
666
667 // Else default
668 return $this->_paymentProcessor['url_recur'];
669 }
670 }