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