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