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