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