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