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 throw new CRM_Core_Exception('Failure: Could not find contribution record for ' . (int) $contribution->id
, NULL, ['context' => "Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE)]);
98 // make sure contact exists and is valid
99 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
100 $contact = new CRM_Contact_BAO_Contact();
101 $contact->id
= $contribution->contact_id
;
102 $contact->find(TRUE);
103 if ($contact->id
!= $ids['contact']) {
104 // 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
105 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");
106 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
107 $ids['contact'] = $contribution->contact_id
;
110 if (!empty($ids['contributionRecur'])) {
111 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
112 $contributionRecur->id
= $ids['contributionRecur'];
113 if (!$contributionRecur->find(TRUE)) {
114 CRM_Core_Error
::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
115 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
120 $objects['contact'] = &$contact;
121 $objects['contribution'] = &$contribution;
123 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
124 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
125 // We don't need to worry if about removing contribution page id as it will be set later in
126 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
127 unset($ids['contributionPage']);
130 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
137 * Load objects related to contribution.
139 * @input array information from Payment processor
141 * @param array $input
143 * @param array $objects
144 * @param bool $required
145 * @param int $paymentProcessorID
148 * @throws \CRM_Core_Exception
150 public function loadObjects($input, &$ids, &$objects, $required, $paymentProcessorID) {
151 $contribution = &$objects['contribution'];
152 $ids['paymentProcessor'] = $paymentProcessorID;
153 $success = $contribution->loadRelatedObjects($input, $ids);
154 if ($required && empty($contribution->_relatedObjects
['paymentProcessor'])) {
155 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id
);
157 $objects = array_merge($objects, $contribution->_relatedObjects
);
162 * Set contribution to failed.
164 * @param array $objects
167 * @throws \CiviCRM_API3_Exception|\CRM_Core_Exception
169 public function failed($objects) {
170 $contribution = &$objects['contribution'];
172 if (!empty($objects['membership'])) {
173 $memberships = &$objects['membership'];
174 if (is_numeric($memberships)) {
175 $memberships = [$objects['membership']];
179 $addLineItems = empty($contribution->id
);
180 $participant = &$objects['participant'];
181 $contribution->contribution_status_id
= CRM_Core_PseudoConstant
::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Failed');
182 $contribution->save();
184 // Add line items for recurring payments.
185 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
186 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
189 //add new soft credit against current contribution id and
190 //copy initial contribution custom fields for recurring contributions
191 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
192 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
193 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
196 if (!empty($memberships)) {
197 foreach ($memberships as $membership) {
198 // @fixme Should we cancel only Pending memberships? per cancelled()
199 $this->cancelMembership($membership, $membership->status_id
, FALSE);
204 $this->cancelParticipant($participant->id
);
207 Civi
::log()->debug("Setting contribution status to Failed");
212 * Handled pending contribution status.
216 * @param array $objects
217 * @param object $transaction
221 public function pending(&$objects, &$transaction) {
222 CRM_Core_Error
::deprecatedFunctionWarning('This function will be removed at some point');
223 $transaction->commit();
224 Civi
::log()->debug('Returning since contribution status is Pending');
225 echo 'Success: Returning since contribution status is pending<p>';
230 * Process cancelled payment outcome.
232 * @param array $objects
235 * @throws \CiviCRM_API3_Exception|\CRM_Core_Exception
237 public function cancelled($objects) {
238 $contribution = &$objects['contribution'];
240 if (!empty($objects['membership'])) {
241 $memberships = &$objects['membership'];
242 if (is_numeric($memberships)) {
243 $memberships = [$objects['membership']];
247 $addLineItems = FALSE;
248 if (empty($contribution->id
)) {
249 $addLineItems = TRUE;
251 $participant = &$objects['participant'];
254 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
255 'labelColumn' => 'name',
258 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
259 $contribution->cancel_date
= self
::$_now;
260 $contribution->save();
262 // Add line items for recurring payments.
263 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
264 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
267 //add new soft credit against current $contribution and
268 //copy initial contribution custom fields for recurring contributions
269 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
270 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
271 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
274 if (!empty($memberships)) {
275 foreach ($memberships as $membership) {
277 $this->cancelMembership($membership, $membership->status_id
);
283 $this->cancelParticipant($participant->id
);
286 Civi
::log()->debug("Setting contribution status to Cancelled");
291 * Rollback unhandled outcomes.
295 * @param array $objects
296 * @param CRM_Core_Transaction $transaction
300 public function unhandled(&$objects, &$transaction) {
301 CRM_Core_Error
::deprecatedFunctionWarning('This function will be removed at some point');
302 $transaction->rollback();
303 Civi
::log()->debug('Returning since contribution status is not handled');
304 echo 'Failure: contribution status is not handled<p>';
309 * Logic to cancel a participant record when the related contribution changes to failed/cancelled.
310 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
312 * @param $participantID
314 * @throws \CiviCRM_API3_Exception
316 private function cancelParticipant($participantID) {
317 // @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
318 $participantParams['id'] = $participantID;
319 $participantParams['status_id'] = 'Cancelled';
320 civicrm_api3('Participant', 'create', $participantParams);
324 * Logic to cancel a membership record when the related contribution changes to failed/cancelled.
325 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
326 * @param \CRM_Member_BAO_Membership $membership
327 * @param int $membershipStatusID
328 * @param boolean $onlyCancelPendingMembership
329 * Do we only cancel pending memberships? OR memberships in any status? (see CRM-18688)
330 * @fixme Historically failed() cancelled membership in any status, cancelled() cancelled only pending memberships so we retain that behaviour for now.
333 private function cancelMembership($membership, $membershipStatusID, $onlyCancelPendingMembership = TRUE) {
334 // @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
335 // Cancel only Pending memberships
336 $pendingMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
337 if (($membershipStatusID == $pendingMembershipStatusId) ||
($onlyCancelPendingMembership == FALSE)) {
338 $cancelledMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Cancelled');
340 $membership->status_id
= $cancelledMembershipStatusId;
343 $params = ['status_id' => $cancelledMembershipStatusId];
344 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
346 // @todo Convert the above to API
347 // $membershipParams = [
348 // 'id' => $membership->id,
349 // 'status_id' => $cancelledMembershipStatusId,
351 // civicrm_api3('Membership', 'create', $membershipParams);
352 // CRM_Member_BAO_Membership::updateRelatedMemberships($membershipParams['id'], ['status_id' => $cancelledMembershipStatusId]);
360 * Jumbled up function.
362 * The purpose of this function is to transition a pending transaction to Completed including updating any
365 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
366 * updating related entities.
368 * It is recommended to avoid calling this function directly and call the api functions:
369 * - contribution.completetransaction
370 * - contribution.repeattransaction
372 * These functions are the focus of testing efforts and more accurately reflect the division of roles
373 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
374 * and from there it should be possible to pass off transaction management.)
376 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
377 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
379 * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo
380 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
381 * a shared function that updates related components.
383 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
384 * IPN class is better accessed through the api which de-jumbles it a bit.
386 * e.g the payment class can have a function like (based on Omnipay extension):
388 * public function handlePaymentNotification() {
389 * $response = $this->getValidatedOutcome();
390 * if ($response->isSuccessful()) {
392 * // @todo check if it is a repeat transaction & call repeattransaction instead.
393 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
395 * catch (CiviCRM_API3_Exception $e) {
396 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
397 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
398 * have occurred. Please check your receipt is correct');
399 * $this->redirectOrExit('success');
401 * elseif ($this->transaction_id) {
402 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
406 * @param array $input
408 * @param array $objects
410 * @throws \CRM_Core_Exception
411 * @throws \CiviCRM_API3_Exception
413 public function completeTransaction($input, $ids, $objects) {
414 CRM_Core_Error
::deprecatedFunctionWarning('Use Payment.create api');
415 CRM_Contribute_BAO_Contribution
::completeOrder($input, [
416 'related_contact' => $ids['related_contact'] ??
NULL,
417 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
418 'contributionRecur' => !empty($objects['contributionRecur']) ?
$objects['contributionRecur']->id
: NULL,
419 ], $objects['contribution']);
424 * Get site billing ID.
430 public function getBillingID(&$ids) {
431 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_LocationType::getBilling()');
432 $ids['billing'] = CRM_Core_BAO_LocationType
::getBilling();
433 if (!$ids['billing']) {
434 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
435 echo "Failure: Could not find billing location type<p>";
444 * @todo confirm this function is not being used by any payment processor outside core & remove.
446 * Note that the compose message part has been moved to contribution
447 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
449 * @param array $input
450 * Incoming data from Payment processor.
452 * Related object IDs.
453 * @param array $objects
455 * @throws \CiviCRM_API3_Exception
457 public function sendMail($input, $ids, $objects) {
458 CRM_Core_Error
::deprecatedFunctionWarning('this should be done via completetransaction api');
459 civicrm_api3('Contribution', 'sendconfirmation', [
460 'id' => $objects['contribution']->id
,