3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Class CRM_Core_Payment_BaseIPN.
15 class CRM_Core_Payment_BaseIPN
{
17 public static $_now = NULL;
20 * Input parameters from payment processor. Store these so that
21 * the code does not need to keep retrieving from the http request
24 protected $_inputParameters = [];
27 * Only used by AuthorizeNetIPN.
33 protected $_isRecurring = FALSE;
36 * Only used by AuthorizeNetIPN.
42 protected $_isFirstOrLastRecurringPayment = FALSE;
47 public function __construct() {
48 self
::$_now = date('YmdHis');
52 * Store input array on the class.
54 * @param array $parameters
56 * @throws CRM_Core_Exception
58 public function setInputParameters($parameters) {
59 if (!is_array($parameters)) {
60 throw new CRM_Core_Exception('Invalid input parameters');
62 $this->_inputParameters
= $parameters;
66 * Validate incoming data.
68 * This function is intended to ensure that incoming data matches
69 * It provides a form of pseudo-authentication - by checking the calling fn already knows
70 * the correct contact id & contribution id (this can be problematic when that has changed in
71 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
72 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
73 * and didn't update your IPN URL.
76 * Interpreted values from the values returned through the IPN.
78 * More interpreted values (ids) from the values returned through the IPN.
79 * @param array $objects
80 * An empty array that will be populated with loaded object.
81 * @param bool $required
82 * Boolean Return FALSE if the relevant objects don't exist.
83 * @param int $paymentProcessorID
84 * Id of the payment processor ID in use.
88 public function validateData($input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
90 // Check if the contribution exists
91 // make sure contribution exists and is valid
92 $contribution = new CRM_Contribute_BAO_Contribution();
93 $contribution->id
= $ids['contribution'];
94 if (!$contribution->find(TRUE)) {
95 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
96 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
100 // make sure contact exists and is valid
101 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
102 $contact = new CRM_Contact_BAO_Contact();
103 $contact->id
= $contribution->contact_id
;
104 $contact->find(TRUE);
105 if ($contact->id
!= $ids['contact']) {
106 // If the ids do not match then it is possible the contact id in the IPN has been merged into another contact which is why we use the contact_id from the contribution
107 CRM_Core_Error
::debug_log_message("Contact ID in IPN {$ids['contact']} not found but contact_id found in contribution {$contribution->contact_id} used instead");
108 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
109 $ids['contact'] = $contribution->contact_id
;
112 if (!empty($ids['contributionRecur'])) {
113 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
114 $contributionRecur->id
= $ids['contributionRecur'];
115 if (!$contributionRecur->find(TRUE)) {
116 CRM_Core_Error
::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
117 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
122 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
123 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
125 $objects['contact'] = &$contact;
126 $objects['contribution'] = &$contribution;
128 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
129 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
130 // We don't need to worry if about removing contribution page id as it will be set later in
131 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
132 unset($ids['contributionPage']);
135 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
138 //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
139 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
140 //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
141 if (isset($objects['contributionRecur'])) {
142 $objects['first_contribution'] = $objects['contribution'];
148 * Load objects related to contribution.
150 * @input array information from Payment processor
152 * @param array $input
154 * @param array $objects
155 * @param bool $required
156 * @param int $paymentProcessorID
157 * @param array $error_handling
161 public function loadObjects($input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
162 if (empty($error_handling)) {
163 // default options are that we log an error & echo it out
164 // note that we should refactor this error handling into error code @ some point
165 // but for now setting up enough separation so we can do unit tests
171 $ids['paymentProcessor'] = $paymentProcessorID;
172 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
173 $contribution = &$objects['contribution'];
176 //legacy support - functions are 'used' to be able to pass in a DAO
177 $contribution = new CRM_Contribute_BAO_Contribution();
178 $contribution->id
= $ids['contribution'] ??
NULL;
179 $contribution->find(TRUE);
180 $objects['contribution'] = &$contribution;
183 $success = $contribution->loadRelatedObjects($input, $ids);
184 if ($required && empty($contribution->_relatedObjects
['paymentProcessor'])) {
185 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id
);
188 catch (Exception
$e) {
190 if (!empty($error_handling['log_error'])) {
191 CRM_Core_Error
::debug_log_message($e->getMessage());
193 if (!empty($error_handling['echo_error'])) {
194 echo $e->getMessage();
196 if (!empty($error_handling['return_error'])) {
199 'error_message' => ($e->getMessage()),
203 $objects = array_merge($objects, $contribution->_relatedObjects
);
208 * Set contribution to failed.
210 * @param array $objects
211 * @param object $transaction
212 * @param array $input
215 * @throws \CiviCRM_API3_Exception
217 public function failed(&$objects, &$transaction, $input = []) {
218 $contribution = &$objects['contribution'];
220 if (!empty($objects['membership'])) {
221 $memberships = &$objects['membership'];
222 if (is_numeric($memberships)) {
223 $memberships = [$objects['membership']];
227 $addLineItems = FALSE;
228 if (empty($contribution->id
)) {
229 $addLineItems = TRUE;
231 $participant = &$objects['participant'];
234 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
235 'labelColumn' => 'name',
238 $contribution->contribution_status_id
= $contributionStatuses['Failed'];
239 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
240 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
241 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
242 $contribution->save();
244 // Add line items for recurring payments.
245 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
246 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
249 //add new soft credit against current contribution id and
250 //copy initial contribution custom fields for recurring contributions
251 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
252 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
253 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
256 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
257 if (!empty($memberships)) {
258 foreach ($memberships as $membership) {
259 // @fixme Should we cancel only Pending memberships? per cancelled()
260 $this->cancelMembership($membership, $membership->status_id
, FALSE);
265 $this->cancelParticipant($participant->id
);
269 $transaction->commit();
270 Civi
::log()->debug("Setting contribution status to Failed");
275 * Handled pending contribution status.
279 * @param array $objects
280 * @param object $transaction
284 public function pending(&$objects, &$transaction) {
285 CRM_Core_Error
::deprecatedFunctionWarning('This function will be removed at some point');
286 $transaction->commit();
287 Civi
::log()->debug('Returning since contribution status is Pending');
288 echo 'Success: Returning since contribution status is pending<p>';
293 * Process cancelled payment outcome.
295 * @param array $objects
296 * @param CRM_Core_Transaction $transaction
297 * @param array $input
300 * @throws \CiviCRM_API3_Exception
302 public function cancelled(&$objects, &$transaction, $input = []) {
303 $contribution = &$objects['contribution'];
305 if (!empty($objects['membership'])) {
306 $memberships = &$objects['membership'];
307 if (is_numeric($memberships)) {
308 $memberships = [$objects['membership']];
312 $addLineItems = FALSE;
313 if (empty($contribution->id
)) {
314 $addLineItems = TRUE;
316 $participant = &$objects['participant'];
319 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
320 'labelColumn' => 'name',
323 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
324 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
325 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
326 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
327 $contribution->cancel_date
= self
::$_now;
328 $contribution->cancel_reason
= $input['reasonCode'] ??
NULL;
329 $contribution->save();
331 // Add line items for recurring payments.
332 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
333 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
336 //add new soft credit against current $contribution and
337 //copy initial contribution custom fields for recurring contributions
338 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
339 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
340 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
343 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
344 if (!empty($memberships)) {
345 foreach ($memberships as $membership) {
347 $this->cancelMembership($membership, $membership->status_id
);
353 $this->cancelParticipant($participant->id
);
356 $transaction->commit();
357 Civi
::log()->debug("Setting contribution status to Cancelled");
362 * Rollback unhandled outcomes.
366 * @param array $objects
367 * @param CRM_Core_Transaction $transaction
371 public function unhandled(&$objects, &$transaction) {
372 CRM_Core_Error
::deprecatedFunctionWarning('This function will be removed at some point');
373 $transaction->rollback();
374 Civi
::log()->debug('Returning since contribution status is not handled');
375 echo 'Failure: contribution status is not handled<p>';
380 * Logic to cancel a participant record when the related contribution changes to failed/cancelled.
381 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
383 * @param $participantID
385 * @throws \CiviCRM_API3_Exception
387 private function cancelParticipant($participantID) {
388 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
389 $participantParams['id'] = $participantID;
390 $participantParams['status_id'] = 'Cancelled';
391 civicrm_api3('Participant', 'create', $participantParams);
395 * Logic to cancel a membership record when the related contribution changes to failed/cancelled.
396 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
397 * @param \CRM_Member_BAO_Membership $membership
398 * @param int $membershipStatusID
399 * @param boolean $onlyCancelPendingMembership
400 * Do we only cancel pending memberships? OR memberships in any status? (see CRM-18688)
401 * @fixme Historically failed() cancelled membership in any status, cancelled() cancelled only pending memberships so we retain that behaviour for now.
404 private function cancelMembership($membership, $membershipStatusID, $onlyCancelPendingMembership = TRUE) {
405 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
406 // Cancel only Pending memberships
407 $pendingMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
408 if (($membershipStatusID == $pendingMembershipStatusId) ||
($onlyCancelPendingMembership == FALSE)) {
409 $cancelledMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Cancelled');
411 $membership->status_id
= $cancelledMembershipStatusId;
414 $params = ['status_id' => $cancelledMembershipStatusId];
415 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
417 // @todo Convert the above to API
418 // $membershipParams = [
419 // 'id' => $membership->id,
420 // 'status_id' => $cancelledMembershipStatusId,
422 // civicrm_api3('Membership', 'create', $membershipParams);
423 // CRM_Member_BAO_Membership::updateRelatedMemberships($membershipParams['id'], ['status_id' => $cancelledMembershipStatusId]);
431 * Jumbled up function.
433 * The purpose of this function is to transition a pending transaction to Completed including updating any
436 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
437 * updating related entities.
439 * It is recommended to avoid calling this function directly and call the api functions:
440 * - contribution.completetransaction
441 * - contribution.repeattransaction
443 * These functions are the focus of testing efforts and more accurately reflect the division of roles
444 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
445 * and from there it should be possible to pass off transaction management.)
447 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
448 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
450 * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo
451 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
452 * a shared function that updates related components.
454 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
455 * IPN class is better accessed through the api which de-jumbles it a bit.
457 * e.g the payment class can have a function like (based on Omnipay extension):
459 * public function handlePaymentNotification() {
460 * $response = $this->getValidatedOutcome();
461 * if ($response->isSuccessful()) {
463 * // @todo check if it is a repeat transaction & call repeattransaction instead.
464 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
466 * catch (CiviCRM_API3_Exception $e) {
467 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
468 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
469 * have occurred. Please check your receipt is correct');
470 * $this->redirectOrExit('success');
472 * elseif ($this->transaction_id) {
473 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
477 * @param array $input
479 * @param array $objects
480 * @param CRM_Core_Transaction $transaction
482 * @throws \CRM_Core_Exception
483 * @throws \CiviCRM_API3_Exception
485 public function completeTransaction(&$input, &$ids, &$objects, $transaction = NULL) {
486 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $objects, $transaction);
491 * Get site billing ID.
497 public function getBillingID(&$ids) {
498 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_LocationType::getBilling()');
499 $ids['billing'] = CRM_Core_BAO_LocationType
::getBilling();
500 if (!$ids['billing']) {
501 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
502 echo "Failure: Could not find billing location type<p>";
511 * @todo confirm this function is not being used by any payment processor outside core & remove.
513 * Note that the compose message part has been moved to contribution
514 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
516 * @param array $input
517 * Incoming data from Payment processor.
519 * Related object IDs.
520 * @param array $objects
522 * @throws \CiviCRM_API3_Exception
524 public function sendMail($input, $ids, $objects) {
525 CRM_Core_Error
::deprecatedFunctionWarning('this should be done via completetransaction api');
526 civicrm_api3('Contribution', 'sendconfirmation', [
527 'id' => $objects['contribution']->id
,