Merge pull request #9209 from otetard/CRM-19483
[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($this->_paymentProcessor['id'], $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 string $qfKey
863 * @param int $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 NULL,
972 FALSE
973 );
974 return (stristr($url, '.')) ? $url : '';
975 }
976
977 /**
978 * Calling this from outside the payment subsystem is deprecated - use doPayment.
979 *
980 * Does a server to server payment transaction.
981 *
982 * @param array $params
983 * Assoc array of input parameters for this transaction.
984 *
985 * @return array
986 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
987 */
988 protected function doDirectPayment(&$params) {
989 return $params;
990 }
991
992 /**
993 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
994 *
995 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
996 * more agnostic.
997 *
998 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
999 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
1000 * doTransferCheckout would not traditionally come back.
1001 *
1002 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
1003 * to be Pending.
1004 *
1005 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
1006 * return Error objects
1007 *
1008 * @param array $params
1009 *
1010 * @param string $component
1011 *
1012 * @return array
1013 * Result array
1014 *
1015 * @throws \Civi\Payment\Exception\PaymentProcessorException
1016 */
1017 public function doPayment(&$params, $component = 'contribute') {
1018 $this->_component = $component;
1019 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
1020
1021 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1022 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1023 // have an example of that at the mome.
1024 if ($params['amount'] == 0) {
1025 $result['payment_status_id'] = array_search('Completed', $statuses);
1026 return $result;
1027 }
1028
1029 if ($this->_paymentProcessor['billing_mode'] == 4) {
1030 $result = $this->doTransferCheckout($params, $component);
1031 if (is_array($result) && !isset($result['payment_status_id'])) {
1032 $result['payment_status_id'] = array_search('Pending', $statuses);
1033 }
1034 }
1035 else {
1036 $result = $this->doDirectPayment($params, $component);
1037 if (is_array($result) && !isset($result['payment_status_id'])) {
1038 if (!empty($params['is_recur'])) {
1039 // See comment block.
1040 $result['payment_status_id'] = array_search('Pending', $statuses);
1041 }
1042 else {
1043 $result['payment_status_id'] = array_search('Completed', $statuses);
1044 }
1045 }
1046 }
1047 if (is_a($result, 'CRM_Core_Error')) {
1048 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
1049 }
1050 return $result;
1051 }
1052
1053 /**
1054 * Query payment processor for details about a transaction.
1055 *
1056 * @param array $params
1057 * Array of parameters containing one of:
1058 * - trxn_id Id of an individual transaction.
1059 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1060 *
1061 * @return array
1062 * Extra parameters retrieved.
1063 * Any parameters retrievable through this should be documented in the function comments at
1064 * CRM_Core_Payment::doQuery. Currently:
1065 * - fee_amount Amount of fee paid
1066 */
1067 public function doQuery($params) {
1068 return array();
1069 }
1070
1071 /**
1072 * This function checks to see if we have the right config values.
1073 *
1074 * @return string
1075 * the error message if any
1076 */
1077 abstract protected function checkConfig();
1078
1079 /**
1080 * Redirect for paypal.
1081 *
1082 * @todo move to paypal class or remove
1083 *
1084 * @param $paymentProcessor
1085 *
1086 * @return bool
1087 */
1088 public static function paypalRedirect(&$paymentProcessor) {
1089 if (!$paymentProcessor) {
1090 return FALSE;
1091 }
1092
1093 if (isset($_GET['payment_date']) &&
1094 isset($_GET['merchant_return_link']) &&
1095 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
1096 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1097 ) {
1098 return TRUE;
1099 }
1100
1101 return FALSE;
1102 }
1103
1104 /**
1105 * Handle incoming payment notification.
1106 *
1107 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1108 *
1109 * @todo move to0 \Civi\Payment\System factory method
1110 * Page callback for civicrm/payment/ipn
1111 */
1112 public static function handleIPN() {
1113 self::handlePaymentMethod(
1114 'PaymentNotification',
1115 array(
1116 'processor_name' => @$_GET['processor_name'],
1117 'processor_id' => @$_GET['processor_id'],
1118 'mode' => @$_GET['mode'],
1119 )
1120 );
1121 CRM_Utils_System::civiExit();
1122 }
1123
1124 /**
1125 * Payment callback handler.
1126 *
1127 * The processor_name or processor_id is passed in.
1128 * Note that processor_id is more reliable as one site may have more than one instance of a
1129 * processor & ideally the processor will be validating the results
1130 * Load requested payment processor and call that processor's handle<$method> method
1131 *
1132 * @todo move to \Civi\Payment\System factory method
1133 *
1134 * @param string $method
1135 * 'PaymentNotification' or 'PaymentCron'
1136 * @param array $params
1137 *
1138 * @throws \CRM_Core_Exception
1139 * @throws \Exception
1140 */
1141 public static function handlePaymentMethod($method, $params = array()) {
1142 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1143 $q = explode('/', CRM_Utils_Array::value(CRM_Core_Config::singleton()->userFrameworkURLVar, $_GET, ''));
1144 $lastParam = array_pop($q);
1145 if (is_numeric($lastParam)) {
1146 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1147 }
1148 else {
1149 self::logPaymentNotification($params);
1150 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1151 }
1152 }
1153
1154 self::logPaymentNotification($params);
1155
1156 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1157 FROM civicrm_payment_processor_type ppt
1158 INNER JOIN civicrm_payment_processor pp
1159 ON pp.payment_processor_type_id = ppt.id
1160 AND pp.is_active";
1161
1162 if (isset($params['processor_id'])) {
1163 $sql .= " WHERE pp.id = %2";
1164 $args[2] = array($params['processor_id'], 'Integer');
1165 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
1166 }
1167 else {
1168 // This is called when processor_name is passed - passing processor_id instead is recommended.
1169 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1170 $args[1] = array(
1171 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
1172 'Integer',
1173 );
1174 $args[2] = array($params['processor_name'], 'String');
1175 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
1176 }
1177
1178 $dao = CRM_Core_DAO::executeQuery($sql, $args);
1179
1180 // Check whether we found anything at all.
1181 if (!$dao->N) {
1182 CRM_Core_Error::fatal($notFound);
1183 }
1184
1185 $method = 'handle' . $method;
1186 $extension_instance_found = FALSE;
1187
1188 // In all likelihood, we'll just end up with the one instance returned here. But it's
1189 // possible we may get more. Hence, iterate through all instances ..
1190
1191 while ($dao->fetch()) {
1192 // Check pp is extension - is this still required - surely the singleton below handles it.
1193 $ext = CRM_Extension_System::singleton()->getMapper();
1194 if ($ext->isExtensionKey($dao->class_name)) {
1195 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
1196 require_once $ext->classToPath($paymentClass);
1197 }
1198
1199 $processorInstance = System::singleton()->getById($dao->processor_id);
1200
1201 // Should never be empty - we already established this processor_id exists and is active.
1202 if (empty($processorInstance)) {
1203 continue;
1204 }
1205
1206 // Does PP implement this method, and can we call it?
1207 if (!method_exists($processorInstance, $method) ||
1208 !is_callable(array($processorInstance, $method))
1209 ) {
1210 // on the off chance there is a double implementation of this processor we should keep looking for another
1211 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1212 continue;
1213 }
1214
1215 // Everything, it seems, is ok - execute pp callback handler
1216 $processorInstance->$method();
1217 $extension_instance_found = TRUE;
1218 }
1219
1220 if (!$extension_instance_found) {
1221 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1222 "%2 method is unsupported in legacy payment processors.";
1223 CRM_Core_Error::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
1224 }
1225 }
1226
1227 /**
1228 * Check whether a method is present ( & supported ) by the payment processor object.
1229 *
1230 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1231 *
1232 * @param string $method
1233 * Method to check for.
1234 *
1235 * @return bool
1236 */
1237 public function isSupported($method) {
1238 return method_exists(CRM_Utils_System::getClassName($this), $method);
1239 }
1240
1241 /**
1242 * Some processors replace the form submit button with their own.
1243 *
1244 * Returning false here will leave the button off front end forms.
1245 *
1246 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1247 */
1248 public function isSuppressSubmitButtons() {
1249 return FALSE;
1250 }
1251
1252 /**
1253 * Checks to see if invoice_id already exists in db.
1254 *
1255 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1256 * it is better to standardise to being here.
1257 *
1258 * @param int $invoiceId The ID to check.
1259 *
1260 * @param null $contributionID
1261 * If a contribution exists pass in the contribution ID.
1262 *
1263 * @return bool
1264 * True if invoice ID otherwise exists, else false
1265 */
1266 protected function checkDupe($invoiceId, $contributionID = NULL) {
1267 $contribution = new CRM_Contribute_DAO_Contribution();
1268 $contribution->invoice_id = $invoiceId;
1269 if ($contributionID) {
1270 $contribution->whereAdd("id <> $contributionID");
1271 }
1272 return $contribution->find();
1273 }
1274
1275 /**
1276 * Get url for users to manage this recurring contribution for this processor.
1277 *
1278 * @param int $entityID
1279 * @param null $entity
1280 * @param string $action
1281 *
1282 * @return string
1283 */
1284 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1285 // Set URL
1286 switch ($action) {
1287 case 'cancel':
1288 $url = 'civicrm/contribute/unsubscribe';
1289 break;
1290
1291 case 'billing':
1292 //in notify mode don't return the update billing url
1293 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
1294 return NULL;
1295 }
1296 $url = 'civicrm/contribute/updatebilling';
1297 break;
1298
1299 case 'update':
1300 $url = 'civicrm/contribute/updaterecur';
1301 break;
1302 }
1303
1304 $userId = CRM_Core_Session::singleton()->get('userID');
1305 $contactID = 0;
1306 $checksumValue = '';
1307 $entityArg = '';
1308
1309 // Find related Contact
1310 if ($entityID) {
1311 switch ($entity) {
1312 case 'membership':
1313 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1314 $entityArg = 'mid';
1315 break;
1316
1317 case 'contribution':
1318 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1319 $entityArg = 'coid';
1320 break;
1321
1322 case 'recur':
1323 $sql = "
1324 SELECT con.contact_id
1325 FROM civicrm_contribution_recur rec
1326 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1327 WHERE rec.id = %1
1328 GROUP BY rec.id";
1329 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
1330 $entityArg = 'crid';
1331 break;
1332 }
1333 }
1334
1335 // Add entity arguments
1336 if ($entityArg != '') {
1337 // Add checksum argument
1338 if ($contactID != 0 && $userId != $contactID) {
1339 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1340 }
1341 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1342 }
1343
1344 // Else login URL
1345 if ($this->isSupported('accountLoginURL')) {
1346 return $this->accountLoginURL();
1347 }
1348
1349 // Else default
1350 return isset($this->_paymentProcessor['url_recur']) ? $this->_paymentProcessor['url_recur'] : '';
1351 }
1352
1353 /**
1354 * Get description of payment to pass to processor.
1355 *
1356 * This is often what people see in the interface so we want to get
1357 * as much unique information in as possible within the field length (& presumably the early part of the field)
1358 *
1359 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1360 * having field names to clarify
1361 *
1362 * @param array $params
1363 * @param int $length
1364 *
1365 * @return string
1366 */
1367 protected function getPaymentDescription($params, $length = 24) {
1368 $parts = array('contactID', 'contributionID', 'description', 'billing_first_name', 'billing_last_name');
1369 $validParts = array();
1370 if (isset($params['description'])) {
1371 $uninformativeStrings = array(ts('Online Event Registration: '), ts('Online Contribution: '));
1372 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1373 }
1374 foreach ($parts as $part) {
1375 if ((!empty($params[$part]))) {
1376 $validParts[] = $params[$part];
1377 }
1378 }
1379 return substr(implode('-', $validParts), 0, $length);
1380 }
1381
1382 /**
1383 * Checks if backoffice recurring edit is allowed
1384 *
1385 * @return bool
1386 */
1387 public function supportsEditRecurringContribution() {
1388 return FALSE;
1389 }
1390
1391 /**
1392 * Should a receipt be sent out for a pending payment.
1393 *
1394 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1395 */
1396 public function isSendReceiptForPending() {
1397 return FALSE;
1398 }
1399
1400 }