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