Merge pull request #8471 from johanv/CRM-18697-export_batches
[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 * 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);
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 * Getter for accessing member vars.
417 *
418 * @todo believe this is unused
419 *
420 * @param string $name
421 *
422 * @return null
423 */
424 public function getVar($name) {
425 return isset($this->$name) ? $this->$name : NULL;
426 }
427
428 /**
429 * Get name for the payment information type.
430 * @todo - use option group + name field (like Omnipay does)
431 * @return string
432 */
433 public function getPaymentTypeName() {
434 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
435 }
436
437 /**
438 * Get label for the payment information type.
439 * @todo - use option group + labels (like Omnipay does)
440 * @return string
441 */
442 public function getPaymentTypeLabel() {
443 return $this->_paymentProcessor['payment_type'] == 1 ? 'Credit Card' : 'Direct Debit';
444 }
445
446 /**
447 * Get array of fields that should be displayed on the payment form.
448 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
449 * @return array
450 * @throws CiviCRM_API3_Exception
451 */
452 public function getPaymentFormFields() {
453 if ($this->_paymentProcessor['billing_mode'] == 4) {
454 return array();
455 }
456 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
457 }
458
459 /**
460 * Get an array of the fields that can be edited on the recurring contribution.
461 *
462 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
463 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
464 * can be updated from the contribution recur edit screen.
465 *
466 * The fields are likely to be a subset of these
467 * - 'amount',
468 * - 'installments',
469 * - 'frequency_interval',
470 * - 'frequency_unit',
471 * - 'cycle_day',
472 * - 'next_sched_contribution_date',
473 * - 'end_date',
474 * - 'failure_retry_day',
475 *
476 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
477 * metadata is not defined in the xml for the field it will cause an error.
478 *
479 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
480 * form (UpdateSubscription).
481 *
482 * @return array
483 */
484 public function getEditableRecurringScheduleFields() {
485 if (method_exists($this, 'changeSubscriptionAmount')) {
486 return array('amount');
487 }
488 }
489
490 /**
491 * Get the help text to present on the recurring update page.
492 *
493 * This should reflect what can or cannot be edited.
494 *
495 * @return string
496 */
497 public function getRecurringScheduleUpdateHelpText() {
498 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
499 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.');
500 }
501 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.');
502 }
503
504 /**
505 * Get the metadata for all required fields.
506 *
507 * @return array;
508 */
509 protected function getMandatoryFields() {
510 $mandatoryFields = array();
511 foreach ($this->getAllFields() as $field_name => $field_spec) {
512 if (!empty($field_spec['is_required'])) {
513 $mandatoryFields[$field_name] = $field_spec;
514 }
515 }
516 return $mandatoryFields;
517 }
518
519 /**
520 * Get the metadata of all the fields configured for this processor.
521 *
522 * @return array
523 */
524 protected function getAllFields() {
525 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
526 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
527 return array_merge($paymentFields, $billingFields);
528 }
529 /**
530 * Get array of fields that should be displayed on the payment form for credit cards.
531 *
532 * @return array
533 */
534 protected function getCreditCardFormFields() {
535 return array(
536 'credit_card_type',
537 'credit_card_number',
538 'cvv2',
539 'credit_card_exp_date',
540 );
541 }
542
543 /**
544 * Get array of fields that should be displayed on the payment form for direct debits.
545 *
546 * @return array
547 */
548 protected function getDirectDebitFormFields() {
549 return array(
550 'account_holder',
551 'bank_account_number',
552 'bank_identification_number',
553 'bank_name',
554 );
555 }
556
557 /**
558 * Return an array of all the details about the fields potentially required for payment fields.
559 *
560 * Only those determined by getPaymentFormFields will actually be assigned to the form
561 *
562 * @return array
563 * field metadata
564 */
565 public function getPaymentFormFieldsMetadata() {
566 //@todo convert credit card type into an option value
567 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
568 return array(
569 'credit_card_number' => array(
570 'htmlType' => 'text',
571 'name' => 'credit_card_number',
572 'title' => ts('Card Number'),
573 'cc_field' => TRUE,
574 'attributes' => array(
575 'size' => 20,
576 'maxlength' => 20,
577 'autocomplete' => 'off',
578 'class' => 'creditcard',
579 ),
580 'is_required' => TRUE,
581 ),
582 'cvv2' => array(
583 'htmlType' => 'text',
584 'name' => 'cvv2',
585 'title' => ts('Security Code'),
586 'cc_field' => TRUE,
587 'attributes' => array(
588 'size' => 5,
589 'maxlength' => 10,
590 'autocomplete' => 'off',
591 ),
592 'is_required' => Civi::settings()->get('cvv_backoffice_required'),
593 'rules' => array(
594 array(
595 '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.'),
596 'rule_name' => 'integer',
597 'rule_parameters' => NULL,
598 ),
599 ),
600 ),
601 'credit_card_exp_date' => array(
602 'htmlType' => 'date',
603 'name' => 'credit_card_exp_date',
604 'title' => ts('Expiration Date'),
605 'cc_field' => TRUE,
606 'attributes' => CRM_Core_SelectValues::date('creditCard'),
607 'is_required' => TRUE,
608 'rules' => array(
609 array(
610 'rule_message' => ts('Card expiration date cannot be a past date.'),
611 'rule_name' => 'currentDate',
612 'rule_parameters' => TRUE,
613 ),
614 ),
615 ),
616 'credit_card_type' => array(
617 'htmlType' => 'select',
618 'name' => 'credit_card_type',
619 'title' => ts('Card Type'),
620 'cc_field' => TRUE,
621 'attributes' => $creditCardType,
622 'is_required' => FALSE,
623 ),
624 'account_holder' => array(
625 'htmlType' => 'text',
626 'name' => 'account_holder',
627 'title' => ts('Account Holder'),
628 'cc_field' => TRUE,
629 'attributes' => array(
630 'size' => 20,
631 'maxlength' => 34,
632 'autocomplete' => 'on',
633 ),
634 'is_required' => TRUE,
635 ),
636 //e.g. IBAN can have maxlength of 34 digits
637 'bank_account_number' => array(
638 'htmlType' => 'text',
639 'name' => 'bank_account_number',
640 'title' => ts('Bank Account Number'),
641 'cc_field' => TRUE,
642 'attributes' => array(
643 'size' => 20,
644 'maxlength' => 34,
645 'autocomplete' => 'off',
646 ),
647 'rules' => array(
648 array(
649 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
650 'rule_name' => 'nopunctuation',
651 'rule_parameters' => NULL,
652 ),
653 ),
654 'is_required' => TRUE,
655 ),
656 //e.g. SWIFT-BIC can have maxlength of 11 digits
657 'bank_identification_number' => array(
658 'htmlType' => 'text',
659 'name' => 'bank_identification_number',
660 'title' => ts('Bank Identification Number'),
661 'cc_field' => TRUE,
662 'attributes' => array(
663 'size' => 20,
664 'maxlength' => 11,
665 'autocomplete' => 'off',
666 ),
667 'is_required' => TRUE,
668 'rules' => array(
669 array(
670 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
671 'rule_name' => 'nopunctuation',
672 'rule_parameters' => NULL,
673 ),
674 ),
675 ),
676 'bank_name' => array(
677 'htmlType' => 'text',
678 'name' => 'bank_name',
679 'title' => ts('Bank Name'),
680 'cc_field' => TRUE,
681 'attributes' => array(
682 'size' => 20,
683 'maxlength' => 64,
684 'autocomplete' => 'off',
685 ),
686 'is_required' => TRUE,
687
688 ),
689 );
690 }
691
692 /**
693 * Get billing fields required for this processor.
694 *
695 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
696 * alter.
697 *
698 * @param int $billingLocationID
699 *
700 * @return array
701 */
702 public function getBillingAddressFields($billingLocationID = NULL) {
703 if (!$billingLocationID) {
704 // Note that although the billing id is passed around the forms the idea that it would be anything other than
705 // the result of the function below doesn't seem to have eventuated.
706 // So taking this as a param is possibly something to be removed in favour of the standard default.
707 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
708 }
709 if ($this->_paymentProcessor['billing_mode'] != 1 && $this->_paymentProcessor['billing_mode'] != 3) {
710 return array();
711 }
712 return array(
713 'first_name' => 'billing_first_name',
714 'middle_name' => 'billing_middle_name',
715 'last_name' => 'billing_last_name',
716 'street_address' => "billing_street_address-{$billingLocationID}",
717 'city' => "billing_city-{$billingLocationID}",
718 'country' => "billing_country_id-{$billingLocationID}",
719 'state_province' => "billing_state_province_id-{$billingLocationID}",
720 'postal_code' => "billing_postal_code-{$billingLocationID}",
721 );
722 }
723
724 /**
725 * Get form metadata for billing address fields.
726 *
727 * @param int $billingLocationID
728 *
729 * @return array
730 * Array of metadata for address fields.
731 */
732 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
733 if (!$billingLocationID) {
734 // Note that although the billing id is passed around the forms the idea that it would be anything other than
735 // the result of the function below doesn't seem to have eventuated.
736 // So taking this as a param is possibly something to be removed in favour of the standard default.
737 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
738 }
739 $metadata = array();
740 $metadata['billing_first_name'] = array(
741 'htmlType' => 'text',
742 'name' => 'billing_first_name',
743 'title' => ts('Billing First Name'),
744 'cc_field' => TRUE,
745 'attributes' => array(
746 'size' => 30,
747 'maxlength' => 60,
748 'autocomplete' => 'off',
749 ),
750 'is_required' => TRUE,
751 );
752
753 $metadata['billing_middle_name'] = array(
754 'htmlType' => 'text',
755 'name' => 'billing_middle_name',
756 'title' => ts('Billing Middle Name'),
757 'cc_field' => TRUE,
758 'attributes' => array(
759 'size' => 30,
760 'maxlength' => 60,
761 'autocomplete' => 'off',
762 ),
763 'is_required' => FALSE,
764 );
765
766 $metadata['billing_last_name'] = array(
767 'htmlType' => 'text',
768 'name' => 'billing_last_name',
769 'title' => ts('Billing Last Name'),
770 'cc_field' => TRUE,
771 'attributes' => array(
772 'size' => 30,
773 'maxlength' => 60,
774 'autocomplete' => 'off',
775 ),
776 'is_required' => TRUE,
777 );
778
779 $metadata["billing_street_address-{$billingLocationID}"] = array(
780 'htmlType' => 'text',
781 'name' => "billing_street_address-{$billingLocationID}",
782 'title' => ts('Street Address'),
783 'cc_field' => TRUE,
784 'attributes' => array(
785 'size' => 30,
786 'maxlength' => 60,
787 'autocomplete' => 'off',
788 ),
789 'is_required' => TRUE,
790 );
791
792 $metadata["billing_city-{$billingLocationID}"] = array(
793 'htmlType' => 'text',
794 'name' => "billing_city-{$billingLocationID}",
795 'title' => ts('City'),
796 'cc_field' => TRUE,
797 'attributes' => array(
798 'size' => 30,
799 'maxlength' => 60,
800 'autocomplete' => 'off',
801 ),
802 'is_required' => TRUE,
803 );
804
805 $metadata["billing_state_province_id-{$billingLocationID}"] = array(
806 'htmlType' => 'chainSelect',
807 'title' => ts('State/Province'),
808 'name' => "billing_state_province_id-{$billingLocationID}",
809 'cc_field' => TRUE,
810 'is_required' => TRUE,
811 );
812
813 $metadata["billing_postal_code-{$billingLocationID}"] = array(
814 'htmlType' => 'text',
815 'name' => "billing_postal_code-{$billingLocationID}",
816 'title' => ts('Postal Code'),
817 'cc_field' => TRUE,
818 'attributes' => array(
819 'size' => 30,
820 'maxlength' => 60,
821 'autocomplete' => 'off',
822 ),
823 'is_required' => TRUE,
824 );
825
826 $metadata["billing_country_id-{$billingLocationID}"] = array(
827 'htmlType' => 'select',
828 'name' => "billing_country_id-{$billingLocationID}",
829 'title' => ts('Country'),
830 'cc_field' => TRUE,
831 'attributes' => array(
832 '' => ts('- select -'),
833 ) + CRM_Core_PseudoConstant::country(),
834 'is_required' => TRUE,
835 );
836 return $metadata;
837 }
838
839 /**
840 * Get base url dependent on component.
841 *
842 * (or preferably set it using the setter function).
843 *
844 * @return string
845 */
846 protected function getBaseReturnUrl() {
847 if ($this->baseReturnUrl) {
848 return $this->baseReturnUrl;
849 }
850 if ($this->_component == 'event') {
851 $baseURL = 'civicrm/event/register';
852 }
853 else {
854 $baseURL = 'civicrm/contribute/transact';
855 }
856 return $baseURL;
857 }
858
859 /**
860 * Get url to return to after cancelled or failed transaction
861 *
862 * @param $qfKey
863 * @param $participantID
864 *
865 * @return string cancel url
866 */
867 public function getCancelUrl($qfKey, $participantID) {
868 if (isset($this->cancelUrl)) {
869 return $this->cancelUrl;
870 }
871
872 if ($this->_component == 'event') {
873 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
874 'reset' => 1,
875 'cc' => 'fail',
876 'participantId' => $participantID,
877 ),
878 TRUE, NULL, FALSE
879 );
880 }
881
882 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
883 '_qf_Main_display' => 1,
884 'qfKey' => $qfKey,
885 'cancel' => 1,
886 ),
887 TRUE, NULL, FALSE
888 );
889 }
890
891 /**
892 * Get URL to return the browser to on success.
893 *
894 * @param $qfKey
895 *
896 * @return string
897 */
898 protected function getReturnSuccessUrl($qfKey) {
899 if (isset($this->successUrl)) {
900 return $this->successUrl;
901 }
902
903 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
904 '_qf_ThankYou_display' => 1,
905 'qfKey' => $qfKey,
906 ),
907 TRUE, NULL, FALSE
908 );
909 }
910
911 /**
912 * Get URL to return the browser to on failure.
913 *
914 * @param string $key
915 * @param int $participantID
916 * @param int $eventID
917 *
918 * @return string
919 * URL for a failing transactor to be redirected to.
920 */
921 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
922 if (isset($this->cancelUrl)) {
923 return $this->cancelUrl;
924 }
925
926 $test = $this->_is_test ? '&action=preview' : '';
927 if ($this->_component == "event") {
928 return CRM_Utils_System::url('civicrm/event/register',
929 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
930 FALSE, NULL, FALSE
931 );
932 }
933 else {
934 return CRM_Utils_System::url('civicrm/contribute/transact',
935 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
936 FALSE, NULL, FALSE
937 );
938 }
939 }
940
941 /**
942 * Get URl for when the back button is pressed.
943 *
944 * @param $qfKey
945 *
946 * @return string url
947 */
948 protected function getGoBackUrl($qfKey) {
949 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
950 '_qf_Confirm_display' => 'true',
951 'qfKey' => $qfKey,
952 ),
953 TRUE, NULL, FALSE
954 );
955 }
956
957 /**
958 * Get the notify (aka ipn, web hook or silent post) url.
959 *
960 * If there is no '.' in it we assume that we are dealing with localhost or
961 * similar and it is unreachable from the web & hence invalid.
962 *
963 * @return string
964 * URL to notify outcome of transaction.
965 */
966 protected function getNotifyUrl() {
967 $url = CRM_Utils_System::url(
968 'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
969 array(),
970 TRUE
971 );
972 return (stristr($url, '.')) ? $url : '';
973 }
974
975 /**
976 * Calling this from outside the payment subsystem is deprecated - use doPayment.
977 *
978 * Does a server to server payment transaction.
979 *
980 * @param array $params
981 * Assoc array of input parameters for this transaction.
982 *
983 * @return array
984 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
985 */
986 protected function doDirectPayment(&$params) {
987 return $params;
988 }
989
990 /**
991 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
992 *
993 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
994 * more agnostic.
995 *
996 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
997 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
998 * doTransferCheckout would not traditionally come back.
999 *
1000 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
1001 * to be Pending.
1002 *
1003 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
1004 * return Error objects
1005 *
1006 * @param array $params
1007 *
1008 * @param string $component
1009 *
1010 * @return array
1011 * Result array
1012 *
1013 * @throws \Civi\Payment\Exception\PaymentProcessorException
1014 */
1015 public function doPayment(&$params, $component = 'contribute') {
1016 $this->_component = $component;
1017 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
1018
1019 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1020 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1021 // have an example of that at the mome.
1022 if ($params['amount'] == 0) {
1023 $result['payment_status_id'] = array_search('Completed', $statuses);
1024 return $result;
1025 }
1026
1027 if ($this->_paymentProcessor['billing_mode'] == 4) {
1028 $result = $this->doTransferCheckout($params, $component);
1029 if (is_array($result) && !isset($result['payment_status_id'])) {
1030 $result['payment_status_id'] = array_search('Pending', $statuses);
1031 }
1032 }
1033 else {
1034 $result = $this->doDirectPayment($params, $component);
1035 if (is_array($result) && !isset($result['payment_status_id'])) {
1036 if (!empty($params['is_recur'])) {
1037 // See comment block.
1038 $result['payment_status_id'] = array_search('Pending', $statuses);
1039 }
1040 else {
1041 $result['payment_status_id'] = array_search('Completed', $statuses);
1042 }
1043 }
1044 }
1045 if (is_a($result, 'CRM_Core_Error')) {
1046 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
1047 }
1048 return $result;
1049 }
1050
1051 /**
1052 * Query payment processor for details about a transaction.
1053 *
1054 * @param array $params
1055 * Array of parameters containing one of:
1056 * - trxn_id Id of an individual transaction.
1057 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1058 *
1059 * @return array
1060 * Extra parameters retrieved.
1061 * Any parameters retrievable through this should be documented in the function comments at
1062 * CRM_Core_Payment::doQuery. Currently:
1063 * - fee_amount Amount of fee paid
1064 */
1065 public function doQuery($params) {
1066 return array();
1067 }
1068
1069 /**
1070 * This function checks to see if we have the right config values.
1071 *
1072 * @return string
1073 * the error message if any
1074 */
1075 abstract protected function checkConfig();
1076
1077 /**
1078 * Redirect for paypal.
1079 *
1080 * @todo move to paypal class or remove
1081 *
1082 * @param $paymentProcessor
1083 *
1084 * @return bool
1085 */
1086 public static function paypalRedirect(&$paymentProcessor) {
1087 if (!$paymentProcessor) {
1088 return FALSE;
1089 }
1090
1091 if (isset($_GET['payment_date']) &&
1092 isset($_GET['merchant_return_link']) &&
1093 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
1094 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1095 ) {
1096 return TRUE;
1097 }
1098
1099 return FALSE;
1100 }
1101
1102 /**
1103 * Handle incoming payment notification.
1104 *
1105 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1106 *
1107 * @todo move to0 \Civi\Payment\System factory method
1108 * Page callback for civicrm/payment/ipn
1109 */
1110 public static function handleIPN() {
1111 self::handlePaymentMethod(
1112 'PaymentNotification',
1113 array(
1114 'processor_name' => @$_GET['processor_name'],
1115 'processor_id' => @$_GET['processor_id'],
1116 'mode' => @$_GET['mode'],
1117 'q' => @$_GET['q'],
1118 )
1119 );
1120 CRM_Utils_System::civiExit();
1121 }
1122
1123 /**
1124 * Payment callback handler.
1125 *
1126 * The processor_name or processor_id is passed in.
1127 * Note that processor_id is more reliable as one site may have more than one instance of a
1128 * processor & ideally the processor will be validating the results
1129 * Load requested payment processor and call that processor's handle<$method> method
1130 *
1131 * @todo move to \Civi\Payment\System factory method
1132 *
1133 * @param string $method
1134 * 'PaymentNotification' or 'PaymentCron'
1135 * @param array $params
1136 *
1137 * @throws \CRM_Core_Exception
1138 * @throws \Exception
1139 */
1140 public static function handlePaymentMethod($method, $params = array()) {
1141 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1142 $q = explode('/', CRM_Utils_Array::value('q', $params, ''));
1143 $lastParam = array_pop($q);
1144 if (is_numeric($lastParam)) {
1145 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1146 }
1147 else {
1148 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1149 }
1150 }
1151
1152 self::logPaymentNotification($params);
1153
1154 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1155 FROM civicrm_payment_processor_type ppt
1156 INNER JOIN civicrm_payment_processor pp
1157 ON pp.payment_processor_type_id = ppt.id
1158 AND pp.is_active";
1159
1160 if (isset($params['processor_id'])) {
1161 $sql .= " WHERE pp.id = %2";
1162 $args[2] = array($params['processor_id'], 'Integer');
1163 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
1164 }
1165 else {
1166 // This is called when processor_name is passed - passing processor_id instead is recommended.
1167 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1168 $args[1] = array(
1169 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
1170 'Integer',
1171 );
1172 $args[2] = array($params['processor_name'], 'String');
1173 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
1174 }
1175
1176 $dao = CRM_Core_DAO::executeQuery($sql, $args);
1177
1178 // Check whether we found anything at all.
1179 if (!$dao->N) {
1180 CRM_Core_Error::fatal($notFound);
1181 }
1182
1183 $method = 'handle' . $method;
1184 $extension_instance_found = FALSE;
1185
1186 // In all likelihood, we'll just end up with the one instance returned here. But it's
1187 // possible we may get more. Hence, iterate through all instances ..
1188
1189 while ($dao->fetch()) {
1190 // Check pp is extension - is this still required - surely the singleton below handles it.
1191 $ext = CRM_Extension_System::singleton()->getMapper();
1192 if ($ext->isExtensionKey($dao->class_name)) {
1193 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
1194 require_once $ext->classToPath($paymentClass);
1195 }
1196
1197 $processorInstance = System::singleton()->getById($dao->processor_id);
1198
1199 // Should never be empty - we already established this processor_id exists and is active.
1200 if (empty($processorInstance)) {
1201 continue;
1202 }
1203
1204 // Does PP implement this method, and can we call it?
1205 if (!method_exists($processorInstance, $method) ||
1206 !is_callable(array($processorInstance, $method))
1207 ) {
1208 // on the off chance there is a double implementation of this processor we should keep looking for another
1209 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1210 continue;
1211 }
1212
1213 // Everything, it seems, is ok - execute pp callback handler
1214 $processorInstance->$method();
1215 $extension_instance_found = TRUE;
1216 }
1217
1218 if (!$extension_instance_found) {
1219 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1220 "%2 method is unsupported in legacy payment processors.";
1221 CRM_Core_Error::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
1222 }
1223 }
1224
1225 /**
1226 * Check whether a method is present ( & supported ) by the payment processor object.
1227 *
1228 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1229 *
1230 * @param string $method
1231 * Method to check for.
1232 *
1233 * @return bool
1234 */
1235 public function isSupported($method) {
1236 return method_exists(CRM_Utils_System::getClassName($this), $method);
1237 }
1238
1239 /**
1240 * Some processors replace the form submit button with their own.
1241 *
1242 * Returning false here will leave the button off front end forms.
1243 *
1244 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1245 */
1246 public function isSuppressSubmitButtons() {
1247 return FALSE;
1248 }
1249
1250 /**
1251 * Checks to see if invoice_id already exists in db.
1252 *
1253 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1254 * it is better to standardise to being here.
1255 *
1256 * @param int $invoiceId The ID to check.
1257 *
1258 * @param null $contributionID
1259 * If a contribution exists pass in the contribution ID.
1260 *
1261 * @return bool
1262 * True if invoice ID otherwise exists, else false
1263 */
1264 protected function checkDupe($invoiceId, $contributionID = NULL) {
1265 $contribution = new CRM_Contribute_DAO_Contribution();
1266 $contribution->invoice_id = $invoiceId;
1267 if ($contributionID) {
1268 $contribution->whereAdd("id <> $contributionID");
1269 }
1270 return $contribution->find();
1271 }
1272
1273 /**
1274 * Get url for users to manage this recurring contribution for this processor.
1275 *
1276 * @param int $entityID
1277 * @param null $entity
1278 * @param string $action
1279 *
1280 * @return string
1281 */
1282 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1283 // Set URL
1284 switch ($action) {
1285 case 'cancel':
1286 $url = 'civicrm/contribute/unsubscribe';
1287 break;
1288
1289 case 'billing':
1290 //in notify mode don't return the update billing url
1291 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
1292 return NULL;
1293 }
1294 $url = 'civicrm/contribute/updatebilling';
1295 break;
1296
1297 case 'update':
1298 $url = 'civicrm/contribute/updaterecur';
1299 break;
1300 }
1301
1302 $userId = CRM_Core_Session::singleton()->get('userID');
1303 $contactID = 0;
1304 $checksumValue = '';
1305 $entityArg = '';
1306
1307 // Find related Contact
1308 if ($entityID) {
1309 switch ($entity) {
1310 case 'membership':
1311 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1312 $entityArg = 'mid';
1313 break;
1314
1315 case 'contribution':
1316 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1317 $entityArg = 'coid';
1318 break;
1319
1320 case 'recur':
1321 $sql = "
1322 SELECT con.contact_id
1323 FROM civicrm_contribution_recur rec
1324 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1325 WHERE rec.id = %1
1326 GROUP BY rec.id";
1327 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
1328 $entityArg = 'crid';
1329 break;
1330 }
1331 }
1332
1333 // Add entity arguments
1334 if ($entityArg != '') {
1335 // Add checksum argument
1336 if ($contactID != 0 && $userId != $contactID) {
1337 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1338 }
1339 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1340 }
1341
1342 // Else login URL
1343 if ($this->isSupported('accountLoginURL')) {
1344 return $this->accountLoginURL();
1345 }
1346
1347 // Else default
1348 return isset($this->_paymentProcessor['url_recur']) ? $this->_paymentProcessor['url_recur'] : '';
1349 }
1350
1351 /**
1352 * Get description of payment to pass to processor.
1353 *
1354 * This is often what people see in the interface so we want to get
1355 * as much unique information in as possible within the field length (& presumably the early part of the field)
1356 *
1357 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1358 * having field names to clarify
1359 *
1360 * @param array $params
1361 * @param int $length
1362 *
1363 * @return string
1364 */
1365 protected function getPaymentDescription($params, $length = 24) {
1366 $parts = array('contactID', 'contributionID', 'description', 'billing_first_name', 'billing_last_name');
1367 $validParts = array();
1368 if (isset($params['description'])) {
1369 $uninformativeStrings = array(ts('Online Event Registration: '), ts('Online Contribution: '));
1370 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1371 }
1372 foreach ($parts as $part) {
1373 if ((!empty($params[$part]))) {
1374 $validParts[] = $params[$part];
1375 }
1376 }
1377 return substr(implode('-', $validParts), 0, $length);
1378 }
1379
1380 /**
1381 * Checks if backoffice recurring edit is allowed
1382 *
1383 * @return bool
1384 */
1385 public function supportsEditRecurringContribution() {
1386 return FALSE;
1387 }
1388
1389 /**
1390 * Should a receipt be sent out for a pending payment.
1391 *
1392 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1393 */
1394 public function isSendReceiptForPending() {
1395 return FALSE;
1396 }
1397
1398 }