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