3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
28 use Civi\Payment\System
;
29 use Civi\Payment\Exception\PaymentProcessorException
;
32 * Class CRM_Core_Payment.
34 * This class is the main class for the payment processor subsystem.
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.
39 abstract class CRM_Core_Payment
{
42 * Component - ie. event or contribute.
44 * This is used for setting return urls.
48 protected $_component;
51 * Parameters to append to the notify url.
53 * The notify url is passed to the payment processor and the processor uses it for return ping backs or redirection.
57 protected $notifyUrlParameters = array();
60 * Get notify url parameters.
64 public function getNotifyUrlParameters() {
65 return $this->notifyUrlParameters
;
69 * Set notify url parameters.
71 * @param array $notifyUrlParameters
73 public function setNotifyUrlParameters($notifyUrlParameters) {
74 $this->notifyUrlParameters
= $notifyUrlParameters;
78 * How are we getting billing information.
80 * We are trying to completely deprecate these parameters.
82 * FORM - we collect it on the same page
83 * BUTTON - the processor collects it and sends it back to us via some protocol
86 BILLING_MODE_FORM
= 1,
87 BILLING_MODE_BUTTON
= 2,
88 BILLING_MODE_NOTIFY
= 4;
91 * Which payment type(s) are we using?
96 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
99 PAYMENT_TYPE_CREDIT_CARD
= 1,
100 PAYMENT_TYPE_DIRECT_DEBIT
= 2;
103 * Subscription / Recurring payment Status
107 RECURRING_PAYMENT_START
= 'START',
108 RECURRING_PAYMENT_END
= 'END';
110 protected $_paymentProcessor;
113 * Base url of the calling form (offsite processors).
117 protected $baseReturnUrl;
120 * Return url upon success (offsite processors).
124 protected $successUrl;
127 * Return url upon failure (offsite processors).
131 protected $cancelUrl;
134 * The profile configured to show on the billing form.
136 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
137 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
138 * requirements with the configured requirements.
140 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
143 * Note this change would probably include converting 'billing' to a reserved profile.
147 protected $billingProfile;
150 * Set base return path (offsite processors).
152 * This is only useful with an internal civicrm form.
155 * Internal civicrm path.
157 public function setBaseReturnUrl($url) {
158 $this->baseReturnUrl
= $url;
162 * Set success return URL (offsite processors).
164 * This overrides $baseReturnUrl
167 * Full url of site to return browser to upon success.
169 public function setSuccessUrl($url) {
170 $this->successUrl
= $url;
174 * Set cancel return URL (offsite processors).
176 * This overrides $baseReturnUrl
179 * Full url of site to return browser to upon failure.
181 public function setCancelUrl($url) {
182 $this->cancelUrl
= $url;
186 * Set the configured payment profile.
188 * @param int|string $value
190 public function setBillingProfile($value) {
191 $this->billingProfile
= $value;
195 * Opportunity for the payment processor to override the entire form build.
197 * @param CRM_Core_Form $form
200 * Should form building stop at this point?
202 public function buildForm(&$form) {
207 * Log payment notification message to forensic system log.
209 * @todo move to factory class \Civi\Payment\System (or similar)
211 * @param array $params
215 public static function logPaymentNotification($params) {
216 $message = 'payment_notification ';
217 if (!empty($params['processor_name'])) {
218 $message .= 'processor_name=' . $params['processor_name'];
220 if (!empty($params['processor_id'])) {
221 $message .= 'processor_id=' . $params['processor_id'];
224 $log = new CRM_Utils_SystemLogger();
225 $log->alert($message, $_REQUEST);
229 * Check if capability is supported.
231 * Capabilities have a one to one relationship with capability-related functions on this class.
233 * Payment processor classes should over-ride the capability-specific function rather than this one.
235 * @param string $capability
236 * E.g BackOffice, LiveMode, FutureRecurStartDate.
240 public function supports($capability) {
241 $function = 'supports' . ucfirst($capability);
242 if (method_exists($this, $function)) {
243 return $this->$function();
249 * Are back office payments supported.
251 * e.g paypal standard won't permit you to enter a credit card associated
252 * with someone else's login.
253 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
254 * reach a 'stable' point we disable.
258 protected function supportsBackOffice() {
259 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
268 * Can more than one transaction be processed at once?
270 * In general processors that process payment by server to server communication support this while others do not.
272 * In future we are likely to hit an issue where this depends on whether a token already exists.
276 protected function supportsMultipleConcurrentPayments() {
277 if ($this->_paymentProcessor
['billing_mode'] == 4 ||
$this->_paymentProcessor
['payment_type'] != 1) {
286 * Are live payments supported - e.g dummy doesn't support this.
290 protected function supportsLiveMode() {
295 * Are test payments supported.
299 protected function supportsTestMode() {
304 * Should the first payment date be configurable when setting up back office recurring payments.
306 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
310 protected function supportsFutureRecurStartDate() {
315 * Does this processor support cancelling recurring contributions through code.
317 * If the processor returns true it must be possible to take action from within CiviCRM
318 * that will result in no further payments being processed. In the case of token processors (e.g
319 * IATS, eWay) updating the contribution_recur table is probably sufficient.
323 protected function supportsCancelRecurring() {
324 return method_exists(CRM_Utils_System
::getClassName($this), 'cancelSubscription');
328 * Does this processor support pre-approval.
330 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
332 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
333 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
334 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
338 protected function supportsPreApproval() {
343 * Can recurring contributions be set against pledges.
345 * In practice all processors that use the baseIPN function to finish transactions or
346 * call the completetransaction api support this by looking up previous contributions in the
347 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
348 * adding the new payment to the pledge.
350 * However, only enabling for processors it has been tested against.
354 protected function supportsRecurContributionsForPledges() {
359 * Function to action pre-approval if supported
361 * @param array $params
362 * Parameters from the form
364 * This function returns an array which should contain
365 * - pre_approval_parameters (this will be stored on the calling form & available later)
366 * - redirect_url (if set the browser will be redirected to this.
368 public function doPreApproval(&$params) {}
371 * Get any details that may be available to the payment processor due to an approval process having happened.
373 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
376 * @param array $storedDetails
380 public function getPreApprovalDetails($storedDetails) {
385 * Default payment instrument validation.
387 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
388 * Not a static function, because I need to check for payment_type.
390 * @param array $values
391 * @param array $errors
393 public function validatePaymentInstrument($values, &$errors) {
394 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
395 if ($this->_paymentProcessor
['payment_type'] == 1) {
396 CRM_Core_Payment_Form
::validateCreditCard($this->_paymentProcessor
['id'], $values, $errors);
401 * Getter for the payment processor.
403 * The payment processor array is based on the civicrm_payment_processor table entry.
406 * Payment processor array.
408 public function getPaymentProcessor() {
409 return $this->_paymentProcessor
;
413 * Setter for the payment processor.
415 * @param array $processor
417 public function setPaymentProcessor($processor) {
418 $this->_paymentProcessor
= $processor;
422 * Setter for the payment form that wants to use the processor.
426 * @param CRM_Core_Form $paymentForm
428 public function setForm(&$paymentForm) {
429 $this->_paymentForm
= $paymentForm;
433 * Getter for payment form that is using the processor.
435 * @return CRM_Core_Form
438 public function getForm() {
439 return $this->_paymentForm
;
443 * Getter for accessing member vars.
445 * @todo believe this is unused
447 * @param string $name
451 public function getVar($name) {
452 return isset($this->$name) ?
$this->$name : NULL;
456 * Get name for the payment information type.
457 * @todo - use option group + name field (like Omnipay does)
460 public function getPaymentTypeName() {
461 return $this->_paymentProcessor
['payment_type'] == 1 ?
'credit_card' : 'direct_debit';
465 * Get label for the payment information type.
466 * @todo - use option group + labels (like Omnipay does)
469 public function getPaymentTypeLabel() {
470 return $this->_paymentProcessor
['payment_type'] == 1 ?
'Credit Card' : 'Direct Debit';
474 * Get array of fields that should be displayed on the payment form.
475 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
477 * @throws CiviCRM_API3_Exception
479 public function getPaymentFormFields() {
480 if ($this->_paymentProcessor
['billing_mode'] == 4) {
483 return $this->_paymentProcessor
['payment_type'] == 1 ?
$this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
487 * Get an array of the fields that can be edited on the recurring contribution.
489 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
490 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
491 * can be updated from the contribution recur edit screen.
493 * The fields are likely to be a subset of these
496 * - 'frequency_interval',
497 * - 'frequency_unit',
499 * - 'next_sched_contribution_date',
501 * - 'failure_retry_day',
503 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
504 * metadata is not defined in the xml for the field it will cause an error.
506 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
507 * form (UpdateSubscription).
511 public function getEditableRecurringScheduleFields() {
512 if (method_exists($this, 'changeSubscriptionAmount')) {
513 return array('amount');
518 * Get the help text to present on the recurring update page.
520 * This should reflect what can or cannot be edited.
524 public function getRecurringScheduleUpdateHelpText() {
525 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
526 return ts('Updates made using this form will change the recurring contribution information stored in your CiviCRM database, but will NOT be sent to the payment processor. You must enter the same changes using the payment processor web site.');
528 return ts('Use this form to change the amount or number of installments for this recurring contribution. Changes will be automatically sent to the payment processor. You can not change the contribution frequency.');
532 * Get the metadata for all required fields.
536 protected function getMandatoryFields() {
537 $mandatoryFields = array();
538 foreach ($this->getAllFields() as $field_name => $field_spec) {
539 if (!empty($field_spec['is_required'])) {
540 $mandatoryFields[$field_name] = $field_spec;
543 return $mandatoryFields;
547 * Get the metadata of all the fields configured for this processor.
551 protected function getAllFields() {
552 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
553 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
554 return array_merge($paymentFields, $billingFields);
557 * Get array of fields that should be displayed on the payment form for credit cards.
561 protected function getCreditCardFormFields() {
564 'credit_card_number',
566 'credit_card_exp_date',
571 * Get array of fields that should be displayed on the payment form for direct debits.
575 protected function getDirectDebitFormFields() {
578 'bank_account_number',
579 'bank_identification_number',
585 * Return an array of all the details about the fields potentially required for payment fields.
587 * Only those determined by getPaymentFormFields will actually be assigned to the form
592 public function getPaymentFormFieldsMetadata() {
593 //@todo convert credit card type into an option value
594 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::creditCard();
596 'credit_card_number' => array(
597 'htmlType' => 'text',
598 'name' => 'credit_card_number',
599 'title' => ts('Card Number'),
601 'attributes' => array(
604 'autocomplete' => 'off',
605 'class' => 'creditcard',
607 'is_required' => TRUE,
610 'htmlType' => 'text',
612 'title' => ts('Security Code'),
614 'attributes' => array(
617 'autocomplete' => 'off',
619 'is_required' => Civi
::settings()->get('cvv_backoffice_required'),
622 'rule_message' => ts('Please enter a valid value for your card security code. This is usually the last 3-4 digits on the card\'s signature panel.'),
623 'rule_name' => 'integer',
624 'rule_parameters' => NULL,
628 'credit_card_exp_date' => array(
629 'htmlType' => 'date',
630 'name' => 'credit_card_exp_date',
631 'title' => ts('Expiration Date'),
633 'attributes' => CRM_Core_SelectValues
::date('creditCard'),
634 'is_required' => TRUE,
637 'rule_message' => ts('Card expiration date cannot be a past date.'),
638 'rule_name' => 'currentDate',
639 'rule_parameters' => TRUE,
643 'credit_card_type' => array(
644 'htmlType' => 'select',
645 'name' => 'credit_card_type',
646 'title' => ts('Card Type'),
648 'attributes' => $creditCardType,
649 'is_required' => FALSE,
651 'account_holder' => array(
652 'htmlType' => 'text',
653 'name' => 'account_holder',
654 'title' => ts('Account Holder'),
656 'attributes' => array(
659 'autocomplete' => 'on',
661 'is_required' => TRUE,
663 //e.g. IBAN can have maxlength of 34 digits
664 'bank_account_number' => array(
665 'htmlType' => 'text',
666 'name' => 'bank_account_number',
667 'title' => ts('Bank Account Number'),
669 'attributes' => array(
672 'autocomplete' => 'off',
676 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
677 'rule_name' => 'nopunctuation',
678 'rule_parameters' => NULL,
681 'is_required' => TRUE,
683 //e.g. SWIFT-BIC can have maxlength of 11 digits
684 'bank_identification_number' => array(
685 'htmlType' => 'text',
686 'name' => 'bank_identification_number',
687 'title' => ts('Bank Identification Number'),
689 'attributes' => array(
692 'autocomplete' => 'off',
694 'is_required' => TRUE,
697 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
698 'rule_name' => 'nopunctuation',
699 'rule_parameters' => NULL,
703 'bank_name' => array(
704 'htmlType' => 'text',
705 'name' => 'bank_name',
706 'title' => ts('Bank Name'),
708 'attributes' => array(
711 'autocomplete' => 'off',
713 'is_required' => TRUE,
720 * Get billing fields required for this processor.
722 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
725 * @param int $billingLocationID
729 public function getBillingAddressFields($billingLocationID = NULL) {
730 if (!$billingLocationID) {
731 // Note that although the billing id is passed around the forms the idea that it would be anything other than
732 // the result of the function below doesn't seem to have eventuated.
733 // So taking this as a param is possibly something to be removed in favour of the standard default.
734 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
736 if ($this->_paymentProcessor
['billing_mode'] != 1 && $this->_paymentProcessor
['billing_mode'] != 3) {
740 'first_name' => 'billing_first_name',
741 'middle_name' => 'billing_middle_name',
742 'last_name' => 'billing_last_name',
743 'street_address' => "billing_street_address-{$billingLocationID}",
744 'city' => "billing_city-{$billingLocationID}",
745 'country' => "billing_country_id-{$billingLocationID}",
746 'state_province' => "billing_state_province_id-{$billingLocationID}",
747 'postal_code' => "billing_postal_code-{$billingLocationID}",
752 * Get form metadata for billing address fields.
754 * @param int $billingLocationID
757 * Array of metadata for address fields.
759 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
760 if (!$billingLocationID) {
761 // Note that although the billing id is passed around the forms the idea that it would be anything other than
762 // the result of the function below doesn't seem to have eventuated.
763 // So taking this as a param is possibly something to be removed in favour of the standard default.
764 $billingLocationID = CRM_Core_BAO_LocationType
::getBilling();
767 $metadata['billing_first_name'] = array(
768 'htmlType' => 'text',
769 'name' => 'billing_first_name',
770 'title' => ts('Billing First Name'),
772 'attributes' => array(
775 'autocomplete' => 'off',
777 'is_required' => TRUE,
780 $metadata['billing_middle_name'] = array(
781 'htmlType' => 'text',
782 'name' => 'billing_middle_name',
783 'title' => ts('Billing Middle Name'),
785 'attributes' => array(
788 'autocomplete' => 'off',
790 'is_required' => FALSE,
793 $metadata['billing_last_name'] = array(
794 'htmlType' => 'text',
795 'name' => 'billing_last_name',
796 'title' => ts('Billing Last Name'),
798 'attributes' => array(
801 'autocomplete' => 'off',
803 'is_required' => TRUE,
806 $metadata["billing_street_address-{$billingLocationID}"] = array(
807 'htmlType' => 'text',
808 'name' => "billing_street_address-{$billingLocationID}",
809 'title' => ts('Street Address'),
811 'attributes' => array(
814 'autocomplete' => 'off',
816 'is_required' => TRUE,
819 $metadata["billing_city-{$billingLocationID}"] = array(
820 'htmlType' => 'text',
821 'name' => "billing_city-{$billingLocationID}",
822 'title' => ts('City'),
824 'attributes' => array(
827 'autocomplete' => 'off',
829 'is_required' => TRUE,
832 $metadata["billing_state_province_id-{$billingLocationID}"] = array(
833 'htmlType' => 'chainSelect',
834 'title' => ts('State/Province'),
835 'name' => "billing_state_province_id-{$billingLocationID}",
837 'is_required' => TRUE,
840 $metadata["billing_postal_code-{$billingLocationID}"] = array(
841 'htmlType' => 'text',
842 'name' => "billing_postal_code-{$billingLocationID}",
843 'title' => ts('Postal Code'),
845 'attributes' => array(
848 'autocomplete' => 'off',
850 'is_required' => TRUE,
853 $metadata["billing_country_id-{$billingLocationID}"] = array(
854 'htmlType' => 'select',
855 'name' => "billing_country_id-{$billingLocationID}",
856 'title' => ts('Country'),
858 'attributes' => array(
859 '' => ts('- select -'),
860 ) + CRM_Core_PseudoConstant
::country(),
861 'is_required' => TRUE,
867 * Get base url dependent on component.
869 * (or preferably set it using the setter function).
873 protected function getBaseReturnUrl() {
874 if ($this->baseReturnUrl
) {
875 return $this->baseReturnUrl
;
877 if ($this->_component
== 'event') {
878 $baseURL = 'civicrm/event/register';
881 $baseURL = 'civicrm/contribute/transact';
887 * Get url to return to after cancelled or failed transaction.
889 * @param string $qfKey
890 * @param int $participantID
892 * @return string cancel url
894 public function getCancelUrl($qfKey, $participantID) {
895 if (isset($this->cancelUrl
)) {
896 return $this->cancelUrl
;
899 if ($this->_component
== 'event') {
900 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
903 'participantId' => $participantID,
909 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
910 '_qf_Main_display' => 1,
919 * Get URL to return the browser to on success.
925 protected function getReturnSuccessUrl($qfKey) {
926 if (isset($this->successUrl
)) {
927 return $this->successUrl
;
930 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
931 '_qf_ThankYou_display' => 1,
939 * Get URL to return the browser to on failure.
942 * @param int $participantID
943 * @param int $eventID
946 * URL for a failing transactor to be redirected to.
948 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
949 if (isset($this->cancelUrl
)) {
950 return $this->cancelUrl
;
953 $test = $this->_is_test ?
'&action=preview' : '';
954 if ($this->_component
== "event") {
955 return CRM_Utils_System
::url('civicrm/event/register',
956 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
961 return CRM_Utils_System
::url('civicrm/contribute/transact',
962 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
969 * Get URl for when the back button is pressed.
975 protected function getGoBackUrl($qfKey) {
976 return CRM_Utils_System
::url($this->getBaseReturnUrl(), array(
977 '_qf_Confirm_display' => 'true',
985 * Get the notify (aka ipn, web hook or silent post) url.
987 * If there is no '.' in it we assume that we are dealing with localhost or
988 * similar and it is unreachable from the web & hence invalid.
991 * URL to notify outcome of transaction.
993 protected function getNotifyUrl() {
994 $url = CRM_Utils_System
::url(
995 'civicrm/payment/ipn/' . $this->_paymentProcessor
['id'],
996 $this->getNotifyUrlParameters(),
1001 return (stristr($url, '.')) ?
$url : '';
1005 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1007 * Does a server to server payment transaction.
1009 * @param array $params
1010 * Assoc array of input parameters for this transaction.
1013 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1015 protected function doDirectPayment(&$params) {
1020 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
1022 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
1025 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
1026 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
1027 * doTransferCheckout would not traditionally come back.
1029 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
1032 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
1033 * return Error objects
1035 * @param array $params
1037 * @param string $component
1042 * @throws \Civi\Payment\Exception\PaymentProcessorException
1044 public function doPayment(&$params, $component = 'contribute') {
1045 $this->_component
= $component;
1046 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1048 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1049 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1050 // have an example of that at the mome.
1051 if ($params['amount'] == 0) {
1052 $result['payment_status_id'] = array_search('Completed', $statuses);
1056 if ($this->_paymentProcessor
['billing_mode'] == 4) {
1057 $result = $this->doTransferCheckout($params, $component);
1058 if (is_array($result) && !isset($result['payment_status_id'])) {
1059 $result['payment_status_id'] = array_search('Pending', $statuses);
1063 $result = $this->doDirectPayment($params, $component);
1064 if (is_array($result) && !isset($result['payment_status_id'])) {
1065 if (!empty($params['is_recur'])) {
1066 // See comment block.
1067 $result['payment_status_id'] = array_search('Pending', $statuses);
1070 $result['payment_status_id'] = array_search('Completed', $statuses);
1074 if (is_a($result, 'CRM_Core_Error')) {
1075 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
1081 * Query payment processor for details about a transaction.
1083 * @param array $params
1084 * Array of parameters containing one of:
1085 * - trxn_id Id of an individual transaction.
1086 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1089 * Extra parameters retrieved.
1090 * Any parameters retrievable through this should be documented in the function comments at
1091 * CRM_Core_Payment::doQuery. Currently:
1092 * - fee_amount Amount of fee paid
1094 public function doQuery($params) {
1099 * This function checks to see if we have the right config values.
1102 * the error message if any
1104 abstract protected function checkConfig();
1107 * Redirect for paypal.
1109 * @todo move to paypal class or remove
1111 * @param $paymentProcessor
1115 public static function paypalRedirect(&$paymentProcessor) {
1116 if (!$paymentProcessor) {
1120 if (isset($_GET['payment_date']) &&
1121 isset($_GET['merchant_return_link']) &&
1122 CRM_Utils_Array
::value('payment_status', $_GET) == 'Completed' &&
1123 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1132 * Handle incoming payment notification.
1134 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1136 * @todo move to0 \Civi\Payment\System factory method
1137 * Page callback for civicrm/payment/ipn
1139 public static function handleIPN() {
1140 self
::handlePaymentMethod(
1141 'PaymentNotification',
1143 'processor_name' => @$_GET['processor_name'],
1144 'processor_id' => @$_GET['processor_id'],
1145 'mode' => @$_GET['mode'],
1148 CRM_Utils_System
::civiExit();
1152 * Payment callback handler.
1154 * The processor_name or processor_id is passed in.
1155 * Note that processor_id is more reliable as one site may have more than one instance of a
1156 * processor & ideally the processor will be validating the results
1157 * Load requested payment processor and call that processor's handle<$method> method
1159 * @todo move to \Civi\Payment\System factory method
1161 * @param string $method
1162 * 'PaymentNotification' or 'PaymentCron'
1163 * @param array $params
1165 * @throws \CRM_Core_Exception
1166 * @throws \Exception
1168 public static function handlePaymentMethod($method, $params = array()) {
1169 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1170 $q = explode('/', CRM_Utils_Array
::value(CRM_Core_Config
::singleton()->userFrameworkURLVar
, $_GET, ''));
1171 $lastParam = array_pop($q);
1172 if (is_numeric($lastParam)) {
1173 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1176 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1180 self
::logPaymentNotification($params);
1182 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1183 FROM civicrm_payment_processor_type ppt
1184 INNER JOIN civicrm_payment_processor pp
1185 ON pp.payment_processor_type_id = ppt.id
1188 if (isset($params['processor_id'])) {
1189 $sql .= " WHERE pp.id = %2";
1190 $args[2] = array($params['processor_id'], 'Integer');
1191 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
1194 // This is called when processor_name is passed - passing processor_id instead is recommended.
1195 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1197 (CRM_Utils_Array
::value('mode', $params) == 'test') ?
1 : 0,
1200 $args[2] = array($params['processor_name'], 'String');
1201 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
1204 $dao = CRM_Core_DAO
::executeQuery($sql, $args);
1206 // Check whether we found anything at all.
1208 CRM_Core_Error
::fatal($notFound);
1211 $method = 'handle' . $method;
1212 $extension_instance_found = FALSE;
1214 // In all likelihood, we'll just end up with the one instance returned here. But it's
1215 // possible we may get more. Hence, iterate through all instances ..
1217 while ($dao->fetch()) {
1218 // Check pp is extension - is this still required - surely the singleton below handles it.
1219 $ext = CRM_Extension_System
::singleton()->getMapper();
1220 if ($ext->isExtensionKey($dao->class_name
)) {
1221 $paymentClass = $ext->keyToClass($dao->class_name
, 'payment');
1222 require_once $ext->classToPath($paymentClass);
1225 $processorInstance = System
::singleton()->getById($dao->processor_id
);
1227 // Should never be empty - we already established this processor_id exists and is active.
1228 if (empty($processorInstance)) {
1232 // Does PP implement this method, and can we call it?
1233 if (!method_exists($processorInstance, $method) ||
1234 !is_callable(array($processorInstance, $method))
1236 // on the off chance there is a double implementation of this processor we should keep looking for another
1237 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1241 // Everything, it seems, is ok - execute pp callback handler
1242 $processorInstance->$method();
1243 $extension_instance_found = TRUE;
1246 if (!$extension_instance_found) {
1247 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1248 "%2 method is unsupported in legacy payment processors.";
1249 CRM_Core_Error
::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
1254 * Check whether a method is present ( & supported ) by the payment processor object.
1256 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1258 * @param string $method
1259 * Method to check for.
1263 public function isSupported($method) {
1264 return method_exists(CRM_Utils_System
::getClassName($this), $method);
1268 * Some processors replace the form submit button with their own.
1270 * Returning false here will leave the button off front end forms.
1272 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1274 public function isSuppressSubmitButtons() {
1279 * Checks to see if invoice_id already exists in db.
1281 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1282 * it is better to standardise to being here.
1284 * @param int $invoiceId The ID to check.
1286 * @param null $contributionID
1287 * If a contribution exists pass in the contribution ID.
1290 * True if invoice ID otherwise exists, else false
1292 protected function checkDupe($invoiceId, $contributionID = NULL) {
1293 $contribution = new CRM_Contribute_DAO_Contribution();
1294 $contribution->invoice_id
= $invoiceId;
1295 if ($contributionID) {
1296 $contribution->whereAdd("id <> $contributionID");
1298 return $contribution->find();
1302 * Get url for users to manage this recurring contribution for this processor.
1304 * @param int $entityID
1305 * @param null $entity
1306 * @param string $action
1310 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1314 $url = 'civicrm/contribute/unsubscribe';
1318 //in notify mode don't return the update billing url
1319 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
1322 $url = 'civicrm/contribute/updatebilling';
1326 $url = 'civicrm/contribute/updaterecur';
1330 $userId = CRM_Core_Session
::singleton()->get('userID');
1332 $checksumValue = '';
1335 // Find related Contact
1339 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1343 case 'contribution':
1344 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1345 $entityArg = 'coid';
1350 SELECT con.contact_id
1351 FROM civicrm_contribution_recur rec
1352 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1355 $contactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
1356 $entityArg = 'crid';
1361 // Add entity arguments
1362 if ($entityArg != '') {
1363 // Add checksum argument
1364 if ($contactID != 0 && $userId != $contactID) {
1365 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
1367 return CRM_Utils_System
::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1371 if ($this->isSupported('accountLoginURL')) {
1372 return $this->accountLoginURL();
1376 return isset($this->_paymentProcessor
['url_recur']) ?
$this->_paymentProcessor
['url_recur'] : '';
1380 * Get description of payment to pass to processor.
1382 * This is often what people see in the interface so we want to get
1383 * as much unique information in as possible within the field length (& presumably the early part of the field)
1385 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1386 * having field names to clarify
1388 * @param array $params
1389 * @param int $length
1393 protected function getPaymentDescription($params, $length = 24) {
1394 $parts = array('contactID', 'contributionID', 'description', 'billing_first_name', 'billing_last_name');
1395 $validParts = array();
1396 if (isset($params['description'])) {
1397 $uninformativeStrings = array(ts('Online Event Registration: '), ts('Online Contribution: '));
1398 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1400 foreach ($parts as $part) {
1401 if ((!empty($params[$part]))) {
1402 $validParts[] = $params[$part];
1405 return substr(implode('-', $validParts), 0, $length);
1409 * Checks if backoffice recurring edit is allowed
1413 public function supportsEditRecurringContribution() {
1418 * Should a receipt be sent out for a pending payment.
1420 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1422 public function isSendReceiptForPending() {