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