Merge pull request #7377 from agh1/export-document-header-region
[civicrm-core.git] / CRM / Core / Payment.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
63 /**
100fef9d 64 * Which payment type(s) are we using?
6a488035
TO
65 *
66 * credit card
67 * direct debit
68 * or both
43e5f0f6 69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
6a488035 70 */
7da04cde 71 const
6a488035
TO
72 PAYMENT_TYPE_CREDIT_CARD = 1,
73 PAYMENT_TYPE_DIRECT_DEBIT = 2;
74
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 /**
86 * Base url of the calling form.
87 *
88 * This is used for processors that need to return the browser back to the CiviCRM site.
89 *
90 * @var string
91 */
92 protected $baseReturnUrl;
93
1d1fee72 94 /**
95 * The profile configured to show on the billing form.
96 *
97 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
98 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
99 * requirements with the configured requirements.
100 *
101 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
102 * of fields.
103 *
104 * Note this change would probably include converting 'billing' to a reserved profile.
105 *
106 * @var int|string
107 */
108 protected $billingProfile;
109
ec022878 110 /**
111 * Set Base return URL.
112 *
113 * @param string $url
114 * Url of site to return browser to.
115 */
116 public function setBaseReturnUrl($url) {
117 $this->baseReturnUrl = $url;
118 }
119
1d1fee72 120 /**
121 * Set the configured payment profile.
122 *
123 * @param int|string $value
124 */
125 public function setBillingProfile($value) {
126 $this->billingProfile = $value;
127 }
128
dbbd55dc
EM
129 /**
130 * Opportunity for the payment processor to override the entire form build.
131 *
132 * @param CRM_Core_Form $form
133 *
134 * @return bool
135 * Should form building stop at this point?
136 */
137 public function buildForm(&$form) {
31d31a05 138 return FALSE;
dbbd55dc
EM
139 }
140
e2bef985 141 /**
3782df3e
EM
142 * Log payment notification message to forensic system log.
143 *
43e5f0f6 144 * @todo move to factory class \Civi\Payment\System (or similar)
3782df3e
EM
145 *
146 * @param array $params
147 *
e2bef985 148 * @return mixed
149 */
150 public static function logPaymentNotification($params) {
414e3596 151 $message = 'payment_notification ';
e2bef985 152 if (!empty($params['processor_name'])) {
414e3596 153 $message .= 'processor_name=' . $params['processor_name'];
e2bef985 154 }
155 if (!empty($params['processor_id'])) {
156 $message .= 'processor_id=' . $params['processor_id'];
157 }
414e3596 158
159 $log = new CRM_Utils_SystemLogger();
160 $log->alert($message, $_REQUEST);
e2bef985 161 }
162
fbcb6fba 163 /**
d09edf64 164 * Check if capability is supported.
3782df3e
EM
165 *
166 * Capabilities have a one to one relationship with capability-related functions on this class.
167 *
168 * Payment processor classes should over-ride the capability-specific function rather than this one.
169 *
6a0b768e
TO
170 * @param string $capability
171 * E.g BackOffice, LiveMode, FutureRecurStartDate.
fbcb6fba
EM
172 *
173 * @return bool
174 */
175 public function supports($capability) {
176 $function = 'supports' . ucfirst($capability);
177 if (method_exists($this, $function)) {
178 return $this->$function();
179 }
180 return FALSE;
181 }
182
183 /**
3782df3e
EM
184 * Are back office payments supported.
185 *
186 * e.g paypal standard won't permit you to enter a credit card associated
187 * with someone else's login.
188 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
189 * reach a 'stable' point we disable.
190 *
fbcb6fba
EM
191 * @return bool
192 */
d8ce0d68 193 protected function supportsBackOffice() {
9c39fb25
EM
194 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
195 return FALSE;
196 }
197 else {
198 return TRUE;
199 }
fbcb6fba
EM
200 }
201
75ead8de
EM
202 /**
203 * Can more than one transaction be processed at once?
204 *
205 * In general processors that process payment by server to server communication support this while others do not.
206 *
207 * In future we are likely to hit an issue where this depends on whether a token already exists.
208 *
209 * @return bool
210 */
211 protected function supportsMultipleConcurrentPayments() {
212 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
213 return FALSE;
214 }
215 else {
216 return TRUE;
217 }
218 }
219
fbcb6fba 220 /**
3782df3e
EM
221 * Are live payments supported - e.g dummy doesn't support this.
222 *
fbcb6fba
EM
223 * @return bool
224 */
d8ce0d68 225 protected function supportsLiveMode() {
fbcb6fba
EM
226 return TRUE;
227 }
228
52767de0 229 /**
d09edf64 230 * Are test payments supported.
3782df3e 231 *
52767de0
EM
232 * @return bool
233 */
234 protected function supportsTestMode() {
235 return TRUE;
236 }
237
fbcb6fba 238 /**
d09edf64 239 * Should the first payment date be configurable when setting up back office recurring payments.
3782df3e 240 *
fbcb6fba 241 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
3782df3e 242 *
fbcb6fba
EM
243 * @return bool
244 */
d8ce0d68 245 protected function supportsFutureRecurStartDate() {
fbcb6fba
EM
246 return FALSE;
247 }
248
1e483eb5
EM
249 /**
250 * Does this processor support cancelling recurring contributions through code.
251 *
252 * @return bool
253 */
254 protected function supportsCancelRecurring() {
255 return method_exists(CRM_Utils_System::getClassName($this), 'cancelSubscription');
256 }
257
3910048c
EM
258 /**
259 * Does this processor support pre-approval.
260 *
261 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
262 *
263 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
264 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
265 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
266 *
267 * @return bool
268 */
269 protected function supportsPreApproval() {
270 return FALSE;
271 }
272
677fe56c
EM
273 /**
274 * Can recurring contributions be set against pledges.
275 *
276 * In practice all processors that use the baseIPN function to finish transactions or
277 * call the completetransaction api support this by looking up previous contributions in the
278 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
279 * adding the new payment to the pledge.
280 *
281 * However, only enabling for processors it has been tested against.
282 *
283 * @return bool
284 */
285 protected function supportsRecurContributionsForPledges() {
286 return FALSE;
287 }
288
3910048c
EM
289 /**
290 * Function to action pre-approval if supported
291 *
292 * @param array $params
293 * Parameters from the form
3910048c
EM
294 *
295 * This function returns an array which should contain
296 * - pre_approval_parameters (this will be stored on the calling form & available later)
297 * - redirect_url (if set the browser will be redirected to this.
298 */
677730bd 299 public function doPreApproval(&$params) {}
3910048c 300
3105efd2
EM
301 /**
302 * Get any details that may be available to the payment processor due to an approval process having happened.
303 *
304 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
305 * result.
306 *
307 * @param array $storedDetails
308 *
309 * @return array
310 */
311 public function getPreApprovalDetails($storedDetails) {
312 return array();
313 }
314
6a488035 315 /**
3782df3e
EM
316 * Default payment instrument validation.
317 *
a479fe60 318 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
3782df3e
EM
319 * Not a static function, because I need to check for payment_type.
320 *
321 * @param array $values
322 * @param array $errors
a479fe60 323 */
324 public function validatePaymentInstrument($values, &$errors) {
c319039f 325 CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
a479fe60 326 if ($this->_paymentProcessor['payment_type'] == 1) {
327 CRM_Core_Payment_Form::validateCreditCard($values, $errors);
328 }
329 }
330
80bcd255
EM
331 /**
332 * Getter for the payment processor.
333 *
334 * The payment processor array is based on the civicrm_payment_processor table entry.
335 *
336 * @return array
337 * Payment processor array.
338 */
339 public function getPaymentProcessor() {
340 return $this->_paymentProcessor;
341 }
342
343 /**
344 * Setter for the payment processor.
345 *
346 * @param array $processor
347 */
348 public function setPaymentProcessor($processor) {
349 $this->_paymentProcessor = $processor;
350 }
351
6a488035 352 /**
3782df3e
EM
353 * Setter for the payment form that wants to use the processor.
354 *
43e5f0f6 355 * @deprecated
3782df3e 356 *
ac32ed13 357 * @param CRM_Core_Form $paymentForm
6a488035 358 */
00be9182 359 public function setForm(&$paymentForm) {
6a488035
TO
360 $this->_paymentForm = $paymentForm;
361 }
362
363 /**
d09edf64 364 * Getter for payment form that is using the processor.
43e5f0f6 365 * @deprecated
16b10e64
CW
366 * @return CRM_Core_Form
367 * A form object
6a488035 368 */
00be9182 369 public function getForm() {
6a488035
TO
370 return $this->_paymentForm;
371 }
372
373 /**
d09edf64 374 * Getter for accessing member vars.
6c99ada1 375 *
43e5f0f6 376 * @todo believe this is unused
6c99ada1 377 *
100fef9d 378 * @param string $name
dc913073
EM
379 *
380 * @return null
6a488035 381 */
00be9182 382 public function getVar($name) {
6a488035
TO
383 return isset($this->$name) ? $this->$name : NULL;
384 }
385
dc913073 386 /**
d09edf64 387 * Get name for the payment information type.
43e5f0f6 388 * @todo - use option group + name field (like Omnipay does)
dc913073
EM
389 * @return string
390 */
391 public function getPaymentTypeName() {
459091e1 392 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
dc913073
EM
393 }
394
395 /**
d09edf64 396 * Get label for the payment information type.
43e5f0f6 397 * @todo - use option group + labels (like Omnipay does)
dc913073
EM
398 * @return string
399 */
400 public function getPaymentTypeLabel() {
459091e1 401 return $this->_paymentProcessor['payment_type'] == 1 ? 'Credit Card' : 'Direct Debit';
dc913073
EM
402 }
403
44b6505d 404 /**
d09edf64 405 * Get array of fields that should be displayed on the payment form.
44b6505d
EM
406 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
407 * @return array
408 * @throws CiviCRM_API3_Exception
409 */
410 public function getPaymentFormFields() {
dc913073 411 if ($this->_paymentProcessor['billing_mode'] == 4) {
44b6505d
EM
412 return array();
413 }
414 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
415 }
416
c319039f 417 /**
418 * Get the metadata for all required fields.
419 *
420 * @return array;
421 */
422 protected function getMandatoryFields() {
423 $mandatoryFields = array();
424 foreach ($this->getAllFields() as $field_name => $field_spec) {
425 if (!empty($field_spec['is_required'])) {
426 $mandatoryFields[$field_name] = $field_spec;
427 }
428 }
429 return $mandatoryFields;
430 }
431
432 /**
433 * Get the metadata of all the fields configured for this processor.
434 *
435 * @return array
436 */
437 protected function getAllFields() {
438 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
439 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
440 return array_merge($paymentFields, $billingFields);
441 }
44b6505d 442 /**
d09edf64 443 * Get array of fields that should be displayed on the payment form for credit cards.
dc913073 444 *
44b6505d
EM
445 * @return array
446 */
447 protected function getCreditCardFormFields() {
448 return array(
449 'credit_card_type',
450 'credit_card_number',
451 'cvv2',
452 'credit_card_exp_date',
453 );
454 }
455
456 /**
d09edf64 457 * Get array of fields that should be displayed on the payment form for direct debits.
dc913073 458 *
44b6505d
EM
459 * @return array
460 */
461 protected function getDirectDebitFormFields() {
462 return array(
463 'account_holder',
464 'bank_account_number',
465 'bank_identification_number',
466 'bank_name',
467 );
468 }
469
dc913073 470 /**
d09edf64 471 * Return an array of all the details about the fields potentially required for payment fields.
3782df3e 472 *
dc913073
EM
473 * Only those determined by getPaymentFormFields will actually be assigned to the form
474 *
a6c01b45
CW
475 * @return array
476 * field metadata
dc913073
EM
477 */
478 public function getPaymentFormFieldsMetadata() {
479 //@todo convert credit card type into an option value
480 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
481 return array(
482 'credit_card_number' => array(
483 'htmlType' => 'text',
484 'name' => 'credit_card_number',
485 'title' => ts('Card Number'),
486 'cc_field' => TRUE,
487 'attributes' => array(
488 'size' => 20,
489 'maxlength' => 20,
21dfd5f5 490 'autocomplete' => 'off',
f803aacb 491 'class' => 'creditcard',
dc913073
EM
492 ),
493 'is_required' => TRUE,
494 ),
495 'cvv2' => array(
496 'htmlType' => 'text',
497 'name' => 'cvv2',
498 'title' => ts('Security Code'),
499 'cc_field' => TRUE,
500 'attributes' => array(
501 'size' => 5,
502 'maxlength' => 10,
21dfd5f5 503 'autocomplete' => 'off',
dc913073 504 ),
d356cdeb 505 'is_required' => Civi::settings()->get('cvv_backoffice_required'),
dc913073
EM
506 'rules' => array(
507 array(
508 '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.'),
509 'rule_name' => 'integer',
510 'rule_parameters' => NULL,
7c550ca0 511 ),
353ffa53 512 ),
dc913073
EM
513 ),
514 'credit_card_exp_date' => array(
515 'htmlType' => 'date',
516 'name' => 'credit_card_exp_date',
517 'title' => ts('Expiration Date'),
518 'cc_field' => TRUE,
519 'attributes' => CRM_Core_SelectValues::date('creditCard'),
520 'is_required' => TRUE,
521 'rules' => array(
522 array(
523 'rule_message' => ts('Card expiration date cannot be a past date.'),
524 'rule_name' => 'currentDate',
525 'rule_parameters' => TRUE,
7c550ca0 526 ),
353ffa53 527 ),
dc913073
EM
528 ),
529 'credit_card_type' => array(
530 'htmlType' => 'select',
531 'name' => 'credit_card_type',
532 'title' => ts('Card Type'),
533 'cc_field' => TRUE,
534 'attributes' => $creditCardType,
535 'is_required' => FALSE,
536 ),
537 'account_holder' => array(
538 'htmlType' => 'text',
539 'name' => 'account_holder',
540 'title' => ts('Account Holder'),
541 'cc_field' => TRUE,
542 'attributes' => array(
543 'size' => 20,
544 'maxlength' => 34,
21dfd5f5 545 'autocomplete' => 'on',
dc913073
EM
546 ),
547 'is_required' => TRUE,
548 ),
549 //e.g. IBAN can have maxlength of 34 digits
550 'bank_account_number' => array(
551 'htmlType' => 'text',
552 'name' => 'bank_account_number',
553 'title' => ts('Bank Account Number'),
554 'cc_field' => TRUE,
555 'attributes' => array(
556 'size' => 20,
557 'maxlength' => 34,
21dfd5f5 558 'autocomplete' => 'off',
dc913073
EM
559 ),
560 'rules' => array(
561 array(
562 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
563 'rule_name' => 'nopunctuation',
564 'rule_parameters' => NULL,
7c550ca0 565 ),
353ffa53 566 ),
dc913073
EM
567 'is_required' => TRUE,
568 ),
569 //e.g. SWIFT-BIC can have maxlength of 11 digits
570 'bank_identification_number' => array(
571 'htmlType' => 'text',
572 'name' => 'bank_identification_number',
573 'title' => ts('Bank Identification Number'),
574 'cc_field' => TRUE,
575 'attributes' => array(
576 'size' => 20,
577 'maxlength' => 11,
21dfd5f5 578 'autocomplete' => 'off',
dc913073
EM
579 ),
580 'is_required' => TRUE,
581 'rules' => array(
582 array(
583 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
584 'rule_name' => 'nopunctuation',
585 'rule_parameters' => NULL,
7c550ca0 586 ),
353ffa53 587 ),
dc913073
EM
588 ),
589 'bank_name' => array(
590 'htmlType' => 'text',
591 'name' => 'bank_name',
592 'title' => ts('Bank Name'),
593 'cc_field' => TRUE,
594 'attributes' => array(
595 'size' => 20,
596 'maxlength' => 64,
21dfd5f5 597 'autocomplete' => 'off',
dc913073
EM
598 ),
599 'is_required' => TRUE,
600
21dfd5f5 601 ),
dc913073
EM
602 );
603 }
44b6505d 604
3310ab71 605 /**
606 * Get billing fields required for this processor.
607 *
608 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
609 * alter.
610 *
611 * @param int $billingLocationID
612 *
613 * @return array
614 */
b576d770 615 public function getBillingAddressFields($billingLocationID = NULL) {
616 if (!$billingLocationID) {
617 // Note that although the billing id is passed around the forms the idea that it would be anything other than
618 // the result of the function below doesn't seem to have eventuated.
619 // So taking this as a param is possibly something to be removed in favour of the standard default.
620 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
621 }
3310ab71 622 if ($this->_paymentProcessor['billing_mode'] != 1 && $this->_paymentProcessor['billing_mode'] != 3) {
623 return array();
624 }
625 return array(
626 'first_name' => 'billing_first_name',
627 'middle_name' => 'billing_middle_name',
628 'last_name' => 'billing_last_name',
629 'street_address' => "billing_street_address-{$billingLocationID}",
630 'city' => "billing_city-{$billingLocationID}",
631 'country' => "billing_country_id-{$billingLocationID}",
632 'state_province' => "billing_state_province_id-{$billingLocationID}",
633 'postal_code' => "billing_postal_code-{$billingLocationID}",
634 );
635 }
636
637 /**
638 * Get form metadata for billing address fields.
639 *
640 * @param int $billingLocationID
641 *
642 * @return array
643 * Array of metadata for address fields.
644 */
b576d770 645 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
646 if (!$billingLocationID) {
647 // Note that although the billing id is passed around the forms the idea that it would be anything other than
648 // the result of the function below doesn't seem to have eventuated.
649 // So taking this as a param is possibly something to be removed in favour of the standard default.
650 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
651 }
3310ab71 652 $metadata = array();
653 $metadata['billing_first_name'] = array(
654 'htmlType' => 'text',
655 'name' => 'billing_first_name',
656 'title' => ts('Billing First Name'),
657 'cc_field' => TRUE,
658 'attributes' => array(
659 'size' => 30,
660 'maxlength' => 60,
661 'autocomplete' => 'off',
662 ),
663 'is_required' => TRUE,
664 );
665
666 $metadata['billing_middle_name'] = array(
667 'htmlType' => 'text',
668 'name' => 'billing_middle_name',
669 'title' => ts('Billing Middle Name'),
670 'cc_field' => TRUE,
671 'attributes' => array(
672 'size' => 30,
673 'maxlength' => 60,
674 'autocomplete' => 'off',
675 ),
676 'is_required' => FALSE,
677 );
678
679 $metadata['billing_last_name'] = array(
680 'htmlType' => 'text',
681 'name' => 'billing_last_name',
682 'title' => ts('Billing Last Name'),
683 'cc_field' => TRUE,
684 'attributes' => array(
685 'size' => 30,
686 'maxlength' => 60,
687 'autocomplete' => 'off',
688 ),
689 'is_required' => TRUE,
690 );
691
692 $metadata["billing_street_address-{$billingLocationID}"] = array(
693 'htmlType' => 'text',
694 'name' => "billing_street_address-{$billingLocationID}",
695 'title' => ts('Street Address'),
696 'cc_field' => TRUE,
697 'attributes' => array(
698 'size' => 30,
699 'maxlength' => 60,
700 'autocomplete' => 'off',
701 ),
702 'is_required' => TRUE,
703 );
704
705 $metadata["billing_city-{$billingLocationID}"] = array(
706 'htmlType' => 'text',
707 'name' => "billing_city-{$billingLocationID}",
708 'title' => ts('City'),
709 'cc_field' => TRUE,
710 'attributes' => array(
711 'size' => 30,
712 'maxlength' => 60,
713 'autocomplete' => 'off',
714 ),
715 'is_required' => TRUE,
716 );
717
718 $metadata["billing_state_province_id-{$billingLocationID}"] = array(
719 'htmlType' => 'chainSelect',
720 'title' => ts('State/Province'),
721 'name' => "billing_state_province_id-{$billingLocationID}",
722 'cc_field' => TRUE,
723 'is_required' => TRUE,
724 );
725
726 $metadata["billing_postal_code-{$billingLocationID}"] = array(
727 'htmlType' => 'text',
728 'name' => "billing_postal_code-{$billingLocationID}",
729 'title' => ts('Postal Code'),
730 'cc_field' => TRUE,
731 'attributes' => array(
732 'size' => 30,
733 'maxlength' => 60,
734 'autocomplete' => 'off',
735 ),
736 'is_required' => TRUE,
737 );
738
739 $metadata["billing_country_id-{$billingLocationID}"] = array(
740 'htmlType' => 'select',
741 'name' => "billing_country_id-{$billingLocationID}",
742 'title' => ts('Country'),
743 'cc_field' => TRUE,
744 'attributes' => array(
745 '' => ts('- select -'),
746 ) + CRM_Core_PseudoConstant::country(),
747 'is_required' => TRUE,
748 );
749 return $metadata;
750 }
751
aefd7f6b
EM
752 /**
753 * Get base url dependent on component.
754 *
ec022878 755 * (or preferably set it using the setter function).
756 *
757 * @return string
aefd7f6b
EM
758 */
759 protected function getBaseReturnUrl() {
ec022878 760 if ($this->baseReturnUrl) {
761 return $this->baseReturnUrl;
762 }
aefd7f6b
EM
763 if ($this->_component == 'event') {
764 $baseURL = 'civicrm/event/register';
765 }
766 else {
767 $baseURL = 'civicrm/contribute/transact';
768 }
769 return $baseURL;
770 }
771
772 /**
773 * Get url to return to after cancelled or failed transaction
774 *
775 * @param $qfKey
776 * @param $participantID
777 *
778 * @return string cancel url
779 */
abfb35ee 780 public function getCancelUrl($qfKey, $participantID) {
aefd7f6b
EM
781 if ($this->_component == 'event') {
782 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
783 'reset' => 1,
784 'cc' => 'fail',
785 'participantId' => $participantID,
786 ),
787 TRUE, NULL, FALSE
788 );
789 }
790
791 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
792 '_qf_Main_display' => 1,
793 'qfKey' => $qfKey,
794 'cancel' => 1,
795 ),
796 TRUE, NULL, FALSE
797 );
798 }
799
800 /**
49c882a3 801 * Get URL to return the browser to on success.
aefd7f6b
EM
802 *
803 * @param $qfKey
804 *
805 * @return string
806 */
807 protected function getReturnSuccessUrl($qfKey) {
808 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
809 '_qf_ThankYou_display' => 1,
05237b76 810 'qfKey' => $qfKey,
aefd7f6b
EM
811 ),
812 TRUE, NULL, FALSE
813 );
814 }
815
49c882a3
EM
816 /**
817 * Get URL to return the browser to on failure.
818 *
819 * @param string $key
820 * @param int $participantID
821 * @param int $eventID
822 *
823 * @return string
824 * URL for a failing transactor to be redirected to.
825 */
826 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
6109d8df 827 $test = $this->_is_test ? '&action=preview' : '';
49c882a3
EM
828 if ($this->_component == "event") {
829 return CRM_Utils_System::url('civicrm/event/register',
830 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
831 FALSE, NULL, FALSE
832 );
833 }
834 else {
835 return CRM_Utils_System::url('civicrm/contribute/transact',
836 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
837 FALSE, NULL, FALSE
838 );
839 }
840 }
841
842 /**
843 * Get URl for when the back button is pressed.
844 *
845 * @param $qfKey
846 *
847 * @return string url
848 */
849 protected function getGoBackUrl($qfKey) {
850 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
851 '_qf_Confirm_display' => 'true',
6109d8df 852 'qfKey' => $qfKey,
49c882a3
EM
853 ),
854 TRUE, NULL, FALSE
855 );
856 }
857
858 /**
859 * Get the notify (aka ipn, web hook or silent post) url.
860 *
861 * If there is no '.' in it we assume that we are dealing with localhost or
862 * similar and it is unreachable from the web & hence invalid.
863 *
864 * @return string
865 * URL to notify outcome of transaction.
866 */
867 protected function getNotifyUrl() {
868 $url = CRM_Utils_System::url(
869 'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
870 array(),
871 TRUE
872 );
873 return (stristr($url, '.')) ? $url : '';
874 }
875
6a488035 876 /**
8319cf11
EM
877 * Calling this from outside the payment subsystem is deprecated - use doPayment.
878 *
879 * Does a server to server payment transaction.
880 *
6a0b768e
TO
881 * @param array $params
882 * Assoc array of input parameters for this transaction.
6a488035 883 *
a6c01b45 884 * @return array
863fadaa 885 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
6a488035 886 */
863fadaa
EM
887 protected function doDirectPayment(&$params) {
888 return $params;
889 }
6a488035 890
c1cc3e0c 891 /**
6c99ada1
EM
892 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
893 *
894 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
895 * more agnostic.
c1cc3e0c 896 *
3910048c 897 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
7758bd2b
EM
898 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
899 * doTransferCheckout would not traditionally come back.
900 *
901 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
902 * to be Pending.
903 *
3910048c
EM
904 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
905 * return Error objects
906 *
c1cc3e0c
EM
907 * @param array $params
908 *
7758bd2b 909 * @param string $component
c1cc3e0c 910 *
a6c01b45 911 * @return array
7758bd2b
EM
912 * Result array
913 *
914 * @throws \Civi\Payment\Exception\PaymentProcessorException
c1cc3e0c 915 */
8319cf11 916 public function doPayment(&$params, $component = 'contribute') {
05c302ec 917 $this->_component = $component;
7758bd2b 918 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
c51070b5 919
920 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
921 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
922 // have an example of that at the mome.
923 if ($params['amount'] == 0) {
924 $result['payment_status_id'] = array_search('Completed', $statuses);
925 return $result;
926 }
927
c1cc3e0c
EM
928 if ($this->_paymentProcessor['billing_mode'] == 4) {
929 $result = $this->doTransferCheckout($params, $component);
7c85dc65
EM
930 if (is_array($result) && !isset($result['payment_status_id'])) {
931 $result['payment_status_id'] = array_search('Pending', $statuses);
7758bd2b 932 }
c1cc3e0c
EM
933 }
934 else {
f8453bef 935 $result = $this->doDirectPayment($params, $component);
7c85dc65 936 if (is_array($result) && !isset($result['payment_status_id'])) {
9dd58272 937 if (!empty($params['is_recur'])) {
7758bd2b 938 // See comment block.
0816949d 939 $result['payment_status_id'] = array_search('Pending', $statuses);
7758bd2b
EM
940 }
941 else {
7c85dc65 942 $result['payment_status_id'] = array_search('Completed', $statuses);
7758bd2b
EM
943 }
944 }
c1cc3e0c
EM
945 }
946 if (is_a($result, 'CRM_Core_Error')) {
7758bd2b 947 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
c1cc3e0c 948 }
a9cf9972 949 return $result;
c1cc3e0c
EM
950 }
951
9d2f24ee 952 /**
953 * Query payment processor for details about a transaction.
954 *
955 * @param array $params
956 * Array of parameters containing one of:
957 * - trxn_id Id of an individual transaction.
958 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
959 *
960 * @return array
961 * Extra parameters retrieved.
962 * Any parameters retrievable through this should be documented in the function comments at
963 * CRM_Core_Payment::doQuery. Currently:
964 * - fee_amount Amount of fee paid
965 */
966 public function doQuery($params) {
967 return array();
968 }
969
6a488035 970 /**
d09edf64 971 * This function checks to see if we have the right config values.
6a488035 972 *
a6c01b45
CW
973 * @return string
974 * the error message if any
6a488035 975 */
7c550ca0 976 abstract protected function checkConfig();
6a488035 977
a0ee3941 978 /**
6c99ada1
EM
979 * Redirect for paypal.
980 *
981 * @todo move to paypal class or remove
982 *
a0ee3941 983 * @param $paymentProcessor
6c99ada1 984 *
a0ee3941
EM
985 * @return bool
986 */
00be9182 987 public static function paypalRedirect(&$paymentProcessor) {
6a488035
TO
988 if (!$paymentProcessor) {
989 return FALSE;
990 }
991
992 if (isset($_GET['payment_date']) &&
993 isset($_GET['merchant_return_link']) &&
994 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
995 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
996 ) {
997 return TRUE;
998 }
999
1000 return FALSE;
1001 }
1002
1003 /**
6c99ada1
EM
1004 * Handle incoming payment notification.
1005 *
1006 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1007 *
43e5f0f6 1008 * @todo move to0 \Civi\Payment\System factory method
6a488035 1009 * Page callback for civicrm/payment/ipn
6a488035 1010 */
00be9182 1011 public static function handleIPN() {
6a488035
TO
1012 self::handlePaymentMethod(
1013 'PaymentNotification',
1014 array(
1015 'processor_name' => @$_GET['processor_name'],
42b90e8f 1016 'processor_id' => @$_GET['processor_id'],
6a488035 1017 'mode' => @$_GET['mode'],
4164f4e1 1018 'q' => @$_GET['q'],
6a488035
TO
1019 )
1020 );
160c9df2 1021 CRM_Utils_System::civiExit();
6a488035
TO
1022 }
1023
1024 /**
3782df3e
EM
1025 * Payment callback handler.
1026 *
1027 * The processor_name or processor_id is passed in.
43d1ae00
EM
1028 * Note that processor_id is more reliable as one site may have more than one instance of a
1029 * processor & ideally the processor will be validating the results
6a488035
TO
1030 * Load requested payment processor and call that processor's handle<$method> method
1031 *
3782df3e
EM
1032 * @todo move to \Civi\Payment\System factory method
1033 *
1034 * @param string $method
1035 * 'PaymentNotification' or 'PaymentCron'
4691b077 1036 * @param array $params
23de1ac0
EM
1037 *
1038 * @throws \CRM_Core_Exception
1039 * @throws \Exception
6a488035 1040 */
00be9182 1041 public static function handlePaymentMethod($method, $params = array()) {
42b90e8f 1042 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
4164f4e1
EM
1043 $q = explode('/', CRM_Utils_Array::value('q', $params, ''));
1044 $lastParam = array_pop($q);
1045 if (is_numeric($lastParam)) {
1046 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1047 }
1048 else {
0ac9fd52 1049 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
4164f4e1 1050 }
6a488035 1051 }
4164f4e1 1052
e2bef985 1053 self::logPaymentNotification($params);
6a488035 1054
42b90e8f
CB
1055 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1056 FROM civicrm_payment_processor_type ppt
1057 INNER JOIN civicrm_payment_processor pp
1058 ON pp.payment_processor_type_id = ppt.id
9ff0c7a1 1059 AND pp.is_active";
42b90e8f
CB
1060
1061 if (isset($params['processor_id'])) {
1062 $sql .= " WHERE pp.id = %2";
1063 $args[2] = array($params['processor_id'], 'Integer');
0ac9fd52 1064 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
42b90e8f
CB
1065 }
1066 else {
9ff0c7a1
EM
1067 // This is called when processor_name is passed - passing processor_id instead is recommended.
1068 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
6c99ada1
EM
1069 $args[1] = array(
1070 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
1071 'Integer',
1072 );
42b90e8f 1073 $args[2] = array($params['processor_name'], 'String');
0ac9fd52 1074 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
42b90e8f
CB
1075 }
1076
1077 $dao = CRM_Core_DAO::executeQuery($sql, $args);
6a488035 1078
3782df3e 1079 // Check whether we found anything at all.
6a488035 1080 if (!$dao->N) {
3782df3e 1081 CRM_Core_Error::fatal($notFound);
6a488035
TO
1082 }
1083
1084 $method = 'handle' . $method;
1085 $extension_instance_found = FALSE;
1086
1087 // In all likelihood, we'll just end up with the one instance returned here. But it's
1088 // possible we may get more. Hence, iterate through all instances ..
1089
1090 while ($dao->fetch()) {
5495e78a 1091 // Check pp is extension - is this still required - surely the singleton below handles it.
6a488035
TO
1092 $ext = CRM_Extension_System::singleton()->getMapper();
1093 if ($ext->isExtensionKey($dao->class_name)) {
6a488035
TO
1094 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
1095 require_once $ext->classToPath($paymentClass);
1096 }
6a488035 1097
b47b1631 1098 $processorInstance = Civi\Payment\System::singleton()->getById($dao->processor_id);
6a488035
TO
1099
1100 // Should never be empty - we already established this processor_id exists and is active.
81ebda7b 1101 if (empty($processorInstance)) {
6a488035
TO
1102 continue;
1103 }
1104
6a488035
TO
1105 // Does PP implement this method, and can we call it?
1106 if (!method_exists($processorInstance, $method) ||
1107 !is_callable(array($processorInstance, $method))
1108 ) {
43d1ae00
EM
1109 // on the off chance there is a double implementation of this processor we should keep looking for another
1110 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1111 continue;
6a488035
TO
1112 }
1113
1114 // Everything, it seems, is ok - execute pp callback handler
1115 $processorInstance->$method();
a5ef96f6 1116 $extension_instance_found = TRUE;
6a488035
TO
1117 }
1118
4f99ca55 1119 if (!$extension_instance_found) {
0ac9fd52
CB
1120 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1121 "%2 method is unsupported in legacy payment processors.";
1122 CRM_Core_Error::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
2aa397bc 1123 }
6a488035
TO
1124 }
1125
1126 /**
100fef9d 1127 * Check whether a method is present ( & supported ) by the payment processor object.
6a488035 1128 *
1e483eb5
EM
1129 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1130 *
6a0b768e
TO
1131 * @param string $method
1132 * Method to check for.
6a488035 1133 *
7c550ca0 1134 * @return bool
6a488035 1135 */
00be9182 1136 public function isSupported($method = 'cancelSubscription') {
6a488035
TO
1137 return method_exists(CRM_Utils_System::getClassName($this), $method);
1138 }
1139
1ba4a3aa
EM
1140 /**
1141 * Some processors replace the form submit button with their own.
1142 *
1143 * Returning false here will leave the button off front end forms.
1144 *
1145 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1146 */
1147 public function isSuppressSubmitButtons() {
1148 return FALSE;
1149 }
1150
d253aeb8
EM
1151 /**
1152 * Checks to see if invoice_id already exists in db.
1153 *
1154 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1155 * it is better to standardise to being here.
1156 *
1157 * @param int $invoiceId The ID to check.
1158 *
1159 * @param null $contributionID
1160 * If a contribution exists pass in the contribution ID.
1161 *
1162 * @return bool
1163 * True if invoice ID otherwise exists, else false
1164 */
1165 protected function checkDupe($invoiceId, $contributionID = NULL) {
1166 $contribution = new CRM_Contribute_DAO_Contribution();
1167 $contribution->invoice_id = $invoiceId;
1168 if ($contributionID) {
1169 $contribution->whereAdd("id <> $contributionID");
1170 }
1171 return $contribution->find();
1172 }
1173
a0ee3941 1174 /**
3782df3e
EM
1175 * Get url for users to manage this recurring contribution for this processor.
1176 *
100fef9d 1177 * @param int $entityID
a0ee3941
EM
1178 * @param null $entity
1179 * @param string $action
1180 *
1181 * @return string
1182 */
00be9182 1183 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
03cfff4c
KW
1184 // Set URL
1185 switch ($action) {
2aa397bc 1186 case 'cancel':
03cfff4c
KW
1187 $url = 'civicrm/contribute/unsubscribe';
1188 break;
2aa397bc
TO
1189
1190 case 'billing':
03cfff4c 1191 //in notify mode don't return the update billing url
68acd6ae 1192 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
03cfff4c
KW
1193 return NULL;
1194 }
68acd6ae 1195 $url = 'civicrm/contribute/updatebilling';
03cfff4c 1196 break;
2aa397bc
TO
1197
1198 case 'update':
03cfff4c
KW
1199 $url = 'civicrm/contribute/updaterecur';
1200 break;
6a488035
TO
1201 }
1202
353ffa53
TO
1203 $session = CRM_Core_Session::singleton();
1204 $userId = $session->get('userID');
1205 $contactID = 0;
03cfff4c 1206 $checksumValue = '';
353ffa53 1207 $entityArg = '';
03cfff4c
KW
1208
1209 // Find related Contact
1210 if ($entityID) {
1211 switch ($entity) {
2aa397bc 1212 case 'membership':
03cfff4c
KW
1213 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1214 $entityArg = 'mid';
1215 break;
1216
2aa397bc 1217 case 'contribution':
03cfff4c
KW
1218 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1219 $entityArg = 'coid';
1220 break;
1221
2aa397bc 1222 case 'recur':
03cfff4c 1223 $sql = "
6a488035
TO
1224 SELECT con.contact_id
1225 FROM civicrm_contribution_recur rec
1226INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1227 WHERE rec.id = %1
1228 GROUP BY rec.id";
03cfff4c
KW
1229 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
1230 $entityArg = 'crid';
1231 break;
6a488035 1232 }
6a488035
TO
1233 }
1234
03cfff4c
KW
1235 // Add entity arguments
1236 if ($entityArg != '') {
1237 // Add checksum argument
1238 if ($contactID != 0 && $userId != $contactID) {
1239 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1240 }
1241 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1242 }
1243
1244 // Else login URL
6a488035
TO
1245 if ($this->isSupported('accountLoginURL')) {
1246 return $this->accountLoginURL();
1247 }
03cfff4c
KW
1248
1249 // Else default
735d988f 1250 return isset($this->_paymentProcessor['url_recur']) ? $this->_paymentProcessor['url_recur'] : '';
6a488035 1251 }
96025800 1252
efa36d6e 1253 /**
1254 * Get description of payment to pass to processor.
1255 *
1256 * This is often what people see in the interface so we want to get
1257 * as much unique information in as possible within the field length (& presumably the early part of the field)
1258 *
1259 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1260 * having field names to clarify
1261 *
1262 * @param array $params
1263 * @param int $length
1264 *
1265 * @return string
1266 */
1267 protected function getPaymentDescription($params, $length = 24) {
1268 $parts = array('contactID', 'contributionID', 'description', 'billing_first_name', 'billing_last_name');
1269 $validParts = array();
1270 if (isset($params['description'])) {
1271 $uninformativeStrings = array(ts('Online Event Registration: '), ts('Online Contribution: '));
1272 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1273 }
1274 foreach ($parts as $part) {
1275 if ((!empty($params[$part]))) {
1276 $validParts[] = $params[$part];
1277 }
1278 }
1279 return substr(implode('-', $validParts), 0, $length);
1280 }
1281
95974e8e
DG
1282 /**
1283 * Checks if backoffice recurring edit is allowed
1284 *
1285 * @return bool
1286 */
1287 public function supportsEditRecurringContribution() {
1288 return FALSE;
1289 }
1290
6a488035 1291}