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