Fix fatal error when sorting by status in activity search
[civicrm-core.git] / CRM / Core / Payment.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
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
a55e39e9 63 /**
64 * Which payment type(s) are we using?
65 *
66 * credit card
67 * direct debit
68 * or both
69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
70 */
71 const
72 PAYMENT_TYPE_CREDIT_CARD = 1,
73 PAYMENT_TYPE_DIRECT_DEBIT = 2;
74
6a488035
TO
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
518fa0ee 83 /**
abf0d662 84 * @var array
518fa0ee 85 */
353ffa53 86 protected $_paymentProcessor;
6a488035 87
ec022878 88 /**
e4555ff1 89 * Base url of the calling form (offsite processors).
ec022878 90 *
91 * @var string
92 */
93 protected $baseReturnUrl;
94
e4555ff1 95 /**
96 * Return url upon success (offsite processors).
97 *
98 * @var string
99 */
100 protected $successUrl;
101
102 /**
103 * Return url upon failure (offsite processors).
104 *
105 * @var string
106 */
107 protected $cancelUrl;
108
e491d0c9
MW
109 /**
110 * Processor type label.
111 *
112 * (Deprecated parameter but used in some messages).
113 *
518fa0ee 114 * @var string
e491d0c9
MW
115 * @deprecated
116 *
e491d0c9
MW
117 */
118 public $_processorName;
119
1d1fee72 120 /**
121 * The profile configured to show on the billing form.
122 *
123 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
124 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
125 * requirements with the configured requirements.
126 *
127 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
128 * of fields.
129 *
130 * Note this change would probably include converting 'billing' to a reserved profile.
131 *
132 * @var int|string
133 */
134 protected $billingProfile;
135
18135422 136 /**
137 * Payment instrument ID.
138 *
139 * This is normally retrieved from the payment_processor table.
140 *
141 * @var int
142 */
143 protected $paymentInstrumentID;
144
145 /**
146 * Is this a back office transaction.
147 *
148 * @var bool
149 */
150 protected $backOffice = FALSE;
151
152 /**
153 * @return bool
154 */
155 public function isBackOffice() {
156 return $this->backOffice;
157 }
158
159 /**
160 * Set back office property.
161 *
162 * @param bool $isBackOffice
163 */
164 public function setBackOffice($isBackOffice) {
165 $this->backOffice = $isBackOffice;
166 }
167
168 /**
169 * Get payment instrument id.
170 *
171 * @return int
172 */
173 public function getPaymentInstrumentID() {
174 return $this->paymentInstrumentID ? $this->paymentInstrumentID : $this->_paymentProcessor['payment_instrument_id'];
175 }
176
31eddd0d 177 /**
178 * Getter for the id.
179 *
180 * @return int
181 */
182 public function getID() {
183 return (int) $this->_paymentProcessor['id'];
184 }
185
18135422 186 /**
187 * Set payment Instrument id.
188 *
189 * By default we actually ignore the form value. The manual processor takes it more seriously.
190 *
191 * @param int $paymentInstrumentID
192 */
193 public function setPaymentInstrumentID($paymentInstrumentID) {
194 $this->paymentInstrumentID = $this->_paymentProcessor['payment_instrument_id'];
195 }
196
ec022878 197 /**
e4555ff1 198 * Set base return path (offsite processors).
199 *
200 * This is only useful with an internal civicrm form.
ec022878 201 *
202 * @param string $url
e4555ff1 203 * Internal civicrm path.
ec022878 204 */
205 public function setBaseReturnUrl($url) {
206 $this->baseReturnUrl = $url;
207 }
208
e4555ff1 209 /**
210 * Set success return URL (offsite processors).
211 *
212 * This overrides $baseReturnUrl
213 *
214 * @param string $url
215 * Full url of site to return browser to upon success.
216 */
217 public function setSuccessUrl($url) {
218 $this->successUrl = $url;
219 }
220
221 /**
222 * Set cancel return URL (offsite processors).
223 *
224 * This overrides $baseReturnUrl
225 *
226 * @param string $url
227 * Full url of site to return browser to upon failure.
228 */
229 public function setCancelUrl($url) {
230 $this->cancelUrl = $url;
231 }
232
1d1fee72 233 /**
234 * Set the configured payment profile.
235 *
236 * @param int|string $value
237 */
238 public function setBillingProfile($value) {
239 $this->billingProfile = $value;
240 }
241
dbbd55dc
EM
242 /**
243 * Opportunity for the payment processor to override the entire form build.
244 *
245 * @param CRM_Core_Form $form
246 *
247 * @return bool
248 * Should form building stop at this point?
249 */
250 public function buildForm(&$form) {
31d31a05 251 return FALSE;
dbbd55dc
EM
252 }
253
e2bef985 254 /**
3782df3e
EM
255 * Log payment notification message to forensic system log.
256 *
43e5f0f6 257 * @todo move to factory class \Civi\Payment\System (or similar)
3782df3e
EM
258 *
259 * @param array $params
e2bef985 260 */
261 public static function logPaymentNotification($params) {
414e3596 262 $message = 'payment_notification ';
e2bef985 263 if (!empty($params['processor_name'])) {
414e3596 264 $message .= 'processor_name=' . $params['processor_name'];
e2bef985 265 }
266 if (!empty($params['processor_id'])) {
267 $message .= 'processor_id=' . $params['processor_id'];
268 }
414e3596 269
270 $log = new CRM_Utils_SystemLogger();
d66880ec
JG
271 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
272 $rawRequestData = file_get_contents("php://input");
273 if (CRM_Utils_JSON::isValidJSON($rawRequestData)) {
274 $log->alert($message, json_decode($rawRequestData, TRUE));
275 }
276 else {
277 $log->alert($message, $_REQUEST);
278 }
e2bef985 279 }
280
fbcb6fba 281 /**
d09edf64 282 * Check if capability is supported.
3782df3e
EM
283 *
284 * Capabilities have a one to one relationship with capability-related functions on this class.
285 *
286 * Payment processor classes should over-ride the capability-specific function rather than this one.
287 *
6a0b768e
TO
288 * @param string $capability
289 * E.g BackOffice, LiveMode, FutureRecurStartDate.
fbcb6fba
EM
290 *
291 * @return bool
292 */
293 public function supports($capability) {
294 $function = 'supports' . ucfirst($capability);
295 if (method_exists($this, $function)) {
296 return $this->$function();
297 }
298 return FALSE;
299 }
300
301 /**
3782df3e
EM
302 * Are back office payments supported.
303 *
304 * e.g paypal standard won't permit you to enter a credit card associated
305 * with someone else's login.
306 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
307 * reach a 'stable' point we disable.
308 *
fbcb6fba
EM
309 * @return bool
310 */
d8ce0d68 311 protected function supportsBackOffice() {
9c39fb25
EM
312 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
313 return FALSE;
314 }
315 else {
316 return TRUE;
317 }
fbcb6fba
EM
318 }
319
75ead8de
EM
320 /**
321 * Can more than one transaction be processed at once?
322 *
323 * In general processors that process payment by server to server communication support this while others do not.
324 *
325 * In future we are likely to hit an issue where this depends on whether a token already exists.
326 *
327 * @return bool
328 */
329 protected function supportsMultipleConcurrentPayments() {
330 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
331 return FALSE;
332 }
333 else {
334 return TRUE;
335 }
336 }
337
fbcb6fba 338 /**
3782df3e
EM
339 * Are live payments supported - e.g dummy doesn't support this.
340 *
fbcb6fba
EM
341 * @return bool
342 */
d8ce0d68 343 protected function supportsLiveMode() {
fbcb6fba
EM
344 return TRUE;
345 }
346
52767de0 347 /**
d09edf64 348 * Are test payments supported.
3782df3e 349 *
52767de0
EM
350 * @return bool
351 */
352 protected function supportsTestMode() {
353 return TRUE;
354 }
355
6bc775cf
MD
356 /**
357 * Does this payment processor support refund?
358 *
359 * @return bool
360 */
361 public function supportsRefund() {
362 return FALSE;
363 }
364
fbcb6fba 365 /**
d09edf64 366 * Should the first payment date be configurable when setting up back office recurring payments.
3782df3e 367 *
fbcb6fba 368 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
3782df3e 369 *
fbcb6fba
EM
370 * @return bool
371 */
d8ce0d68 372 protected function supportsFutureRecurStartDate() {
fbcb6fba
EM
373 return FALSE;
374 }
375
1e483eb5
EM
376 /**
377 * Does this processor support cancelling recurring contributions through code.
378 *
3e473c0b 379 * If the processor returns true it must be possible to take action from within CiviCRM
380 * that will result in no further payments being processed. In the case of token processors (e.g
381 * IATS, eWay) updating the contribution_recur table is probably sufficient.
382 *
1e483eb5
EM
383 * @return bool
384 */
385 protected function supportsCancelRecurring() {
386 return method_exists(CRM_Utils_System::getClassName($this), 'cancelSubscription');
387 }
388
3910048c
EM
389 /**
390 * Does this processor support pre-approval.
391 *
392 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
393 *
394 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
395 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
396 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
397 *
398 * @return bool
399 */
400 protected function supportsPreApproval() {
401 return FALSE;
402 }
403
b690491e
MWMC
404 /**
405 * Does this processor support updating billing info for recurring contributions through code.
406 *
407 * If the processor returns true then it must be possible to update billing info from within CiviCRM
408 * that will be updated at the payment processor.
409 *
410 * @return bool
411 */
412 protected function supportsUpdateSubscriptionBillingInfo() {
413 return method_exists(CRM_Utils_System::getClassName($this), 'updateSubscriptionBillingInfo');
414 }
415
677fe56c
EM
416 /**
417 * Can recurring contributions be set against pledges.
418 *
419 * In practice all processors that use the baseIPN function to finish transactions or
420 * call the completetransaction api support this by looking up previous contributions in the
421 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
422 * adding the new payment to the pledge.
423 *
424 * However, only enabling for processors it has been tested against.
425 *
426 * @return bool
427 */
428 protected function supportsRecurContributionsForPledges() {
429 return FALSE;
430 }
431
3910048c
EM
432 /**
433 * Function to action pre-approval if supported
434 *
435 * @param array $params
436 * Parameters from the form
3910048c
EM
437 *
438 * This function returns an array which should contain
439 * - pre_approval_parameters (this will be stored on the calling form & available later)
440 * - redirect_url (if set the browser will be redirected to this.
441 */
9e3bf561 442 public function doPreApproval(&$params) {
443 }
3910048c 444
3105efd2
EM
445 /**
446 * Get any details that may be available to the payment processor due to an approval process having happened.
447 *
448 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
449 * result.
450 *
451 * @param array $storedDetails
452 *
453 * @return array
454 */
455 public function getPreApprovalDetails($storedDetails) {
9e3bf561 456 return [];
3105efd2
EM
457 }
458
6a488035 459 /**
3782df3e
EM
460 * Default payment instrument validation.
461 *
a479fe60 462 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
3782df3e
EM
463 * Not a static function, because I need to check for payment_type.
464 *
465 * @param array $values
466 * @param array $errors
a479fe60 467 */
468 public function validatePaymentInstrument($values, &$errors) {
c319039f 469 CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
a479fe60 470 if ($this->_paymentProcessor['payment_type'] == 1) {
06051ca4 471 CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
a479fe60 472 }
473 }
474
80bcd255
EM
475 /**
476 * Getter for the payment processor.
477 *
478 * The payment processor array is based on the civicrm_payment_processor table entry.
479 *
480 * @return array
481 * Payment processor array.
482 */
483 public function getPaymentProcessor() {
484 return $this->_paymentProcessor;
485 }
486
487 /**
488 * Setter for the payment processor.
489 *
490 * @param array $processor
491 */
492 public function setPaymentProcessor($processor) {
493 $this->_paymentProcessor = $processor;
494 }
495
6a488035 496 /**
3782df3e
EM
497 * Setter for the payment form that wants to use the processor.
498 *
43e5f0f6 499 * @deprecated
3782df3e 500 *
ac32ed13 501 * @param CRM_Core_Form $paymentForm
6a488035 502 */
00be9182 503 public function setForm(&$paymentForm) {
6a488035
TO
504 $this->_paymentForm = $paymentForm;
505 }
506
507 /**
d09edf64 508 * Getter for payment form that is using the processor.
43e5f0f6 509 * @deprecated
16b10e64
CW
510 * @return CRM_Core_Form
511 * A form object
6a488035 512 */
00be9182 513 public function getForm() {
6a488035
TO
514 return $this->_paymentForm;
515 }
516
6841f76b 517 /**
518 * Get help text information (help, description, etc.) about this payment,
519 * to display to the user.
520 *
521 * @param string $context
522 * Context of the text.
523 * Only explicitly supported contexts are handled without error.
524 * Currently supported:
525 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
526 *
527 * @param array $params
528 * Parameters for the field, context specific.
529 *
530 * @return string
531 */
532 public function getText($context, $params) {
533 // I have deliberately added a noisy fail here.
534 // The function is intended to be extendable, but not by changes
535 // not documented clearly above.
536 switch ($context) {
537 case 'contributionPageRecurringHelp':
538 // require exactly two parameters
9e3bf561 539 if (array_keys($params) == [
518fa0ee
SL
540 'is_recur_installments',
541 'is_email_receipt',
542 ]) {
6841f76b 543 $gotText = ts('Your recurring contribution will be processed automatically.');
544 if ($params['is_recur_installments']) {
8567f420 545 $gotText .= ' ' . ts('You can specify the number of installments, or you can leave the number of installments blank if you want to make an open-ended commitment. In either case, you can choose to cancel at any time.');
6841f76b 546 }
547 if ($params['is_email_receipt']) {
8567f420 548 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
6841f76b 549 }
550 }
e364c762 551 return $gotText;
552
553 case 'contributionPageContinueText':
554 if ($params['amount'] <= 0) {
555 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
556 }
557 if ($this->_paymentProcessor['billing_mode'] == 4) {
558 return ts('Click the <strong>Continue</strong> button to go to %1, where you will select your payment method and complete the contribution.', [$this->_paymentProcessor['payment_processor_type']]);
559 }
560 if ($params['is_payment_to_existing']) {
561 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
562 }
563 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
564
6841f76b 565 }
e364c762 566 CRM_Core_Error::deprecatedFunctionWarning('Calls to getText must use a supported method');
567 return '';
6841f76b 568 }
569
6a488035 570 /**
d09edf64 571 * Getter for accessing member vars.
6c99ada1 572 *
43e5f0f6 573 * @todo believe this is unused
6c99ada1 574 *
100fef9d 575 * @param string $name
dc913073
EM
576 *
577 * @return null
6a488035 578 */
00be9182 579 public function getVar($name) {
6a488035
TO
580 return isset($this->$name) ? $this->$name : NULL;
581 }
582
dc913073 583 /**
d09edf64 584 * Get name for the payment information type.
43e5f0f6 585 * @todo - use option group + name field (like Omnipay does)
dc913073
EM
586 * @return string
587 */
588 public function getPaymentTypeName() {
459091e1 589 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
dc913073
EM
590 }
591
592 /**
d09edf64 593 * Get label for the payment information type.
43e5f0f6 594 * @todo - use option group + labels (like Omnipay does)
dc913073
EM
595 * @return string
596 */
597 public function getPaymentTypeLabel() {
526d9a06 598 return $this->_paymentProcessor['payment_type'] == 1 ? ts('Credit Card') : ts('Direct Debit');
dc913073
EM
599 }
600
44b6505d 601 /**
d09edf64 602 * Get array of fields that should be displayed on the payment form.
9f7f8a50 603 *
604 * Common results are
605 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
606 * or
607 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
608 * or
609 * array()
610 *
44b6505d 611 * @return array
9f7f8a50 612 * Array of payment fields appropriate to the payment processor.
613 *
44b6505d
EM
614 * @throws CiviCRM_API3_Exception
615 */
616 public function getPaymentFormFields() {
dc913073 617 if ($this->_paymentProcessor['billing_mode'] == 4) {
9e3bf561 618 return [];
44b6505d
EM
619 }
620 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
621 }
622
0c6c47a5 623 /**
624 * Get an array of the fields that can be edited on the recurring contribution.
625 *
626 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
627 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
628 * can be updated from the contribution recur edit screen.
629 *
630 * The fields are likely to be a subset of these
631 * - 'amount',
632 * - 'installments',
633 * - 'frequency_interval',
634 * - 'frequency_unit',
635 * - 'cycle_day',
636 * - 'next_sched_contribution_date',
637 * - 'end_date',
638 * - 'failure_retry_day',
639 *
640 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
641 * metadata is not defined in the xml for the field it will cause an error.
642 *
643 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
644 * form (UpdateSubscription).
645 *
646 * @return array
647 */
648 public function getEditableRecurringScheduleFields() {
b690491e 649 if ($this->supports('changeSubscriptionAmount')) {
9e3bf561 650 return ['amount'];
0c6c47a5 651 }
71e680bd 652 return [];
0c6c47a5 653 }
654
655 /**
656 * Get the help text to present on the recurring update page.
657 *
658 * This should reflect what can or cannot be edited.
659 *
660 * @return string
661 */
662 public function getRecurringScheduleUpdateHelpText() {
663 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
664 return ts('Updates made using this form will change the recurring contribution information stored in your CiviCRM database, but will NOT be sent to the payment processor. You must enter the same changes using the payment processor web site.');
665 }
666 return ts('Use this form to change the amount or number of installments for this recurring contribution. Changes will be automatically sent to the payment processor. You can not change the contribution frequency.');
667 }
668
c319039f 669 /**
670 * Get the metadata for all required fields.
671 *
672 * @return array;
673 */
674 protected function getMandatoryFields() {
9e3bf561 675 $mandatoryFields = [];
c319039f 676 foreach ($this->getAllFields() as $field_name => $field_spec) {
677 if (!empty($field_spec['is_required'])) {
678 $mandatoryFields[$field_name] = $field_spec;
679 }
680 }
681 return $mandatoryFields;
682 }
683
684 /**
685 * Get the metadata of all the fields configured for this processor.
686 *
687 * @return array
688 */
689 protected function getAllFields() {
690 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
691 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
692 return array_merge($paymentFields, $billingFields);
693 }
9e3bf561 694
44b6505d 695 /**
d09edf64 696 * Get array of fields that should be displayed on the payment form for credit cards.
dc913073 697 *
44b6505d
EM
698 * @return array
699 */
700 protected function getCreditCardFormFields() {
9e3bf561 701 return [
44b6505d
EM
702 'credit_card_type',
703 'credit_card_number',
704 'cvv2',
705 'credit_card_exp_date',
9e3bf561 706 ];
44b6505d
EM
707 }
708
709 /**
d09edf64 710 * Get array of fields that should be displayed on the payment form for direct debits.
dc913073 711 *
44b6505d
EM
712 * @return array
713 */
714 protected function getDirectDebitFormFields() {
9e3bf561 715 return [
44b6505d
EM
716 'account_holder',
717 'bank_account_number',
718 'bank_identification_number',
719 'bank_name',
9e3bf561 720 ];
44b6505d
EM
721 }
722
dc913073 723 /**
d09edf64 724 * Return an array of all the details about the fields potentially required for payment fields.
3782df3e 725 *
dc913073
EM
726 * Only those determined by getPaymentFormFields will actually be assigned to the form
727 *
a6c01b45
CW
728 * @return array
729 * field metadata
dc913073
EM
730 */
731 public function getPaymentFormFieldsMetadata() {
732 //@todo convert credit card type into an option value
9e3bf561 733 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::creditCard();
02d3eb1c
AP
734 $isCVVRequired = Civi::settings()->get('cvv_backoffice_required');
735 if (!$this->isBackOffice()) {
736 $isCVVRequired = TRUE;
737 }
9e3bf561 738 return [
739 'credit_card_number' => [
dc913073
EM
740 'htmlType' => 'text',
741 'name' => 'credit_card_number',
742 'title' => ts('Card Number'),
9e3bf561 743 'attributes' => [
dc913073
EM
744 'size' => 20,
745 'maxlength' => 20,
21dfd5f5 746 'autocomplete' => 'off',
f803aacb 747 'class' => 'creditcard',
9e3bf561 748 ],
dc913073 749 'is_required' => TRUE,
4533376a 750 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
9e3bf561 751 ],
752 'cvv2' => [
dc913073
EM
753 'htmlType' => 'text',
754 'name' => 'cvv2',
755 'title' => ts('Security Code'),
9e3bf561 756 'attributes' => [
dc913073
EM
757 'size' => 5,
758 'maxlength' => 10,
21dfd5f5 759 'autocomplete' => 'off',
9e3bf561 760 ],
02d3eb1c 761 'is_required' => $isCVVRequired,
9e3bf561 762 'rules' => [
763 [
dc913073
EM
764 '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.'),
765 'rule_name' => 'integer',
766 'rule_parameters' => NULL,
9e3bf561 767 ],
768 ],
769 ],
770 'credit_card_exp_date' => [
dc913073
EM
771 'htmlType' => 'date',
772 'name' => 'credit_card_exp_date',
773 'title' => ts('Expiration Date'),
dc913073
EM
774 'attributes' => CRM_Core_SelectValues::date('creditCard'),
775 'is_required' => TRUE,
9e3bf561 776 'rules' => [
777 [
dc913073
EM
778 'rule_message' => ts('Card expiration date cannot be a past date.'),
779 'rule_name' => 'currentDate',
780 'rule_parameters' => TRUE,
9e3bf561 781 ],
782 ],
69e1be3a 783 'extra' => ['class' => 'crm-form-select'],
9e3bf561 784 ],
785 'credit_card_type' => [
dc913073
EM
786 'htmlType' => 'select',
787 'name' => 'credit_card_type',
788 'title' => ts('Card Type'),
dc913073
EM
789 'attributes' => $creditCardType,
790 'is_required' => FALSE,
9e3bf561 791 ],
792 'account_holder' => [
dc913073
EM
793 'htmlType' => 'text',
794 'name' => 'account_holder',
795 'title' => ts('Account Holder'),
9e3bf561 796 'attributes' => [
dc913073
EM
797 'size' => 20,
798 'maxlength' => 34,
21dfd5f5 799 'autocomplete' => 'on',
9e3bf561 800 ],
dc913073 801 'is_required' => TRUE,
9e3bf561 802 ],
dc913073 803 //e.g. IBAN can have maxlength of 34 digits
9e3bf561 804 'bank_account_number' => [
dc913073
EM
805 'htmlType' => 'text',
806 'name' => 'bank_account_number',
807 'title' => ts('Bank Account Number'),
9e3bf561 808 'attributes' => [
dc913073
EM
809 'size' => 20,
810 'maxlength' => 34,
21dfd5f5 811 'autocomplete' => 'off',
9e3bf561 812 ],
813 'rules' => [
814 [
dc913073
EM
815 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
816 'rule_name' => 'nopunctuation',
817 'rule_parameters' => NULL,
9e3bf561 818 ],
819 ],
dc913073 820 'is_required' => TRUE,
9e3bf561 821 ],
dc913073 822 //e.g. SWIFT-BIC can have maxlength of 11 digits
9e3bf561 823 'bank_identification_number' => [
dc913073
EM
824 'htmlType' => 'text',
825 'name' => 'bank_identification_number',
826 'title' => ts('Bank Identification Number'),
9e3bf561 827 'attributes' => [
dc913073
EM
828 'size' => 20,
829 'maxlength' => 11,
21dfd5f5 830 'autocomplete' => 'off',
9e3bf561 831 ],
dc913073 832 'is_required' => TRUE,
9e3bf561 833 'rules' => [
834 [
dc913073
EM
835 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
836 'rule_name' => 'nopunctuation',
837 'rule_parameters' => NULL,
9e3bf561 838 ],
839 ],
840 ],
841 'bank_name' => [
dc913073
EM
842 'htmlType' => 'text',
843 'name' => 'bank_name',
844 'title' => ts('Bank Name'),
9e3bf561 845 'attributes' => [
dc913073
EM
846 'size' => 20,
847 'maxlength' => 64,
21dfd5f5 848 'autocomplete' => 'off',
9e3bf561 849 ],
dc913073
EM
850 'is_required' => TRUE,
851
9e3bf561 852 ],
853 'check_number' => [
794d4fc0 854 'htmlType' => 'text',
855 'name' => 'check_number',
856 'title' => ts('Check Number'),
857 'is_required' => FALSE,
794d4fc0 858 'attributes' => NULL,
9e3bf561 859 ],
860 'pan_truncation' => [
794d4fc0 861 'htmlType' => 'text',
862 'name' => 'pan_truncation',
863 'title' => ts('Last 4 digits of the card'),
864 'is_required' => FALSE,
9e3bf561 865 'attributes' => [
794d4fc0 866 'size' => 4,
867 'maxlength' => 4,
a7f2d5fd 868 'minlength' => 4,
794d4fc0 869 'autocomplete' => 'off',
9e3bf561 870 ],
871 'rules' => [
872 [
a55e39e9 873 'rule_message' => ts('Please enter valid last 4 digit card number.'),
874 'rule_name' => 'numeric',
875 'rule_parameters' => NULL,
9e3bf561 876 ],
877 ],
878 ],
879 'payment_token' => [
c42f1a19 880 'htmlType' => 'hidden',
881 'name' => 'payment_token',
882 'title' => ts('Authorization token'),
883 'is_required' => FALSE,
9e3bf561 884 'attributes' => [
885 'size' => 10,
886 'autocomplete' => 'off',
887 'id' => 'payment_token',
888 ],
889 ],
890 ];
dc913073 891 }
44b6505d 892
3310ab71 893 /**
894 * Get billing fields required for this processor.
895 *
896 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
897 * alter.
898 *
899 * @param int $billingLocationID
900 *
901 * @return array
902 */
b576d770 903 public function getBillingAddressFields($billingLocationID = NULL) {
904 if (!$billingLocationID) {
905 // Note that although the billing id is passed around the forms the idea that it would be anything other than
906 // the result of the function below doesn't seem to have eventuated.
907 // So taking this as a param is possibly something to be removed in favour of the standard default.
908 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
909 }
3310ab71 910 if ($this->_paymentProcessor['billing_mode'] != 1 && $this->_paymentProcessor['billing_mode'] != 3) {
9e3bf561 911 return [];
3310ab71 912 }
9e3bf561 913 return [
3310ab71 914 'first_name' => 'billing_first_name',
915 'middle_name' => 'billing_middle_name',
916 'last_name' => 'billing_last_name',
917 'street_address' => "billing_street_address-{$billingLocationID}",
918 'city' => "billing_city-{$billingLocationID}",
919 'country' => "billing_country_id-{$billingLocationID}",
920 'state_province' => "billing_state_province_id-{$billingLocationID}",
921 'postal_code' => "billing_postal_code-{$billingLocationID}",
9e3bf561 922 ];
3310ab71 923 }
924
925 /**
926 * Get form metadata for billing address fields.
927 *
928 * @param int $billingLocationID
929 *
930 * @return array
518fa0ee 931 * Array of metadata for address fields.
3310ab71 932 */
b576d770 933 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
934 if (!$billingLocationID) {
935 // Note that although the billing id is passed around the forms the idea that it would be anything other than
936 // the result of the function below doesn't seem to have eventuated.
937 // So taking this as a param is possibly something to be removed in favour of the standard default.
938 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
939 }
9e3bf561 940 $metadata = [];
941 $metadata['billing_first_name'] = [
3310ab71 942 'htmlType' => 'text',
943 'name' => 'billing_first_name',
944 'title' => ts('Billing First Name'),
945 'cc_field' => TRUE,
9e3bf561 946 'attributes' => [
3310ab71 947 'size' => 30,
948 'maxlength' => 60,
949 'autocomplete' => 'off',
9e3bf561 950 ],
3310ab71 951 'is_required' => TRUE,
9e3bf561 952 ];
3310ab71 953
9e3bf561 954 $metadata['billing_middle_name'] = [
3310ab71 955 'htmlType' => 'text',
956 'name' => 'billing_middle_name',
957 'title' => ts('Billing Middle Name'),
958 'cc_field' => TRUE,
9e3bf561 959 'attributes' => [
3310ab71 960 'size' => 30,
961 'maxlength' => 60,
962 'autocomplete' => 'off',
9e3bf561 963 ],
3310ab71 964 'is_required' => FALSE,
9e3bf561 965 ];
3310ab71 966
9e3bf561 967 $metadata['billing_last_name'] = [
3310ab71 968 'htmlType' => 'text',
969 'name' => 'billing_last_name',
970 'title' => ts('Billing Last Name'),
971 'cc_field' => TRUE,
9e3bf561 972 'attributes' => [
3310ab71 973 'size' => 30,
974 'maxlength' => 60,
975 'autocomplete' => 'off',
9e3bf561 976 ],
3310ab71 977 'is_required' => TRUE,
9e3bf561 978 ];
3310ab71 979
9e3bf561 980 $metadata["billing_street_address-{$billingLocationID}"] = [
3310ab71 981 'htmlType' => 'text',
982 'name' => "billing_street_address-{$billingLocationID}",
983 'title' => ts('Street Address'),
984 'cc_field' => TRUE,
9e3bf561 985 'attributes' => [
3310ab71 986 'size' => 30,
987 'maxlength' => 60,
988 'autocomplete' => 'off',
9e3bf561 989 ],
3310ab71 990 'is_required' => TRUE,
9e3bf561 991 ];
3310ab71 992
9e3bf561 993 $metadata["billing_city-{$billingLocationID}"] = [
3310ab71 994 'htmlType' => 'text',
995 'name' => "billing_city-{$billingLocationID}",
996 'title' => ts('City'),
997 'cc_field' => TRUE,
9e3bf561 998 'attributes' => [
3310ab71 999 'size' => 30,
1000 'maxlength' => 60,
1001 'autocomplete' => 'off',
9e3bf561 1002 ],
3310ab71 1003 'is_required' => TRUE,
9e3bf561 1004 ];
3310ab71 1005
9e3bf561 1006 $metadata["billing_state_province_id-{$billingLocationID}"] = [
3310ab71 1007 'htmlType' => 'chainSelect',
1008 'title' => ts('State/Province'),
1009 'name' => "billing_state_province_id-{$billingLocationID}",
1010 'cc_field' => TRUE,
1011 'is_required' => TRUE,
9e3bf561 1012 ];
3310ab71 1013
9e3bf561 1014 $metadata["billing_postal_code-{$billingLocationID}"] = [
3310ab71 1015 'htmlType' => 'text',
1016 'name' => "billing_postal_code-{$billingLocationID}",
1017 'title' => ts('Postal Code'),
1018 'cc_field' => TRUE,
9e3bf561 1019 'attributes' => [
3310ab71 1020 'size' => 30,
1021 'maxlength' => 60,
1022 'autocomplete' => 'off',
9e3bf561 1023 ],
3310ab71 1024 'is_required' => TRUE,
9e3bf561 1025 ];
3310ab71 1026
9e3bf561 1027 $metadata["billing_country_id-{$billingLocationID}"] = [
3310ab71 1028 'htmlType' => 'select',
1029 'name' => "billing_country_id-{$billingLocationID}",
1030 'title' => ts('Country'),
1031 'cc_field' => TRUE,
9e3bf561 1032 'attributes' => [
518fa0ee
SL
1033 '' => ts('- select -'),
1034 ] + CRM_Core_PseudoConstant::country(),
3310ab71 1035 'is_required' => TRUE,
9e3bf561 1036 ];
3310ab71 1037 return $metadata;
1038 }
1039
aefd7f6b
EM
1040 /**
1041 * Get base url dependent on component.
1042 *
ec022878 1043 * (or preferably set it using the setter function).
1044 *
1045 * @return string
aefd7f6b
EM
1046 */
1047 protected function getBaseReturnUrl() {
ec022878 1048 if ($this->baseReturnUrl) {
1049 return $this->baseReturnUrl;
1050 }
aefd7f6b
EM
1051 if ($this->_component == 'event') {
1052 $baseURL = 'civicrm/event/register';
1053 }
1054 else {
1055 $baseURL = 'civicrm/contribute/transact';
1056 }
1057 return $baseURL;
1058 }
1059
899c09b3 1060 /**
1061 * Get the currency for the transaction.
1062 *
1063 * Handle any inconsistency about how it is passed in here.
1064 *
1065 * @param $params
1066 *
1067 * @return string
1068 */
05bf1fb0 1069 protected function getCurrency($params) {
1070 return CRM_Utils_Array::value('currencyID', $params, CRM_Utils_Array::value('currency', $params));
899c09b3 1071 }
1072
88afada7 1073 /**
1074 * Get the currency for the transaction.
1075 *
1076 * Handle any inconsistency about how it is passed in here.
1077 *
05bf1fb0 1078 * @param $params
88afada7 1079 *
1080 * @return string
1081 */
05bf1fb0 1082 protected function getAmount($params) {
1083 return CRM_Utils_Money::format($params['amount'], NULL, NULL, TRUE);
88afada7 1084 }
1085
aefd7f6b 1086 /**
ddc4b5af 1087 * Get url to return to after cancelled or failed transaction.
aefd7f6b 1088 *
ddc4b5af 1089 * @param string $qfKey
1090 * @param int $participantID
aefd7f6b
EM
1091 *
1092 * @return string cancel url
1093 */
abfb35ee 1094 public function getCancelUrl($qfKey, $participantID) {
e4555ff1 1095 if (isset($this->cancelUrl)) {
1096 return $this->cancelUrl;
1097 }
1098
aefd7f6b 1099 if ($this->_component == 'event') {
9e3bf561 1100 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
aefd7f6b
EM
1101 'reset' => 1,
1102 'cc' => 'fail',
1103 'participantId' => $participantID,
9e3bf561 1104 ],
aefd7f6b
EM
1105 TRUE, NULL, FALSE
1106 );
1107 }
1108
9e3bf561 1109 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
aefd7f6b
EM
1110 '_qf_Main_display' => 1,
1111 'qfKey' => $qfKey,
1112 'cancel' => 1,
9e3bf561 1113 ],
aefd7f6b
EM
1114 TRUE, NULL, FALSE
1115 );
1116 }
1117
1118 /**
49c882a3 1119 * Get URL to return the browser to on success.
aefd7f6b
EM
1120 *
1121 * @param $qfKey
1122 *
1123 * @return string
1124 */
1125 protected function getReturnSuccessUrl($qfKey) {
e4555ff1 1126 if (isset($this->successUrl)) {
1127 return $this->successUrl;
1128 }
1129
9e3bf561 1130 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
aefd7f6b 1131 '_qf_ThankYou_display' => 1,
05237b76 1132 'qfKey' => $qfKey,
9e3bf561 1133 ],
aefd7f6b
EM
1134 TRUE, NULL, FALSE
1135 );
1136 }
1137
49c882a3
EM
1138 /**
1139 * Get URL to return the browser to on failure.
1140 *
1141 * @param string $key
1142 * @param int $participantID
1143 * @param int $eventID
1144 *
1145 * @return string
1146 * URL for a failing transactor to be redirected to.
1147 */
1148 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
e4555ff1 1149 if (isset($this->cancelUrl)) {
1150 return $this->cancelUrl;
1151 }
1152
6109d8df 1153 $test = $this->_is_test ? '&action=preview' : '';
49c882a3
EM
1154 if ($this->_component == "event") {
1155 return CRM_Utils_System::url('civicrm/event/register',
1156 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1157 FALSE, NULL, FALSE
1158 );
1159 }
1160 else {
1161 return CRM_Utils_System::url('civicrm/contribute/transact',
1162 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1163 FALSE, NULL, FALSE
1164 );
1165 }
1166 }
1167
1168 /**
1169 * Get URl for when the back button is pressed.
1170 *
1171 * @param $qfKey
1172 *
1173 * @return string url
1174 */
1175 protected function getGoBackUrl($qfKey) {
9e3bf561 1176 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
49c882a3 1177 '_qf_Confirm_display' => 'true',
6109d8df 1178 'qfKey' => $qfKey,
9e3bf561 1179 ],
49c882a3
EM
1180 TRUE, NULL, FALSE
1181 );
1182 }
1183
1184 /**
1185 * Get the notify (aka ipn, web hook or silent post) url.
1186 *
1187 * If there is no '.' in it we assume that we are dealing with localhost or
1188 * similar and it is unreachable from the web & hence invalid.
1189 *
1190 * @return string
1191 * URL to notify outcome of transaction.
1192 */
1193 protected function getNotifyUrl() {
1194 $url = CRM_Utils_System::url(
1195 'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
9e3bf561 1196 [],
ddc4b5af 1197 TRUE,
1198 NULL,
c56db8c3
JGJ
1199 FALSE,
1200 TRUE
49c882a3
EM
1201 );
1202 return (stristr($url, '.')) ? $url : '';
1203 }
1204
6a488035 1205 /**
8319cf11 1206 * Calling this from outside the payment subsystem is deprecated - use doPayment.
278c5e16 1207 * @deprecated
8319cf11
EM
1208 * Does a server to server payment transaction.
1209 *
6a0b768e
TO
1210 * @param array $params
1211 * Assoc array of input parameters for this transaction.
6a488035 1212 *
a6c01b45 1213 * @return array
863fadaa 1214 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
6a488035 1215 */
863fadaa
EM
1216 protected function doDirectPayment(&$params) {
1217 return $params;
1218 }
6a488035 1219
c1cc3e0c 1220 /**
01c23151 1221 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
278c5e16 1222 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
6c99ada1 1223 *
278c5e16
MWMC
1224 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1225 * the transaction & in fact doTransferCheckout would not traditionally come back.
1226 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
7758bd2b 1227 *
278c5e16
MWMC
1228 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1229 * In some cases the IPN will set the payment to "Completed" some time later.
3910048c 1230 *
278c5e16
MWMC
1231 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1232 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1233 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
c4b164f7 1234 *
c1cc3e0c
EM
1235 * @param array $params
1236 *
7758bd2b 1237 * @param string $component
c1cc3e0c 1238 *
a6c01b45 1239 * @return array
278c5e16 1240 * Result array (containing at least the key payment_status_id)
7758bd2b
EM
1241 *
1242 * @throws \Civi\Payment\Exception\PaymentProcessorException
c1cc3e0c 1243 */
8319cf11 1244 public function doPayment(&$params, $component = 'contribute') {
05c302ec 1245 $this->_component = $component;
371e0262 1246 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
c51070b5 1247
1248 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1249 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1250 // have an example of that at the mome.
1251 if ($params['amount'] == 0) {
1252 $result['payment_status_id'] = array_search('Completed', $statuses);
1253 return $result;
1254 }
1255
c1cc3e0c
EM
1256 if ($this->_paymentProcessor['billing_mode'] == 4) {
1257 $result = $this->doTransferCheckout($params, $component);
7c85dc65
EM
1258 if (is_array($result) && !isset($result['payment_status_id'])) {
1259 $result['payment_status_id'] = array_search('Pending', $statuses);
7758bd2b 1260 }
c1cc3e0c
EM
1261 }
1262 else {
f8453bef 1263 $result = $this->doDirectPayment($params, $component);
7c85dc65 1264 if (is_array($result) && !isset($result['payment_status_id'])) {
9dd58272 1265 if (!empty($params['is_recur'])) {
7758bd2b 1266 // See comment block.
0816949d 1267 $result['payment_status_id'] = array_search('Pending', $statuses);
7758bd2b
EM
1268 }
1269 else {
7c85dc65 1270 $result['payment_status_id'] = array_search('Completed', $statuses);
7758bd2b
EM
1271 }
1272 }
c1cc3e0c
EM
1273 }
1274 if (is_a($result, 'CRM_Core_Error')) {
7758bd2b 1275 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
c1cc3e0c 1276 }
a9cf9972 1277 return $result;
c1cc3e0c
EM
1278 }
1279
6bc775cf
MD
1280 /**
1281 * Refunds payment
1282 *
1283 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1284 *
1285 * @param array $params
1286 *
1287 * @throws \Civi\Payment\Exception\PaymentProcessorException
1288 */
1289 public function doRefund(&$params) {}
1290
9d2f24ee 1291 /**
1292 * Query payment processor for details about a transaction.
1293 *
1294 * @param array $params
1295 * Array of parameters containing one of:
1296 * - trxn_id Id of an individual transaction.
1297 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1298 *
1299 * @return array
1300 * Extra parameters retrieved.
1301 * Any parameters retrievable through this should be documented in the function comments at
1302 * CRM_Core_Payment::doQuery. Currently:
1303 * - fee_amount Amount of fee paid
1304 */
1305 public function doQuery($params) {
9e3bf561 1306 return [];
9d2f24ee 1307 }
1308
6a488035 1309 /**
d09edf64 1310 * This function checks to see if we have the right config values.
6a488035 1311 *
a6c01b45
CW
1312 * @return string
1313 * the error message if any
6a488035 1314 */
7c550ca0 1315 abstract protected function checkConfig();
6a488035 1316
a0ee3941 1317 /**
6c99ada1
EM
1318 * Redirect for paypal.
1319 *
1320 * @todo move to paypal class or remove
1321 *
a0ee3941 1322 * @param $paymentProcessor
6c99ada1 1323 *
a0ee3941
EM
1324 * @return bool
1325 */
00be9182 1326 public static function paypalRedirect(&$paymentProcessor) {
6a488035
TO
1327 if (!$paymentProcessor) {
1328 return FALSE;
1329 }
1330
1331 if (isset($_GET['payment_date']) &&
1332 isset($_GET['merchant_return_link']) &&
1333 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
1334 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1335 ) {
1336 return TRUE;
1337 }
1338
1339 return FALSE;
1340 }
1341
1342 /**
6c99ada1
EM
1343 * Handle incoming payment notification.
1344 *
1345 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1346 *
43e5f0f6 1347 * @todo move to0 \Civi\Payment\System factory method
6a488035 1348 * Page callback for civicrm/payment/ipn
6a488035 1349 */
00be9182 1350 public static function handleIPN() {
b2a883a8 1351 try {
1352 self::handlePaymentMethod(
1353 'PaymentNotification',
1354 [
1355 'processor_name' => CRM_Utils_Request::retrieveValue('processor_name', 'String'),
1356 'processor_id' => CRM_Utils_Request::retrieveValue('processor_id', 'Integer'),
1357 'mode' => CRM_Utils_Request::retrieveValue('mode', 'Alphanumeric'),
1358 ]
1359 );
1360 }
1361 catch (CRM_Core_Exception $e) {
1362 Civi::log()->error('ipn_payment_callback_exception', [
1363 'context' => [
1364 'backtrace' => CRM_Core_Error::formatBacktrace(debug_backtrace()),
9e3bf561 1365 ],
b2a883a8 1366 ]);
1367 }
160c9df2 1368 CRM_Utils_System::civiExit();
6a488035
TO
1369 }
1370
1371 /**
3782df3e
EM
1372 * Payment callback handler.
1373 *
1374 * The processor_name or processor_id is passed in.
43d1ae00
EM
1375 * Note that processor_id is more reliable as one site may have more than one instance of a
1376 * processor & ideally the processor will be validating the results
6a488035
TO
1377 * Load requested payment processor and call that processor's handle<$method> method
1378 *
3782df3e
EM
1379 * @todo move to \Civi\Payment\System factory method
1380 *
1381 * @param string $method
1382 * 'PaymentNotification' or 'PaymentCron'
4691b077 1383 * @param array $params
23de1ac0
EM
1384 *
1385 * @throws \CRM_Core_Exception
1386 * @throws \Exception
6a488035 1387 */
9e3bf561 1388 public static function handlePaymentMethod($method, $params = []) {
42b90e8f 1389 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
020c48ef 1390 $q = explode('/', CRM_Utils_Array::value(CRM_Core_Config::singleton()->userFrameworkURLVar, $_GET, ''));
4164f4e1
EM
1391 $lastParam = array_pop($q);
1392 if (is_numeric($lastParam)) {
1393 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1394 }
1395 else {
068fb0de 1396 self::logPaymentNotification($params);
0ac9fd52 1397 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
4164f4e1 1398 }
6a488035 1399 }
4164f4e1 1400
e2bef985 1401 self::logPaymentNotification($params);
6a488035 1402
42b90e8f
CB
1403 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1404 FROM civicrm_payment_processor_type ppt
1405 INNER JOIN civicrm_payment_processor pp
1406 ON pp.payment_processor_type_id = ppt.id
9ff0c7a1 1407 AND pp.is_active";
42b90e8f
CB
1408
1409 if (isset($params['processor_id'])) {
1410 $sql .= " WHERE pp.id = %2";
9e3bf561 1411 $args[2] = [$params['processor_id'], 'Integer'];
1412 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
42b90e8f
CB
1413 }
1414 else {
9ff0c7a1
EM
1415 // This is called when processor_name is passed - passing processor_id instead is recommended.
1416 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
9e3bf561 1417 $args[1] = [
6c99ada1
EM
1418 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
1419 'Integer',
9e3bf561 1420 ];
1421 $args[2] = [$params['processor_name'], 'String'];
1422 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
42b90e8f
CB
1423 }
1424
1425 $dao = CRM_Core_DAO::executeQuery($sql, $args);
6a488035 1426
3782df3e 1427 // Check whether we found anything at all.
6a488035 1428 if (!$dao->N) {
b2a883a8 1429 throw new CRM_Core_Exception($notFound);
6a488035
TO
1430 }
1431
1432 $method = 'handle' . $method;
1433 $extension_instance_found = FALSE;
1434
1435 // In all likelihood, we'll just end up with the one instance returned here. But it's
1436 // possible we may get more. Hence, iterate through all instances ..
1437
1438 while ($dao->fetch()) {
5495e78a 1439 // Check pp is extension - is this still required - surely the singleton below handles it.
6a488035
TO
1440 $ext = CRM_Extension_System::singleton()->getMapper();
1441 if ($ext->isExtensionKey($dao->class_name)) {
6a488035
TO
1442 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
1443 require_once $ext->classToPath($paymentClass);
1444 }
6a488035 1445
7a3b0ca3 1446 $processorInstance = System::singleton()->getById($dao->processor_id);
6a488035
TO
1447
1448 // Should never be empty - we already established this processor_id exists and is active.
81ebda7b 1449 if (empty($processorInstance)) {
6a488035
TO
1450 continue;
1451 }
1452
6a488035
TO
1453 // Does PP implement this method, and can we call it?
1454 if (!method_exists($processorInstance, $method) ||
9e3bf561 1455 !is_callable([$processorInstance, $method])
6a488035 1456 ) {
43d1ae00
EM
1457 // on the off chance there is a double implementation of this processor we should keep looking for another
1458 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1459 continue;
6a488035
TO
1460 }
1461
1462 // Everything, it seems, is ok - execute pp callback handler
1463 $processorInstance->$method();
a5ef96f6 1464 $extension_instance_found = TRUE;
6a488035
TO
1465 }
1466
c5117180 1467 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
2d39b9c0
SL
1468 $IPNParams = array_merge($_GET, $_REQUEST);
1469 CRM_Utils_Hook::postIPNProcess($IPNParams);
4f99ca55 1470 if (!$extension_instance_found) {
0ac9fd52
CB
1471 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1472 "%2 method is unsupported in legacy payment processors.";
9e3bf561 1473 throw new CRM_Core_Exception(ts($message, [
1474 1 => $params['processor_name'],
1475 2 => $method,
1476 ]));
2aa397bc 1477 }
6a488035
TO
1478 }
1479
1480 /**
100fef9d 1481 * Check whether a method is present ( & supported ) by the payment processor object.
6a488035 1482 *
1e483eb5
EM
1483 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1484 *
6a0b768e
TO
1485 * @param string $method
1486 * Method to check for.
6a488035 1487 *
7c550ca0 1488 * @return bool
6a488035 1489 */
1524a007 1490 public function isSupported($method) {
6a488035
TO
1491 return method_exists(CRM_Utils_System::getClassName($this), $method);
1492 }
1493
1ba4a3aa
EM
1494 /**
1495 * Some processors replace the form submit button with their own.
1496 *
1497 * Returning false here will leave the button off front end forms.
1498 *
1499 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1500 */
1501 public function isSuppressSubmitButtons() {
1502 return FALSE;
1503 }
1504
d253aeb8
EM
1505 /**
1506 * Checks to see if invoice_id already exists in db.
1507 *
1508 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1509 * it is better to standardise to being here.
1510 *
1511 * @param int $invoiceId The ID to check.
1512 *
1513 * @param null $contributionID
1514 * If a contribution exists pass in the contribution ID.
1515 *
1516 * @return bool
1517 * True if invoice ID otherwise exists, else false
1518 */
1519 protected function checkDupe($invoiceId, $contributionID = NULL) {
1520 $contribution = new CRM_Contribute_DAO_Contribution();
1521 $contribution->invoice_id = $invoiceId;
1522 if ($contributionID) {
1523 $contribution->whereAdd("id <> $contributionID");
1524 }
1525 return $contribution->find();
1526 }
1527
a0ee3941 1528 /**
3782df3e
EM
1529 * Get url for users to manage this recurring contribution for this processor.
1530 *
100fef9d 1531 * @param int $entityID
a0ee3941
EM
1532 * @param null $entity
1533 * @param string $action
1534 *
1535 * @return string
1536 */
00be9182 1537 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
03cfff4c
KW
1538 // Set URL
1539 switch ($action) {
2aa397bc 1540 case 'cancel':
f926d56f
MWMC
1541 if (!$this->supports('cancelRecurring')) {
1542 return NULL;
1543 }
03cfff4c
KW
1544 $url = 'civicrm/contribute/unsubscribe';
1545 break;
2aa397bc
TO
1546
1547 case 'billing':
03cfff4c 1548 //in notify mode don't return the update billing url
b690491e 1549 if (!$this->supports('updateSubscriptionBillingInfo')) {
03cfff4c
KW
1550 return NULL;
1551 }
68acd6ae 1552 $url = 'civicrm/contribute/updatebilling';
03cfff4c 1553 break;
2aa397bc
TO
1554
1555 case 'update':
f926d56f
MWMC
1556 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1557 return NULL;
1558 }
03cfff4c
KW
1559 $url = 'civicrm/contribute/updaterecur';
1560 break;
6a488035
TO
1561 }
1562
b7e7f943 1563 $userId = CRM_Core_Session::singleton()->get('userID');
353ffa53 1564 $contactID = 0;
03cfff4c 1565 $checksumValue = '';
353ffa53 1566 $entityArg = '';
03cfff4c
KW
1567
1568 // Find related Contact
1569 if ($entityID) {
1570 switch ($entity) {
2aa397bc 1571 case 'membership':
03cfff4c
KW
1572 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1573 $entityArg = 'mid';
1574 break;
1575
2aa397bc 1576 case 'contribution':
03cfff4c
KW
1577 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1578 $entityArg = 'coid';
1579 break;
1580
2aa397bc 1581 case 'recur':
03cfff4c 1582 $sql = "
0f913c6d 1583 SELECT DISTINCT con.contact_id
6a488035
TO
1584 FROM civicrm_contribution_recur rec
1585INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
0f913c6d 1586 WHERE rec.id = %1";
9e3bf561 1587 $contactID = CRM_Core_DAO::singleValueQuery($sql, [
1588 1 => [
1589 $entityID,
1590 'Integer',
1591 ],
1592 ]);
03cfff4c
KW
1593 $entityArg = 'crid';
1594 break;
6a488035 1595 }
6a488035
TO
1596 }
1597
03cfff4c
KW
1598 // Add entity arguments
1599 if ($entityArg != '') {
1600 // Add checksum argument
1601 if ($contactID != 0 && $userId != $contactID) {
1602 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1603 }
1604 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1605 }
1606
1607 // Else login URL
b690491e 1608 if ($this->supports('accountLoginURL')) {
6a488035
TO
1609 return $this->accountLoginURL();
1610 }
03cfff4c
KW
1611
1612 // Else default
735d988f 1613 return isset($this->_paymentProcessor['url_recur']) ? $this->_paymentProcessor['url_recur'] : '';
6a488035 1614 }
96025800 1615
efa36d6e 1616 /**
1617 * Get description of payment to pass to processor.
1618 *
1619 * This is often what people see in the interface so we want to get
1620 * as much unique information in as possible within the field length (& presumably the early part of the field)
1621 *
1622 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1623 * having field names to clarify
1624 *
1625 * @param array $params
1626 * @param int $length
1627 *
1628 * @return string
1629 */
05bf1fb0 1630 protected function getPaymentDescription($params, $length = 24) {
9e3bf561 1631 $parts = [
1632 'contactID',
1633 'contributionID',
1634 'description',
1635 'billing_first_name',
1636 'billing_last_name',
1637 ];
1638 $validParts = [];
05bf1fb0 1639 if (isset($params['description'])) {
1640 $uninformativeStrings = [
1641 ts('Online Event Registration: '),
1642 ts('Online Contribution: '),
1643 ];
1644 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1645 }
efa36d6e 1646 foreach ($parts as $part) {
1647 if ((!empty($params[$part]))) {
1648 $validParts[] = $params[$part];
1649 }
1650 }
1651 return substr(implode('-', $validParts), 0, $length);
1652 }
1653
95974e8e
DG
1654 /**
1655 * Checks if backoffice recurring edit is allowed
1656 *
1657 * @return bool
1658 */
1659 public function supportsEditRecurringContribution() {
1660 return FALSE;
1661 }
1662
b690491e
MWMC
1663 /**
1664 * Does this processor support changing the amount for recurring contributions through code.
1665 *
1666 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1667 * that will be updated at the payment processor.
1668 *
1669 * @return bool
1670 */
1671 protected function supportsChangeSubscriptionAmount() {
1672 return method_exists(CRM_Utils_System::getClassName($this), 'changeSubscriptionAmount');
1673 }
1674
54afd8a6
MW
1675 /**
1676 * Checks if payment processor supports recurring contributions
1677 *
1678 * @return bool
1679 */
1680 public function supportsRecurring() {
1681 if (!empty($this->_paymentProcessor['is_recur'])) {
1682 return TRUE;
1683 }
1684 return FALSE;
1685 }
1686
b690491e
MWMC
1687 /**
1688 * Checks if payment processor supports an account login URL
1689 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1690 * TODO: It is implemented by AuthorizeNET, any others?
1691 *
1692 * @return bool
1693 */
1694 protected function supportsAccountLoginURL() {
1695 return method_exists(CRM_Utils_System::getClassName($this), 'accountLoginURL');
1696 }
1697
cd3bc162 1698 /**
1699 * Should a receipt be sent out for a pending payment.
1700 *
1701 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1702 */
1703 public function isSendReceiptForPending() {
1704 return FALSE;
1705 }
1706
6a488035 1707}