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