Merge pull request #6590 from eileenmcnaughton/CRM-16555
[civicrm-core.git] / CRM / Core / Payment.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035 27
914a49bf 28use Civi\Payment\System;
7758bd2b 29use Civi\Payment\Exception\PaymentProcessorException;
353ffa53 30
6a488035 31/**
3782df3e 32 * Class CRM_Core_Payment.
6a488035 33 *
3782df3e 34 * This class is the main class for the payment processor subsystem.
6a488035 35 *
3782df3e
EM
36 * It is the parent class for payment processors. It also holds some IPN related functions
37 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
6a488035 38 */
6a488035
TO
39abstract class CRM_Core_Payment {
40
41 /**
05c302ec
EM
42 * Component - ie. event or contribute.
43 *
44 * This is used for setting return urls.
45 *
46 * @var string
47 */
fd359255
EM
48 protected $_component;
49
05c302ec
EM
50 /**
51 * How are we getting billing information.
52 *
53 * We are trying to completely deprecate these parameters.
6a488035
TO
54 *
55 * FORM - we collect it on the same page
56 * BUTTON - the processor collects it and sends it back to us via some protocol
57 */
7da04cde 58 const
6a488035
TO
59 BILLING_MODE_FORM = 1,
60 BILLING_MODE_BUTTON = 2,
61 BILLING_MODE_NOTIFY = 4;
62
63 /**
100fef9d 64 * Which payment type(s) are we using?
6a488035
TO
65 *
66 * credit card
67 * direct debit
68 * or both
43e5f0f6 69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
6a488035 70 */
7da04cde 71 const
6a488035
TO
72 PAYMENT_TYPE_CREDIT_CARD = 1,
73 PAYMENT_TYPE_DIRECT_DEBIT = 2;
74
75 /**
76 * Subscription / Recurring payment Status
77 * START, END
6a488035 78 */
7da04cde 79 const
6a488035
TO
80 RECURRING_PAYMENT_START = 'START',
81 RECURRING_PAYMENT_END = 'END';
82
353ffa53 83 protected $_paymentProcessor;
6a488035 84
dbbd55dc
EM
85 /**
86 * Opportunity for the payment processor to override the entire form build.
87 *
88 * @param CRM_Core_Form $form
89 *
90 * @return bool
91 * Should form building stop at this point?
92 */
93 public function buildForm(&$form) {
31d31a05 94 return FALSE;
dbbd55dc
EM
95 }
96
e2bef985 97 /**
3782df3e
EM
98 * Log payment notification message to forensic system log.
99 *
43e5f0f6 100 * @todo move to factory class \Civi\Payment\System (or similar)
3782df3e
EM
101 *
102 * @param array $params
103 *
e2bef985 104 * @return mixed
105 */
106 public static function logPaymentNotification($params) {
414e3596 107 $message = 'payment_notification ';
e2bef985 108 if (!empty($params['processor_name'])) {
414e3596 109 $message .= 'processor_name=' . $params['processor_name'];
e2bef985 110 }
111 if (!empty($params['processor_id'])) {
112 $message .= 'processor_id=' . $params['processor_id'];
113 }
414e3596 114
115 $log = new CRM_Utils_SystemLogger();
116 $log->alert($message, $_REQUEST);
e2bef985 117 }
118
fbcb6fba 119 /**
d09edf64 120 * Check if capability is supported.
3782df3e
EM
121 *
122 * Capabilities have a one to one relationship with capability-related functions on this class.
123 *
124 * Payment processor classes should over-ride the capability-specific function rather than this one.
125 *
6a0b768e
TO
126 * @param string $capability
127 * E.g BackOffice, LiveMode, FutureRecurStartDate.
fbcb6fba
EM
128 *
129 * @return bool
130 */
131 public function supports($capability) {
132 $function = 'supports' . ucfirst($capability);
133 if (method_exists($this, $function)) {
134 return $this->$function();
135 }
136 return FALSE;
137 }
138
139 /**
3782df3e
EM
140 * Are back office payments supported.
141 *
142 * e.g paypal standard won't permit you to enter a credit card associated
143 * with someone else's login.
144 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
145 * reach a 'stable' point we disable.
146 *
fbcb6fba
EM
147 * @return bool
148 */
d8ce0d68 149 protected function supportsBackOffice() {
9c39fb25
EM
150 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
151 return FALSE;
152 }
153 else {
154 return TRUE;
155 }
fbcb6fba
EM
156 }
157
75ead8de
EM
158 /**
159 * Can more than one transaction be processed at once?
160 *
161 * In general processors that process payment by server to server communication support this while others do not.
162 *
163 * In future we are likely to hit an issue where this depends on whether a token already exists.
164 *
165 * @return bool
166 */
167 protected function supportsMultipleConcurrentPayments() {
168 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
169 return FALSE;
170 }
171 else {
172 return TRUE;
173 }
174 }
175
fbcb6fba 176 /**
3782df3e
EM
177 * Are live payments supported - e.g dummy doesn't support this.
178 *
fbcb6fba
EM
179 * @return bool
180 */
d8ce0d68 181 protected function supportsLiveMode() {
fbcb6fba
EM
182 return TRUE;
183 }
184
52767de0 185 /**
d09edf64 186 * Are test payments supported.
3782df3e 187 *
52767de0
EM
188 * @return bool
189 */
190 protected function supportsTestMode() {
191 return TRUE;
192 }
193
fbcb6fba 194 /**
d09edf64 195 * Should the first payment date be configurable when setting up back office recurring payments.
3782df3e 196 *
fbcb6fba 197 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
3782df3e 198 *
fbcb6fba
EM
199 * @return bool
200 */
d8ce0d68 201 protected function supportsFutureRecurStartDate() {
fbcb6fba
EM
202 return FALSE;
203 }
204
1e483eb5
EM
205 /**
206 * Does this processor support cancelling recurring contributions through code.
207 *
208 * @return bool
209 */
210 protected function supportsCancelRecurring() {
211 return method_exists(CRM_Utils_System::getClassName($this), 'cancelSubscription');
212 }
213
3910048c
EM
214 /**
215 * Does this processor support pre-approval.
216 *
217 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
218 *
219 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
220 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
221 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
222 *
223 * @return bool
224 */
225 protected function supportsPreApproval() {
226 return FALSE;
227 }
228
677fe56c
EM
229 /**
230 * Can recurring contributions be set against pledges.
231 *
232 * In practice all processors that use the baseIPN function to finish transactions or
233 * call the completetransaction api support this by looking up previous contributions in the
234 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
235 * adding the new payment to the pledge.
236 *
237 * However, only enabling for processors it has been tested against.
238 *
239 * @return bool
240 */
241 protected function supportsRecurContributionsForPledges() {
242 return FALSE;
243 }
244
3910048c
EM
245 /**
246 * Function to action pre-approval if supported
247 *
248 * @param array $params
249 * Parameters from the form
3910048c
EM
250 *
251 * This function returns an array which should contain
252 * - pre_approval_parameters (this will be stored on the calling form & available later)
253 * - redirect_url (if set the browser will be redirected to this.
254 */
677730bd 255 public function doPreApproval(&$params) {}
3910048c 256
3105efd2
EM
257 /**
258 * Get any details that may be available to the payment processor due to an approval process having happened.
259 *
260 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
261 * result.
262 *
263 * @param array $storedDetails
264 *
265 * @return array
266 */
267 public function getPreApprovalDetails($storedDetails) {
268 return array();
269 }
270
6a488035 271 /**
3782df3e
EM
272 * Default payment instrument validation.
273 *
a479fe60 274 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
3782df3e
EM
275 * Not a static function, because I need to check for payment_type.
276 *
277 * @param array $values
278 * @param array $errors
a479fe60 279 */
280 public function validatePaymentInstrument($values, &$errors) {
281 if ($this->_paymentProcessor['payment_type'] == 1) {
282 CRM_Core_Payment_Form::validateCreditCard($values, $errors);
283 }
284 }
285
80bcd255
EM
286 /**
287 * Getter for the payment processor.
288 *
289 * The payment processor array is based on the civicrm_payment_processor table entry.
290 *
291 * @return array
292 * Payment processor array.
293 */
294 public function getPaymentProcessor() {
295 return $this->_paymentProcessor;
296 }
297
298 /**
299 * Setter for the payment processor.
300 *
301 * @param array $processor
302 */
303 public function setPaymentProcessor($processor) {
304 $this->_paymentProcessor = $processor;
305 }
306
6a488035 307 /**
3782df3e
EM
308 * Setter for the payment form that wants to use the processor.
309 *
43e5f0f6 310 * @deprecated
3782df3e 311 *
ac32ed13 312 * @param CRM_Core_Form $paymentForm
6a488035 313 */
00be9182 314 public function setForm(&$paymentForm) {
6a488035
TO
315 $this->_paymentForm = $paymentForm;
316 }
317
318 /**
d09edf64 319 * Getter for payment form that is using the processor.
43e5f0f6 320 * @deprecated
16b10e64
CW
321 * @return CRM_Core_Form
322 * A form object
6a488035 323 */
00be9182 324 public function getForm() {
6a488035
TO
325 return $this->_paymentForm;
326 }
327
328 /**
d09edf64 329 * Getter for accessing member vars.
6c99ada1 330 *
43e5f0f6 331 * @todo believe this is unused
6c99ada1 332 *
100fef9d 333 * @param string $name
dc913073
EM
334 *
335 * @return null
6a488035 336 */
00be9182 337 public function getVar($name) {
6a488035
TO
338 return isset($this->$name) ? $this->$name : NULL;
339 }
340
dc913073 341 /**
d09edf64 342 * Get name for the payment information type.
43e5f0f6 343 * @todo - use option group + name field (like Omnipay does)
dc913073
EM
344 * @return string
345 */
346 public function getPaymentTypeName() {
459091e1 347 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
dc913073
EM
348 }
349
350 /**
d09edf64 351 * Get label for the payment information type.
43e5f0f6 352 * @todo - use option group + labels (like Omnipay does)
dc913073
EM
353 * @return string
354 */
355 public function getPaymentTypeLabel() {
459091e1 356 return $this->_paymentProcessor['payment_type'] == 1 ? 'Credit Card' : 'Direct Debit';
dc913073
EM
357 }
358
44b6505d 359 /**
d09edf64 360 * Get array of fields that should be displayed on the payment form.
44b6505d
EM
361 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
362 * @return array
363 * @throws CiviCRM_API3_Exception
364 */
365 public function getPaymentFormFields() {
dc913073 366 if ($this->_paymentProcessor['billing_mode'] == 4) {
44b6505d
EM
367 return array();
368 }
369 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
370 }
371
372 /**
d09edf64 373 * Get array of fields that should be displayed on the payment form for credit cards.
dc913073 374 *
44b6505d
EM
375 * @return array
376 */
377 protected function getCreditCardFormFields() {
378 return array(
379 'credit_card_type',
380 'credit_card_number',
381 'cvv2',
382 'credit_card_exp_date',
383 );
384 }
385
386 /**
d09edf64 387 * Get array of fields that should be displayed on the payment form for direct debits.
dc913073 388 *
44b6505d
EM
389 * @return array
390 */
391 protected function getDirectDebitFormFields() {
392 return array(
393 'account_holder',
394 'bank_account_number',
395 'bank_identification_number',
396 'bank_name',
397 );
398 }
399
dc913073 400 /**
d09edf64 401 * Return an array of all the details about the fields potentially required for payment fields.
3782df3e 402 *
dc913073
EM
403 * Only those determined by getPaymentFormFields will actually be assigned to the form
404 *
a6c01b45
CW
405 * @return array
406 * field metadata
dc913073
EM
407 */
408 public function getPaymentFormFieldsMetadata() {
409 //@todo convert credit card type into an option value
410 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
411 return array(
412 'credit_card_number' => array(
413 'htmlType' => 'text',
414 'name' => 'credit_card_number',
415 'title' => ts('Card Number'),
416 'cc_field' => TRUE,
417 'attributes' => array(
418 'size' => 20,
419 'maxlength' => 20,
21dfd5f5 420 'autocomplete' => 'off',
f803aacb 421 'class' => 'creditcard',
dc913073
EM
422 ),
423 'is_required' => TRUE,
424 ),
425 'cvv2' => array(
426 'htmlType' => 'text',
427 'name' => 'cvv2',
428 'title' => ts('Security Code'),
429 'cc_field' => TRUE,
430 'attributes' => array(
431 'size' => 5,
432 'maxlength' => 10,
21dfd5f5 433 'autocomplete' => 'off',
dc913073
EM
434 ),
435 'is_required' => CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
436 'cvv_backoffice_required',
437 NULL,
438 1
439 ),
440 'rules' => array(
441 array(
442 '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.'),
443 'rule_name' => 'integer',
444 'rule_parameters' => NULL,
7c550ca0 445 ),
353ffa53 446 ),
dc913073
EM
447 ),
448 'credit_card_exp_date' => array(
449 'htmlType' => 'date',
450 'name' => 'credit_card_exp_date',
451 'title' => ts('Expiration Date'),
452 'cc_field' => TRUE,
453 'attributes' => CRM_Core_SelectValues::date('creditCard'),
454 'is_required' => TRUE,
455 'rules' => array(
456 array(
457 'rule_message' => ts('Card expiration date cannot be a past date.'),
458 'rule_name' => 'currentDate',
459 'rule_parameters' => TRUE,
7c550ca0 460 ),
353ffa53 461 ),
dc913073
EM
462 ),
463 'credit_card_type' => array(
464 'htmlType' => 'select',
465 'name' => 'credit_card_type',
466 'title' => ts('Card Type'),
467 'cc_field' => TRUE,
468 'attributes' => $creditCardType,
469 'is_required' => FALSE,
470 ),
471 'account_holder' => array(
472 'htmlType' => 'text',
473 'name' => 'account_holder',
474 'title' => ts('Account Holder'),
475 'cc_field' => TRUE,
476 'attributes' => array(
477 'size' => 20,
478 'maxlength' => 34,
21dfd5f5 479 'autocomplete' => 'on',
dc913073
EM
480 ),
481 'is_required' => TRUE,
482 ),
483 //e.g. IBAN can have maxlength of 34 digits
484 'bank_account_number' => array(
485 'htmlType' => 'text',
486 'name' => 'bank_account_number',
487 'title' => ts('Bank Account Number'),
488 'cc_field' => TRUE,
489 'attributes' => array(
490 'size' => 20,
491 'maxlength' => 34,
21dfd5f5 492 'autocomplete' => 'off',
dc913073
EM
493 ),
494 'rules' => array(
495 array(
496 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
497 'rule_name' => 'nopunctuation',
498 'rule_parameters' => NULL,
7c550ca0 499 ),
353ffa53 500 ),
dc913073
EM
501 'is_required' => TRUE,
502 ),
503 //e.g. SWIFT-BIC can have maxlength of 11 digits
504 'bank_identification_number' => array(
505 'htmlType' => 'text',
506 'name' => 'bank_identification_number',
507 'title' => ts('Bank Identification Number'),
508 'cc_field' => TRUE,
509 'attributes' => array(
510 'size' => 20,
511 'maxlength' => 11,
21dfd5f5 512 'autocomplete' => 'off',
dc913073
EM
513 ),
514 'is_required' => TRUE,
515 'rules' => array(
516 array(
517 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
518 'rule_name' => 'nopunctuation',
519 'rule_parameters' => NULL,
7c550ca0 520 ),
353ffa53 521 ),
dc913073
EM
522 ),
523 'bank_name' => array(
524 'htmlType' => 'text',
525 'name' => 'bank_name',
526 'title' => ts('Bank Name'),
527 'cc_field' => TRUE,
528 'attributes' => array(
529 'size' => 20,
530 'maxlength' => 64,
21dfd5f5 531 'autocomplete' => 'off',
dc913073
EM
532 ),
533 'is_required' => TRUE,
534
21dfd5f5 535 ),
dc913073
EM
536 );
537 }
44b6505d 538
aefd7f6b
EM
539 /**
540 * Get base url dependent on component.
541 *
542 * @return string|void
543 */
544 protected function getBaseReturnUrl() {
545 if ($this->_component == 'event') {
546 $baseURL = 'civicrm/event/register';
547 }
548 else {
549 $baseURL = 'civicrm/contribute/transact';
550 }
551 return $baseURL;
552 }
553
554 /**
555 * Get url to return to after cancelled or failed transaction
556 *
557 * @param $qfKey
558 * @param $participantID
559 *
560 * @return string cancel url
561 */
562 protected function getCancelUrl($qfKey, $participantID) {
563 if ($this->_component == 'event') {
564 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
565 'reset' => 1,
566 'cc' => 'fail',
567 'participantId' => $participantID,
568 ),
569 TRUE, NULL, FALSE
570 );
571 }
572
573 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
574 '_qf_Main_display' => 1,
575 'qfKey' => $qfKey,
576 'cancel' => 1,
577 ),
578 TRUE, NULL, FALSE
579 );
580 }
581
582 /**
49c882a3 583 * Get URL to return the browser to on success.
aefd7f6b
EM
584 *
585 * @param $qfKey
586 *
587 * @return string
588 */
589 protected function getReturnSuccessUrl($qfKey) {
590 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
591 '_qf_ThankYou_display' => 1,
05237b76 592 'qfKey' => $qfKey,
aefd7f6b
EM
593 ),
594 TRUE, NULL, FALSE
595 );
596 }
597
49c882a3
EM
598 /**
599 * Get URL to return the browser to on failure.
600 *
601 * @param string $key
602 * @param int $participantID
603 * @param int $eventID
604 *
605 * @return string
606 * URL for a failing transactor to be redirected to.
607 */
608 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
6109d8df 609 $test = $this->_is_test ? '&action=preview' : '';
49c882a3
EM
610 if ($this->_component == "event") {
611 return CRM_Utils_System::url('civicrm/event/register',
612 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
613 FALSE, NULL, FALSE
614 );
615 }
616 else {
617 return CRM_Utils_System::url('civicrm/contribute/transact',
618 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
619 FALSE, NULL, FALSE
620 );
621 }
622 }
623
624 /**
625 * Get URl for when the back button is pressed.
626 *
627 * @param $qfKey
628 *
629 * @return string url
630 */
631 protected function getGoBackUrl($qfKey) {
632 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
633 '_qf_Confirm_display' => 'true',
6109d8df 634 'qfKey' => $qfKey,
49c882a3
EM
635 ),
636 TRUE, NULL, FALSE
637 );
638 }
639
640 /**
641 * Get the notify (aka ipn, web hook or silent post) url.
642 *
643 * If there is no '.' in it we assume that we are dealing with localhost or
644 * similar and it is unreachable from the web & hence invalid.
645 *
646 * @return string
647 * URL to notify outcome of transaction.
648 */
649 protected function getNotifyUrl() {
650 $url = CRM_Utils_System::url(
651 'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
652 array(),
653 TRUE
654 );
655 return (stristr($url, '.')) ? $url : '';
656 }
657
6a488035 658 /**
8319cf11
EM
659 * Calling this from outside the payment subsystem is deprecated - use doPayment.
660 *
661 * Does a server to server payment transaction.
662 *
6a0b768e
TO
663 * @param array $params
664 * Assoc array of input parameters for this transaction.
6a488035 665 *
a6c01b45 666 * @return array
863fadaa 667 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
6a488035 668 */
863fadaa
EM
669 protected function doDirectPayment(&$params) {
670 return $params;
671 }
6a488035 672
c1cc3e0c 673 /**
6c99ada1
EM
674 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
675 *
676 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
677 * more agnostic.
c1cc3e0c 678 *
3910048c 679 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
7758bd2b
EM
680 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
681 * doTransferCheckout would not traditionally come back.
682 *
683 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
684 * to be Pending.
685 *
3910048c
EM
686 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
687 * return Error objects
688 *
c1cc3e0c
EM
689 * @param array $params
690 *
7758bd2b 691 * @param string $component
c1cc3e0c 692 *
a6c01b45 693 * @return array
7758bd2b
EM
694 * Result array
695 *
696 * @throws \Civi\Payment\Exception\PaymentProcessorException
c1cc3e0c 697 */
8319cf11 698 public function doPayment(&$params, $component = 'contribute') {
05c302ec 699 $this->_component = $component;
7758bd2b 700 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
c1cc3e0c
EM
701 if ($this->_paymentProcessor['billing_mode'] == 4) {
702 $result = $this->doTransferCheckout($params, $component);
7c85dc65
EM
703 if (is_array($result) && !isset($result['payment_status_id'])) {
704 $result['payment_status_id'] = array_search('Pending', $statuses);
7758bd2b 705 }
c1cc3e0c
EM
706 }
707 else {
f8453bef 708 $result = $this->doDirectPayment($params, $component);
7c85dc65 709 if (is_array($result) && !isset($result['payment_status_id'])) {
9dd58272 710 if (!empty($params['is_recur'])) {
7758bd2b 711 // See comment block.
0816949d 712 $result['payment_status_id'] = array_search('Pending', $statuses);
7758bd2b
EM
713 }
714 else {
7c85dc65 715 $result['payment_status_id'] = array_search('Completed', $statuses);
7758bd2b
EM
716 }
717 }
c1cc3e0c
EM
718 }
719 if (is_a($result, 'CRM_Core_Error')) {
7758bd2b 720 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
c1cc3e0c 721 }
a9cf9972 722 return $result;
c1cc3e0c
EM
723 }
724
9d2f24ee 725 /**
726 * Query payment processor for details about a transaction.
727 *
728 * @param array $params
729 * Array of parameters containing one of:
730 * - trxn_id Id of an individual transaction.
731 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
732 *
733 * @return array
734 * Extra parameters retrieved.
735 * Any parameters retrievable through this should be documented in the function comments at
736 * CRM_Core_Payment::doQuery. Currently:
737 * - fee_amount Amount of fee paid
738 */
739 public function doQuery($params) {
740 return array();
741 }
742
6a488035 743 /**
d09edf64 744 * This function checks to see if we have the right config values.
6a488035 745 *
a6c01b45
CW
746 * @return string
747 * the error message if any
6a488035 748 */
7c550ca0 749 abstract protected function checkConfig();
6a488035 750
a0ee3941 751 /**
6c99ada1
EM
752 * Redirect for paypal.
753 *
754 * @todo move to paypal class or remove
755 *
a0ee3941 756 * @param $paymentProcessor
6c99ada1 757 *
a0ee3941
EM
758 * @return bool
759 */
00be9182 760 public static function paypalRedirect(&$paymentProcessor) {
6a488035
TO
761 if (!$paymentProcessor) {
762 return FALSE;
763 }
764
765 if (isset($_GET['payment_date']) &&
766 isset($_GET['merchant_return_link']) &&
767 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
768 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
769 ) {
770 return TRUE;
771 }
772
773 return FALSE;
774 }
775
776 /**
6c99ada1
EM
777 * Handle incoming payment notification.
778 *
779 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
780 *
43e5f0f6 781 * @todo move to0 \Civi\Payment\System factory method
6a488035 782 * Page callback for civicrm/payment/ipn
6a488035 783 */
00be9182 784 public static function handleIPN() {
6a488035
TO
785 self::handlePaymentMethod(
786 'PaymentNotification',
787 array(
788 'processor_name' => @$_GET['processor_name'],
42b90e8f 789 'processor_id' => @$_GET['processor_id'],
6a488035 790 'mode' => @$_GET['mode'],
4164f4e1 791 'q' => @$_GET['q'],
6a488035
TO
792 )
793 );
160c9df2 794 CRM_Utils_System::civiExit();
6a488035
TO
795 }
796
797 /**
3782df3e
EM
798 * Payment callback handler.
799 *
800 * The processor_name or processor_id is passed in.
43d1ae00
EM
801 * Note that processor_id is more reliable as one site may have more than one instance of a
802 * processor & ideally the processor will be validating the results
6a488035
TO
803 * Load requested payment processor and call that processor's handle<$method> method
804 *
3782df3e
EM
805 * @todo move to \Civi\Payment\System factory method
806 *
807 * @param string $method
808 * 'PaymentNotification' or 'PaymentCron'
4691b077 809 * @param array $params
23de1ac0
EM
810 *
811 * @throws \CRM_Core_Exception
812 * @throws \Exception
6a488035 813 */
00be9182 814 public static function handlePaymentMethod($method, $params = array()) {
42b90e8f 815 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
4164f4e1
EM
816 $q = explode('/', CRM_Utils_Array::value('q', $params, ''));
817 $lastParam = array_pop($q);
818 if (is_numeric($lastParam)) {
819 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
820 }
821 else {
0ac9fd52 822 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
4164f4e1 823 }
6a488035 824 }
4164f4e1 825
e2bef985 826 self::logPaymentNotification($params);
6a488035 827
42b90e8f
CB
828 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
829 FROM civicrm_payment_processor_type ppt
830 INNER JOIN civicrm_payment_processor pp
831 ON pp.payment_processor_type_id = ppt.id
9ff0c7a1 832 AND pp.is_active";
42b90e8f
CB
833
834 if (isset($params['processor_id'])) {
835 $sql .= " WHERE pp.id = %2";
836 $args[2] = array($params['processor_id'], 'Integer');
0ac9fd52 837 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
42b90e8f
CB
838 }
839 else {
9ff0c7a1
EM
840 // This is called when processor_name is passed - passing processor_id instead is recommended.
841 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
6c99ada1
EM
842 $args[1] = array(
843 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
844 'Integer',
845 );
42b90e8f 846 $args[2] = array($params['processor_name'], 'String');
0ac9fd52 847 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
42b90e8f
CB
848 }
849
850 $dao = CRM_Core_DAO::executeQuery($sql, $args);
6a488035 851
3782df3e 852 // Check whether we found anything at all.
6a488035 853 if (!$dao->N) {
3782df3e 854 CRM_Core_Error::fatal($notFound);
6a488035
TO
855 }
856
857 $method = 'handle' . $method;
858 $extension_instance_found = FALSE;
859
860 // In all likelihood, we'll just end up with the one instance returned here. But it's
861 // possible we may get more. Hence, iterate through all instances ..
862
863 while ($dao->fetch()) {
5495e78a 864 // Check pp is extension - is this still required - surely the singleton below handles it.
6a488035
TO
865 $ext = CRM_Extension_System::singleton()->getMapper();
866 if ($ext->isExtensionKey($dao->class_name)) {
6a488035
TO
867 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
868 require_once $ext->classToPath($paymentClass);
869 }
6a488035 870
b47b1631 871 $processorInstance = Civi\Payment\System::singleton()->getById($dao->processor_id);
6a488035
TO
872
873 // Should never be empty - we already established this processor_id exists and is active.
81ebda7b 874 if (empty($processorInstance)) {
6a488035
TO
875 continue;
876 }
877
6a488035
TO
878 // Does PP implement this method, and can we call it?
879 if (!method_exists($processorInstance, $method) ||
880 !is_callable(array($processorInstance, $method))
881 ) {
43d1ae00
EM
882 // on the off chance there is a double implementation of this processor we should keep looking for another
883 // note that passing processor_id is more reliable & we should work to deprecate processor_name
884 continue;
6a488035
TO
885 }
886
887 // Everything, it seems, is ok - execute pp callback handler
888 $processorInstance->$method();
a5ef96f6 889 $extension_instance_found = TRUE;
6a488035
TO
890 }
891
4f99ca55 892 if (!$extension_instance_found) {
0ac9fd52
CB
893 $message = "No extension instances of the '%1' payment processor were found.<br />" .
894 "%2 method is unsupported in legacy payment processors.";
895 CRM_Core_Error::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
2aa397bc 896 }
6a488035
TO
897 }
898
899 /**
100fef9d 900 * Check whether a method is present ( & supported ) by the payment processor object.
6a488035 901 *
1e483eb5
EM
902 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
903 *
6a0b768e
TO
904 * @param string $method
905 * Method to check for.
6a488035 906 *
7c550ca0 907 * @return bool
6a488035 908 */
00be9182 909 public function isSupported($method = 'cancelSubscription') {
6a488035
TO
910 return method_exists(CRM_Utils_System::getClassName($this), $method);
911 }
912
1ba4a3aa
EM
913 /**
914 * Some processors replace the form submit button with their own.
915 *
916 * Returning false here will leave the button off front end forms.
917 *
918 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
919 */
920 public function isSuppressSubmitButtons() {
921 return FALSE;
922 }
923
d253aeb8
EM
924 /**
925 * Checks to see if invoice_id already exists in db.
926 *
927 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
928 * it is better to standardise to being here.
929 *
930 * @param int $invoiceId The ID to check.
931 *
932 * @param null $contributionID
933 * If a contribution exists pass in the contribution ID.
934 *
935 * @return bool
936 * True if invoice ID otherwise exists, else false
937 */
938 protected function checkDupe($invoiceId, $contributionID = NULL) {
939 $contribution = new CRM_Contribute_DAO_Contribution();
940 $contribution->invoice_id = $invoiceId;
941 if ($contributionID) {
942 $contribution->whereAdd("id <> $contributionID");
943 }
944 return $contribution->find();
945 }
946
a0ee3941 947 /**
3782df3e
EM
948 * Get url for users to manage this recurring contribution for this processor.
949 *
100fef9d 950 * @param int $entityID
a0ee3941
EM
951 * @param null $entity
952 * @param string $action
953 *
954 * @return string
955 */
00be9182 956 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
03cfff4c
KW
957 // Set URL
958 switch ($action) {
2aa397bc 959 case 'cancel':
03cfff4c
KW
960 $url = 'civicrm/contribute/unsubscribe';
961 break;
2aa397bc
TO
962
963 case 'billing':
03cfff4c 964 //in notify mode don't return the update billing url
68acd6ae 965 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
03cfff4c
KW
966 return NULL;
967 }
68acd6ae 968 $url = 'civicrm/contribute/updatebilling';
03cfff4c 969 break;
2aa397bc
TO
970
971 case 'update':
03cfff4c
KW
972 $url = 'civicrm/contribute/updaterecur';
973 break;
6a488035
TO
974 }
975
353ffa53
TO
976 $session = CRM_Core_Session::singleton();
977 $userId = $session->get('userID');
978 $contactID = 0;
03cfff4c 979 $checksumValue = '';
353ffa53 980 $entityArg = '';
03cfff4c
KW
981
982 // Find related Contact
983 if ($entityID) {
984 switch ($entity) {
2aa397bc 985 case 'membership':
03cfff4c
KW
986 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
987 $entityArg = 'mid';
988 break;
989
2aa397bc 990 case 'contribution':
03cfff4c
KW
991 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
992 $entityArg = 'coid';
993 break;
994
2aa397bc 995 case 'recur':
03cfff4c 996 $sql = "
6a488035
TO
997 SELECT con.contact_id
998 FROM civicrm_contribution_recur rec
999INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1000 WHERE rec.id = %1
1001 GROUP BY rec.id";
03cfff4c
KW
1002 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
1003 $entityArg = 'crid';
1004 break;
6a488035 1005 }
6a488035
TO
1006 }
1007
03cfff4c
KW
1008 // Add entity arguments
1009 if ($entityArg != '') {
1010 // Add checksum argument
1011 if ($contactID != 0 && $userId != $contactID) {
1012 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1013 }
1014 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1015 }
1016
1017 // Else login URL
6a488035
TO
1018 if ($this->isSupported('accountLoginURL')) {
1019 return $this->accountLoginURL();
1020 }
03cfff4c
KW
1021
1022 // Else default
735d988f 1023 return isset($this->_paymentProcessor['url_recur']) ? $this->_paymentProcessor['url_recur'] : '';
6a488035 1024 }
96025800 1025
6a488035 1026}