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