3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 +--------------------------------------------------------------------+
29 * Class CRM_Core_Payment_BaseIPN.
31 class CRM_Core_Payment_BaseIPN
{
33 public static $_now = NULL;
36 * Input parameters from payment processor. Store these so that
37 * the code does not need to keep retrieving from the http request
40 protected $_inputParameters = [];
43 * Only used by AuthorizeNetIPN.
49 protected $_isRecurring = FALSE;
52 * Only used by AuthorizeNetIPN.
58 protected $_isFirstOrLastRecurringPayment = FALSE;
63 public function __construct() {
64 self
::$_now = date('YmdHis');
68 * Store input array on the class.
70 * @param array $parameters
72 * @throws CRM_Core_Exception
74 public function setInputParameters($parameters) {
75 if (!is_array($parameters)) {
76 throw new CRM_Core_Exception('Invalid input parameters');
78 $this->_inputParameters
= $parameters;
82 * Validate incoming data.
84 * This function is intended to ensure that incoming data matches
85 * It provides a form of pseudo-authentication - by checking the calling fn already knows
86 * the correct contact id & contribution id (this can be problematic when that has changed in
87 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
88 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
89 * and didn't update your IPN URL.
92 * Interpreted values from the values returned through the IPN.
94 * More interpreted values (ids) from the values returned through the IPN.
95 * @param array $objects
96 * An empty array that will be populated with loaded object.
97 * @param bool $required
98 * Boolean Return FALSE if the relevant objects don't exist.
99 * @param int $paymentProcessorID
100 * Id of the payment processor ID in use.
104 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
106 // make sure contact exists and is valid
107 $contact = new CRM_Contact_BAO_Contact();
108 $contact->id
= $ids['contact'];
109 if (!$contact->find(TRUE)) {
110 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
111 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
115 // make sure contribution exists and is valid
116 $contribution = new CRM_Contribute_BAO_Contribution();
117 $contribution->id
= $ids['contribution'];
118 if (!$contribution->find(TRUE)) {
119 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
120 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
123 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
124 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
126 $objects['contact'] = &$contact;
127 $objects['contribution'] = &$contribution;
129 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
130 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
131 // We don't need to worry if about removing contribution page id as it will be set later in
132 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
133 unset($ids['contributionPage']);
136 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
139 //the process is that the loadObjects is kind of hacked by loading the objects for the original contribution and then somewhat inconsistently using them for the
140 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
141 //we don't want to fix this in the payment processor classes because we would have to fix all of them - so better to fix somewhere central
142 if (isset($objects['contributionRecur'])) {
143 $objects['first_contribution'] = $objects['contribution'];
149 * Load objects related to contribution.
151 * @input array information from Payment processor
153 * @param array $input
155 * @param array $objects
156 * @param bool $required
157 * @param int $paymentProcessorID
158 * @param array $error_handling
162 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
163 if (empty($error_handling)) {
164 // default options are that we log an error & echo it out
165 // note that we should refactor this error handling into error code @ some point
166 // but for now setting up enough separation so we can do unit tests
172 $ids['paymentProcessor'] = $paymentProcessorID;
173 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
174 $contribution = &$objects['contribution'];
177 //legacy support - functions are 'used' to be able to pass in a DAO
178 $contribution = new CRM_Contribute_BAO_Contribution();
179 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
180 $contribution->find(TRUE);
181 $objects['contribution'] = &$contribution;
184 $success = $contribution->loadRelatedObjects($input, $ids);
185 if ($required && empty($contribution->_relatedObjects
['paymentProcessor'])) {
186 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id
);
189 catch (Exception
$e) {
191 if (!empty($error_handling['log_error'])) {
192 CRM_Core_Error
::debug_log_message($e->getMessage());
194 if (!empty($error_handling['echo_error'])) {
195 echo $e->getMessage();
197 if (!empty($error_handling['return_error'])) {
200 'error_message' => ($e->getMessage()),
204 $objects = array_merge($objects, $contribution->_relatedObjects
);
209 * Set contribution to failed.
211 * @param array $objects
212 * @param object $transaction
213 * @param array $input
216 * @throws \CiviCRM_API3_Exception
218 public function failed(&$objects, &$transaction, $input = []) {
219 $contribution = &$objects['contribution'];
221 if (!empty($objects['membership'])) {
222 $memberships = &$objects['membership'];
223 if (is_numeric($memberships)) {
224 $memberships = [$objects['membership']];
228 $addLineItems = FALSE;
229 if (empty($contribution->id
)) {
230 $addLineItems = TRUE;
232 $participant = &$objects['participant'];
235 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
236 'labelColumn' => 'name',
239 $contribution->contribution_status_id
= $contributionStatuses['Failed'];
240 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
241 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
242 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
243 $contribution->save();
245 // Add line items for recurring payments.
246 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
247 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
250 //add new soft credit against current contribution id and
251 //copy initial contribution custom fields for recurring contributions
252 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
253 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
254 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
257 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
258 if (!empty($memberships)) {
259 // if transaction is failed then set "Cancelled" as membership status
260 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', [
261 'labelColumn' => 'name',
264 // @fixme Should we cancel only Pending memberships? per cancelled()
265 foreach ($memberships as $membership) {
267 $membership->status_id
= $membershipStatuses['Cancelled'];
270 //update related Memberships.
271 $params = ['status_id' => $membershipStatuses['Cancelled']];
272 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
278 $participantParams['id'] = $participant->id
;
279 $participantParams['status_id'] = 'Cancelled';
280 civicrm_api3('Participant', 'create', $participantParams);
284 $transaction->commit();
285 Civi
::log()->debug("Setting contribution status to Failed");
290 * Handled pending contribution status.
292 * @param array $objects
293 * @param object $transaction
297 public function pending(&$objects, &$transaction) {
298 $transaction->commit();
299 Civi
::log()->debug("Returning since contribution status is Pending");
300 echo "Success: Returning since contribution status is pending<p>";
305 * Process cancelled payment outcome.
307 * @param array $objects
308 * @param CRM_Core_Transaction $transaction
309 * @param array $input
312 * @throws \CiviCRM_API3_Exception
314 public function cancelled(&$objects, &$transaction, $input = []) {
315 $contribution = &$objects['contribution'];
317 if (!empty($objects['membership'])) {
318 $memberships = &$objects['membership'];
319 if (is_numeric($memberships)) {
320 $memberships = [$objects['membership']];
324 $addLineItems = FALSE;
325 if (empty($contribution->id
)) {
326 $addLineItems = TRUE;
328 $participant = &$objects['participant'];
331 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
332 'labelColumn' => 'name',
335 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
336 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
337 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
338 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
339 $contribution->cancel_date
= self
::$_now;
340 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
341 $contribution->save();
343 // Add line items for recurring payments.
344 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
345 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
348 //add new soft credit against current $contribution and
349 //copy initial contribution custom fields for recurring contributions
350 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
351 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
352 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
355 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
356 if (!empty($memberships)) {
357 // if transaction is failed then set "Cancelled" as membership status
358 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', [
359 'labelColumn' => 'name',
362 // Cancel only Pending memberships
364 $pendingStatusId = $membershipStatuses['Pending'];
365 foreach ($memberships as $membership) {
366 if ($membership && ($membership->status_id
== $pendingStatusId)) {
367 $membership->status_id
= $membershipStatuses['Cancelled'];
370 //update related Memberships.
371 $params = ['status_id' => $membershipStatuses['Cancelled']];
372 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
378 $participantParams['id'] = $participant->id
;
379 $participantParams['status_id'] = 'Cancelled';
380 civicrm_api3('Participant', 'create', $participantParams);
383 $transaction->commit();
384 Civi
::log()->debug("Setting contribution status to Cancelled");
389 * Rollback unhandled outcomes.
391 * @param array $objects
392 * @param CRM_Core_Transaction $transaction
396 public function unhandled(&$objects, &$transaction) {
397 $transaction->rollback();
398 Civi
::log()->debug("Returning since contribution status is not handled");
399 echo "Failure: contribution status is not handled<p>";
406 * Jumbled up function.
408 * The purpose of this function is to transition a pending transaction to Completed including updating any
411 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
412 * updating related entities.
414 * It is recommended to avoid calling this function directly and call the api functions:
415 * - contribution.completetransaction
416 * - contribution.repeattransaction
418 * These functions are the focus of testing efforts and more accurately reflect the division of roles
419 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
420 * and from there it should be possible to pass off transaction management.)
422 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
423 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
425 * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo
426 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
427 * a shared function that updates related components.
429 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
430 * IPN class is better accessed through the api which de-jumbles it a bit.
432 * e.g the payment class can have a function like (based on Omnipay extension):
434 * public function handlePaymentNotification() {
435 * $response = $this->getValidatedOutcome();
436 * if ($response->isSuccessful()) {
438 * // @todo check if it is a repeat transaction & call repeattransaction instead.
439 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
441 * catch (CiviCRM_API3_Exception $e) {
442 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
443 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
444 * have occurred. Please check your receipt is correct');
445 * $this->redirectOrExit('success');
447 * elseif ($this->transaction_id) {
448 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
452 * @param array $input
454 * @param array $objects
455 * @param CRM_Core_Transaction $transaction
458 * @throws \CRM_Core_Exception
459 * @throws \CiviCRM_API3_Exception
461 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
462 $contribution = &$objects['contribution'];
464 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $objects, $transaction, $recur, $contribution);
468 * Get site billing ID.
474 public function getBillingID(&$ids) {
475 $ids['billing'] = CRM_Core_BAO_LocationType
::getBilling();
476 if (!$ids['billing']) {
477 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
478 echo "Failure: Could not find billing location type<p>";
487 * @todo confirm this function is not being used by any payment processor outside core & remove.
489 * Note that the compose message part has been moved to contribution
490 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
492 * @param array $input
493 * Incoming data from Payment processor.
495 * Related object IDs.
496 * @param array $objects
497 * @param array $values
498 * Values related to objects that have already been loaded.
500 * Is it part of a recurring contribution.
501 * @param bool $returnMessageText
502 * Should text be returned instead of sent. This.
503 * is because the function is also used to generate pdfs
506 * @throws \CRM_Core_Exception
507 * @throws \CiviCRM_API3_Exception
509 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
510 return CRM_Contribute_BAO_Contribution
::sendMail($input, $ids, $objects['contribution']->id
, $values,