dev/core#927 preliminary cleanup
[civicrm-core.git] / CRM / Core / Payment / BaseIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
1ba7b504 12use Civi\Api4\Contribution;
13
6a488035 14/**
1d86918a 15 * Class CRM_Core_Payment_BaseIPN.
6a488035
TO
16 */
17class CRM_Core_Payment_BaseIPN {
18
518fa0ee 19 public static $_now = NULL;
8196c759 20
c8aa607b 21 /**
22 * Input parameters from payment processor. Store these so that
23 * the code does not need to keep retrieving from the http request
24 * @var array
25 */
be2fb01f 26 protected $_inputParameters = [];
c8aa607b 27
59cdadfc 28 /**
29 * Only used by AuthorizeNetIPN.
518fa0ee 30 * @var bool
59cdadfc 31 *
32 * @deprecated
33 *
59cdadfc 34 */
937cf542
EM
35 protected $_isRecurring = FALSE;
36
59cdadfc 37 /**
38 * Only used by AuthorizeNetIPN.
518fa0ee 39 * @var bool
59cdadfc 40 *
41 * @deprecated
42 *
59cdadfc 43 */
937cf542 44 protected $_isFirstOrLastRecurringPayment = FALSE;
353ffa53 45
8196c759 46 /**
fe482240 47 * Constructor.
8196c759 48 */
00be9182 49 public function __construct() {
6a488035
TO
50 self::$_now = date('YmdHis');
51 }
52
c8aa607b 53 /**
fe482240 54 * Store input array on the class.
77b97be7 55 *
c8aa607b 56 * @param array $parameters
77b97be7
EM
57 *
58 * @throws CRM_Core_Exception
c8aa607b 59 */
00be9182 60 public function setInputParameters($parameters) {
22e263ad 61 if (!is_array($parameters)) {
cc0c30cc 62 throw new CRM_Core_Exception('Invalid input parameters');
c8aa607b 63 }
64 $this->_inputParameters = $parameters;
65 }
353ffa53 66
8196c759 67 /**
1d86918a
EM
68 * Validate incoming data.
69 *
70 * This function is intended to ensure that incoming data matches
8196c759 71 * It provides a form of pseudo-authentication - by checking the calling fn already knows
72 * the correct contact id & contribution id (this can be problematic when that has changed in
73 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
74 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
75 * and didn't update your IPN URL.
76 *
6a0b768e
TO
77 * @param array $input
78 * Interpreted values from the values returned through the IPN.
79 * @param array $ids
80 * More interpreted values (ids) from the values returned through the IPN.
81 * @param array $objects
82 * An empty array that will be populated with loaded object.
83 * @param bool $required
84 * Boolean Return FALSE if the relevant objects don't exist.
85 * @param int $paymentProcessorID
86 * Id of the payment processor ID in use.
1d86918a 87 *
5c766a0b 88 * @return bool
8196c759 89 */
ad64fa72 90 public function validateData($input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
6a488035 91
21843539 92 // Check if the contribution exists
6a488035 93 // make sure contribution exists and is valid
5a9c68ac 94 $contribution = new CRM_Contribute_BAO_Contribution();
6a488035
TO
95 $contribution->id = $ids['contribution'];
96 if (!$contribution->find(TRUE)) {
eb0fd0ce 97 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)]);
6a488035 98 }
21843539
SL
99
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;
110 }
111
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>";
118 return FALSE;
119 }
120 }
121
6a488035
TO
122 $objects['contact'] = &$contact;
123 $objects['contribution'] = &$contribution;
d0488f03 124
125 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
126 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
127 // We don't need to worry if about removing contribution page id as it will be set later in
128 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
129 unset($ids['contributionPage']);
130 }
131
6a488035
TO
132 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
133 return FALSE;
134 }
6a488035
TO
135 return TRUE;
136 }
137
8196c759 138 /**
fe482240 139 * Load objects related to contribution.
6a488035
TO
140 *
141 * @input array information from Payment processor
dd244018 142 *
3aaa68fb 143 * @param array $input
8196c759 144 * @param array $ids
145 * @param array $objects
6a0b768e
TO
146 * @param bool $required
147 * @param int $paymentProcessorID
dd244018 148 *
3aaa68fb 149 * @return bool|array
49ed4888 150 * @throws \CRM_Core_Exception
6a488035 151 */
49ed4888 152 public function loadObjects($input, &$ids, &$objects, $required, $paymentProcessorID) {
eb0fd0ce 153 $contribution = &$objects['contribution'];
6a488035 154 $ids['paymentProcessor'] = $paymentProcessorID;
49ed4888 155 $success = $contribution->loadRelatedObjects($input, $ids);
156 if ($required && empty($contribution->_relatedObjects['paymentProcessor'])) {
157 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id);
6a488035
TO
158 }
159 $objects = array_merge($objects, $contribution->_relatedObjects);
160 return $success;
161 }
162
8196c759 163 /**
fe482240 164 * Set contribution to failed.
28de42d1 165 *
8196c759 166 * @param array $objects
28de42d1 167 *
5c766a0b 168 * @return bool
09cafd47 169 * @throws \CiviCRM_API3_Exception|\CRM_Core_Exception
8196c759 170 */
09cafd47 171 public function failed($objects) {
6a488035 172 $contribution = &$objects['contribution'];
be2fb01f 173 $memberships = [];
a7488080 174 if (!empty($objects['membership'])) {
6a488035
TO
175 $memberships = &$objects['membership'];
176 if (is_numeric($memberships)) {
be2fb01f 177 $memberships = [$objects['membership']];
6a488035
TO
178 }
179 }
180
4586a81f 181 $addLineItems = empty($contribution->id);
6a488035 182 $participant = &$objects['participant'];
4586a81f 183 $contribution->contribution_status_id = CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Failed');
6a488035
TO
184 $contribution->save();
185
28de42d1 186 // Add line items for recurring payments.
a7488080 187 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
e577770c 188 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
189 }
190
391ccd27 191 if (!empty($memberships)) {
192 foreach ($memberships as $membership) {
193 // @fixme Should we cancel only Pending memberships? per cancelled()
194 $this->cancelMembership($membership, $membership->status_id, FALSE);
6a488035 195 }
391ccd27 196 }
d63f4fc3 197
391ccd27 198 if ($participant) {
199 $this->cancelParticipant($participant->id);
6a488035
TO
200 }
201
e44c82e1 202 Civi::log()->debug("Setting contribution status to Failed");
6a488035
TO
203 return TRUE;
204 }
205
8196c759 206 /**
fe482240 207 * Handled pending contribution status.
1d86918a 208 *
0e89200f 209 * @deprecated
210 *
8196c759 211 * @param array $objects
212 * @param object $transaction
1d86918a 213 *
5c766a0b 214 * @return bool
8196c759 215 */
00be9182 216 public function pending(&$objects, &$transaction) {
0e89200f 217 CRM_Core_Error::deprecatedFunctionWarning('This function will be removed at some point');
6a488035 218 $transaction->commit();
0e89200f 219 Civi::log()->debug('Returning since contribution status is Pending');
220 echo 'Success: Returning since contribution status is pending<p>';
6a488035
TO
221 return TRUE;
222 }
223
6c786a9b 224 /**
1d86918a
EM
225 * Process cancelled payment outcome.
226 *
3aaa68fb 227 * @param array $objects
6c786a9b
EM
228 *
229 * @return bool
01ebb9d3 230 * @throws \CiviCRM_API3_Exception|\CRM_Core_Exception
6c786a9b 231 */
01ebb9d3 232 public function cancelled($objects) {
6a488035 233 $contribution = &$objects['contribution'];
e44c82e1
MWMC
234 $memberships = [];
235 if (!empty($objects['membership'])) {
236 $memberships = &$objects['membership'];
237 if (is_numeric($memberships)) {
238 $memberships = [$objects['membership']];
239 }
6a488035
TO
240 }
241
6a488035
TO
242 if (empty($contribution->id)) {
243 $addLineItems = TRUE;
1ba7b504 244 // CRM-15546
245 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
246 'labelColumn' => 'name',
247 'flip' => 1,
248 ]);
249 $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
250 $contribution->cancel_date = self::$_now;
251 $contribution->save();
252 // Add line items for recurring payments.
253 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
254 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
255 }
6a488035 256 }
1ba7b504 257 else {
258 Contribution::update(FALSE)->setValues([
259 'cancel_date' => 'now',
260 'contribution_status_id:name' => 'Cancelled',
261 ])->addWhere('id', '=', $contribution->id)->execute();
6a488035 262 }
1ba7b504 263 $participant = &$objects['participant'];
6a488035 264
4eba8926 265 if (!empty($memberships)) {
266 foreach ($memberships as $membership) {
267 if ($membership) {
268 $this->cancelMembership($membership, $membership->status_id);
6a488035
TO
269 }
270 }
4eba8926 271 }
d63f4fc3 272
4eba8926 273 if ($participant) {
274 $this->cancelParticipant($participant->id);
6a488035 275 }
4eba8926 276
e44c82e1 277 Civi::log()->debug("Setting contribution status to Cancelled");
6a488035
TO
278 return TRUE;
279 }
280
6c786a9b 281 /**
1d86918a
EM
282 * Rollback unhandled outcomes.
283 *
85ce114d 284 * @deprecated
285 *
3aaa68fb 286 * @param array $objects
287 * @param CRM_Core_Transaction $transaction
6c786a9b
EM
288 *
289 * @return bool
290 */
00be9182 291 public function unhandled(&$objects, &$transaction) {
85ce114d 292 CRM_Core_Error::deprecatedFunctionWarning('This function will be removed at some point');
6a488035 293 $transaction->rollback();
85ce114d 294 Civi::log()->debug('Returning since contribution status is not handled');
295 echo 'Failure: contribution status is not handled<p>';
6a488035
TO
296 return FALSE;
297 }
298
56c7d914
MWMC
299 /**
300 * Logic to cancel a participant record when the related contribution changes to failed/cancelled.
301 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
302 *
303 * @param $participantID
304 *
305 * @throws \CiviCRM_API3_Exception
306 */
307 private function cancelParticipant($participantID) {
308 // @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
309 $participantParams['id'] = $participantID;
310 $participantParams['status_id'] = 'Cancelled';
311 civicrm_api3('Participant', 'create', $participantParams);
312 }
313
314 /**
315 * Logic to cancel a membership record when the related contribution changes to failed/cancelled.
316 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
317 * @param \CRM_Member_BAO_Membership $membership
318 * @param int $membershipStatusID
319 * @param boolean $onlyCancelPendingMembership
320 * Do we only cancel pending memberships? OR memberships in any status? (see CRM-18688)
321 * @fixme Historically failed() cancelled membership in any status, cancelled() cancelled only pending memberships so we retain that behaviour for now.
322 *
323 */
324 private function cancelMembership($membership, $membershipStatusID, $onlyCancelPendingMembership = TRUE) {
325 // @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
326 // Cancel only Pending memberships
327 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
328 if (($membershipStatusID == $pendingMembershipStatusId) || ($onlyCancelPendingMembership == FALSE)) {
329 $cancelledMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Cancelled');
330
331 $membership->status_id = $cancelledMembershipStatusId;
332 $membership->save();
333
334 $params = ['status_id' => $cancelledMembershipStatusId];
335 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
336
337 // @todo Convert the above to API
338 // $membershipParams = [
339 // 'id' => $membership->id,
340 // 'status_id' => $cancelledMembershipStatusId,
341 // ];
342 // civicrm_api3('Membership', 'create', $membershipParams);
343 // CRM_Member_BAO_Membership::updateRelatedMemberships($membershipParams['id'], ['status_id' => $cancelledMembershipStatusId]);
344 }
345
346 }
347
6c786a9b 348 /**
4a1ba425 349 * @deprecated
350 *
3ccde016 351 * Jumbled up function.
1d86918a 352 *
3ccde016
EM
353 * The purpose of this function is to transition a pending transaction to Completed including updating any
354 * related entities.
355 *
356 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
357 * updating related entities.
358 *
359 * It is recommended to avoid calling this function directly and call the api functions:
360 * - contribution.completetransaction
361 * - contribution.repeattransaction
362 *
363 * These functions are the focus of testing efforts and more accurately reflect the division of roles
364 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
365 * and from there it should be possible to pass off transaction management.)
366 *
367 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
368 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
369 *
5ca657dd 370 * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo
3ccde016
EM
371 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
372 * a shared function that updates related components.
373 *
374 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
375 * IPN class is better accessed through the api which de-jumbles it a bit.
376 *
377 * e.g the payment class can have a function like (based on Omnipay extension):
378 *
379 * public function handlePaymentNotification() {
380 * $response = $this->getValidatedOutcome();
381 * if ($response->isSuccessful()) {
382 * try {
383 * // @todo check if it is a repeat transaction & call repeattransaction instead.
384 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
385 * }
386 * catch (CiviCRM_API3_Exception $e) {
387 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
388 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
389 * have occurred. Please check your receipt is correct');
390 * $this->redirectOrExit('success');
391 * }
392 * elseif ($this->transaction_id) {
393 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
394 * 'Failed'));
395 * }
396 *
397 * @param array $input
398 * @param array $ids
399 * @param array $objects
e44c82e1
MWMC
400 *
401 * @throws \CRM_Core_Exception
402 * @throws \CiviCRM_API3_Exception
6c786a9b 403 */
c7497653 404 public function completeTransaction($input, $ids, $objects) {
6067e16b 405 CRM_Core_Error::deprecatedFunctionWarning('Use Payment.create api');
adb4fb96 406 CRM_Contribute_BAO_Contribution::completeOrder($input, [
407 'related_contact' => $ids['related_contact'] ?? NULL,
408 'participant' => !empty($objects['participant']) ? $objects['participant']->id : NULL,
409 'contributionRecur' => !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
fedc226f 410 ], $objects['contribution']);
6a488035
TO
411 }
412
6c786a9b 413 /**
e9a11021 414 * @deprecated
1d86918a
EM
415 * Get site billing ID.
416 *
417 * @param array $ids
6c786a9b
EM
418 *
419 * @return bool
420 */
00be9182 421 public function getBillingID(&$ids) {
e9a11021 422 CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_BAO_LocationType::getBilling()');
b576d770 423 $ids['billing'] = CRM_Core_BAO_LocationType::getBilling();
6a488035 424 if (!$ids['billing']) {
be2fb01f 425 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
6a488035
TO
426 echo "Failure: Could not find billing location type<p>";
427 return FALSE;
428 }
429 return TRUE;
430 }
431
c490a46a 432 /**
db59bb73
EM
433 * @deprecated
434 *
6626a693 435 * @todo confirm this function is not being used by any payment processor outside core & remove.
436 *
1d86918a 437 * Note that the compose message part has been moved to contribution
6a488035
TO
438 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
439 *
6a0b768e
TO
440 * @param array $input
441 * Incoming data from Payment processor.
442 * @param array $ids
443 * Related object IDs.
3aaa68fb 444 * @param array $objects
5909727d 445 *
e44c82e1 446 * @throws \CiviCRM_API3_Exception
6c786a9b 447 */
5909727d 448 public function sendMail($input, $ids, $objects) {
449 CRM_Core_Error::deprecatedFunctionWarning('this should be done via completetransaction api');
450 civicrm_api3('Contribution', 'sendconfirmation', [
451 'id' => $objects['contribution']->id,
452 ]);
6a488035
TO
453 }
454
b2b0530a 455}