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