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