[REF] Remove most interaction with
[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
TO
11
12/**
1d86918a 13 * Class CRM_Core_Payment_BaseIPN.
6a488035
TO
14 */
15class CRM_Core_Payment_BaseIPN {
16
518fa0ee 17 public static $_now = NULL;
8196c759 18
c8aa607b 19 /**
20 * Input parameters from payment processor. Store these so that
21 * the code does not need to keep retrieving from the http request
22 * @var array
23 */
be2fb01f 24 protected $_inputParameters = [];
c8aa607b 25
59cdadfc 26 /**
27 * Only used by AuthorizeNetIPN.
518fa0ee 28 * @var bool
59cdadfc 29 *
30 * @deprecated
31 *
59cdadfc 32 */
937cf542
EM
33 protected $_isRecurring = FALSE;
34
59cdadfc 35 /**
36 * Only used by AuthorizeNetIPN.
518fa0ee 37 * @var bool
59cdadfc 38 *
39 * @deprecated
40 *
59cdadfc 41 */
937cf542 42 protected $_isFirstOrLastRecurringPayment = FALSE;
353ffa53 43
8196c759 44 /**
fe482240 45 * Constructor.
8196c759 46 */
00be9182 47 public function __construct() {
6a488035
TO
48 self::$_now = date('YmdHis');
49 }
50
c8aa607b 51 /**
fe482240 52 * Store input array on the class.
77b97be7 53 *
c8aa607b 54 * @param array $parameters
77b97be7
EM
55 *
56 * @throws CRM_Core_Exception
c8aa607b 57 */
00be9182 58 public function setInputParameters($parameters) {
22e263ad 59 if (!is_array($parameters)) {
cc0c30cc 60 throw new CRM_Core_Exception('Invalid input parameters');
c8aa607b 61 }
62 $this->_inputParameters = $parameters;
63 }
353ffa53 64
8196c759 65 /**
1d86918a
EM
66 * Validate incoming data.
67 *
68 * This function is intended to ensure that incoming data matches
8196c759 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.
74 *
6a0b768e
TO
75 * @param array $input
76 * Interpreted values from the values returned through the IPN.
77 * @param array $ids
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.
1d86918a 85 *
5c766a0b 86 * @return bool
8196c759 87 */
ad64fa72 88 public function validateData($input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
6a488035 89
21843539 90 // Check if the contribution exists
6a488035 91 // make sure contribution exists and is valid
5a9c68ac 92 $contribution = new CRM_Contribute_BAO_Contribution();
6a488035
TO
93 $contribution->id = $ids['contribution'];
94 if (!$contribution->find(TRUE)) {
92fcb95f 95 CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
6a488035
TO
96 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
97 return FALSE;
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 122 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
d9924163 123 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
6a488035
TO
124
125 $objects['contact'] = &$contact;
126 $objects['contribution'] = &$contribution;
d0488f03 127
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']);
133 }
134
6a488035
TO
135 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
136 return FALSE;
137 }
6a488035
TO
138 return TRUE;
139 }
140
8196c759 141 /**
fe482240 142 * Load objects related to contribution.
6a488035
TO
143 *
144 * @input array information from Payment processor
dd244018 145 *
3aaa68fb 146 * @param array $input
8196c759 147 * @param array $ids
148 * @param array $objects
6a0b768e
TO
149 * @param bool $required
150 * @param int $paymentProcessorID
8196c759 151 * @param array $error_handling
dd244018 152 *
3aaa68fb 153 * @return bool|array
6a488035 154 */
ad64fa72 155 public function loadObjects($input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
6a488035
TO
156 if (empty($error_handling)) {
157 // default options are that we log an error & echo it out
158 // note that we should refactor this error handling into error code @ some point
159 // but for now setting up enough separation so we can do unit tests
be2fb01f 160 $error_handling = [
6a488035
TO
161 'log_error' => 1,
162 'echo_error' => 1,
be2fb01f 163 ];
6a488035
TO
164 }
165 $ids['paymentProcessor'] = $paymentProcessorID;
166 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
167 $contribution = &$objects['contribution'];
168 }
169 else {
170 //legacy support - functions are 'used' to be able to pass in a DAO
171 $contribution = new CRM_Contribute_BAO_Contribution();
9c1bc317 172 $contribution->id = $ids['contribution'] ?? NULL;
6a488035
TO
173 $contribution->find(TRUE);
174 $objects['contribution'] = &$contribution;
175 }
176 try {
276e3ec6 177 $success = $contribution->loadRelatedObjects($input, $ids);
178 if ($required && empty($contribution->_relatedObjects['paymentProcessor'])) {
179 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id);
180 }
6a488035 181 }
353ffa53 182 catch (Exception $e) {
cc0c30cc 183 $success = FALSE;
a7488080 184 if (!empty($error_handling['log_error'])) {
6a488035
TO
185 CRM_Core_Error::debug_log_message($e->getMessage());
186 }
a7488080 187 if (!empty($error_handling['echo_error'])) {
6c552737 188 echo $e->getMessage();
6a488035 189 }
a7488080 190 if (!empty($error_handling['return_error'])) {
be2fb01f 191 return [
6a488035
TO
192 'is_error' => 1,
193 'error_message' => ($e->getMessage()),
be2fb01f 194 ];
6a488035
TO
195 }
196 }
197 $objects = array_merge($objects, $contribution->_relatedObjects);
198 return $success;
199 }
200
8196c759 201 /**
fe482240 202 * Set contribution to failed.
28de42d1 203 *
8196c759 204 * @param array $objects
205 * @param object $transaction
206 * @param array $input
28de42d1 207 *
5c766a0b 208 * @return bool
e44c82e1 209 * @throws \CiviCRM_API3_Exception
8196c759 210 */
156534ce 211 public function failed(&$objects, $transaction = NULL, $input = []) {
6a488035 212 $contribution = &$objects['contribution'];
be2fb01f 213 $memberships = [];
a7488080 214 if (!empty($objects['membership'])) {
6a488035
TO
215 $memberships = &$objects['membership'];
216 if (is_numeric($memberships)) {
be2fb01f 217 $memberships = [$objects['membership']];
6a488035
TO
218 }
219 }
220
4586a81f 221 $addLineItems = empty($contribution->id);
6a488035 222 $participant = &$objects['participant'];
4586a81f 223 $contribution->contribution_status_id = CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Failed');
6a488035
TO
224 $contribution->save();
225
28de42d1 226 // Add line items for recurring payments.
a7488080 227 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
e577770c 228 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
229 }
230
8381af80 231 //add new soft credit against current contribution id and
6357981e 232 //copy initial contribution custom fields for recurring contributions
a7488080 233 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
e577770c
EM
234 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
235 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
236 }
237
0bad10e7 238 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
6a488035
TO
239 if (!empty($memberships)) {
240 foreach ($memberships as $membership) {
56c7d914
MWMC
241 // @fixme Should we cancel only Pending memberships? per cancelled()
242 $this->cancelMembership($membership, $membership->status_id, FALSE);
6a488035
TO
243 }
244 }
d63f4fc3 245
6a488035 246 if ($participant) {
56c7d914 247 $this->cancelParticipant($participant->id);
6a488035
TO
248 }
249 }
250
156534ce 251 if ($transaction) {
252 $transaction->commit();
253 }
e44c82e1 254 Civi::log()->debug("Setting contribution status to Failed");
6a488035
TO
255 return TRUE;
256 }
257
8196c759 258 /**
fe482240 259 * Handled pending contribution status.
1d86918a 260 *
0e89200f 261 * @deprecated
262 *
8196c759 263 * @param array $objects
264 * @param object $transaction
1d86918a 265 *
5c766a0b 266 * @return bool
8196c759 267 */
00be9182 268 public function pending(&$objects, &$transaction) {
0e89200f 269 CRM_Core_Error::deprecatedFunctionWarning('This function will be removed at some point');
6a488035 270 $transaction->commit();
0e89200f 271 Civi::log()->debug('Returning since contribution status is Pending');
272 echo 'Success: Returning since contribution status is pending<p>';
6a488035
TO
273 return TRUE;
274 }
275
6c786a9b 276 /**
1d86918a
EM
277 * Process cancelled payment outcome.
278 *
3aaa68fb 279 * @param array $objects
280 * @param CRM_Core_Transaction $transaction
6c786a9b
EM
281 * @param array $input
282 *
283 * @return bool
e44c82e1 284 * @throws \CiviCRM_API3_Exception
6c786a9b 285 */
156534ce 286 public function cancelled(&$objects, $transaction = NULL, $input = []) {
6a488035 287 $contribution = &$objects['contribution'];
e44c82e1
MWMC
288 $memberships = [];
289 if (!empty($objects['membership'])) {
290 $memberships = &$objects['membership'];
291 if (is_numeric($memberships)) {
292 $memberships = [$objects['membership']];
293 }
6a488035
TO
294 }
295
6a488035
TO
296 $addLineItems = FALSE;
297 if (empty($contribution->id)) {
298 $addLineItems = TRUE;
299 }
e44c82e1
MWMC
300 $participant = &$objects['participant'];
301
302 // CRM-15546
be2fb01f 303 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
518fa0ee
SL
304 'labelColumn' => 'name',
305 'flip' => 1,
306 ]);
71d085fe 307 $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
6a488035
TO
308 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
309 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
310 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
e44c82e1 311 $contribution->cancel_date = self::$_now;
9c1bc317 312 $contribution->cancel_reason = $input['reasonCode'] ?? NULL;
6a488035
TO
313 $contribution->save();
314
e44c82e1 315 // Add line items for recurring payments.
a7488080 316 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
e577770c 317 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
318 }
319
8381af80 320 //add new soft credit against current $contribution and
6357981e 321 //copy initial contribution custom fields for recurring contributions
a7488080 322 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
e577770c
EM
323 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
324 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
325 }
326
0bad10e7 327 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
6a488035
TO
328 if (!empty($memberships)) {
329 foreach ($memberships as $membership) {
56c7d914
MWMC
330 if ($membership) {
331 $this->cancelMembership($membership, $membership->status_id);
6a488035
TO
332 }
333 }
334 }
d63f4fc3 335
6a488035 336 if ($participant) {
56c7d914 337 $this->cancelParticipant($participant->id);
6a488035
TO
338 }
339 }
156534ce 340 if ($transaction) {
341 $transaction->commit();
342 }
e44c82e1 343 Civi::log()->debug("Setting contribution status to Cancelled");
6a488035
TO
344 return TRUE;
345 }
346
6c786a9b 347 /**
1d86918a
EM
348 * Rollback unhandled outcomes.
349 *
85ce114d 350 * @deprecated
351 *
3aaa68fb 352 * @param array $objects
353 * @param CRM_Core_Transaction $transaction
6c786a9b
EM
354 *
355 * @return bool
356 */
00be9182 357 public function unhandled(&$objects, &$transaction) {
85ce114d 358 CRM_Core_Error::deprecatedFunctionWarning('This function will be removed at some point');
6a488035 359 $transaction->rollback();
85ce114d 360 Civi::log()->debug('Returning since contribution status is not handled');
361 echo 'Failure: contribution status is not handled<p>';
6a488035
TO
362 return FALSE;
363 }
364
56c7d914
MWMC
365 /**
366 * Logic to cancel a participant record when the related contribution changes to failed/cancelled.
367 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
368 *
369 * @param $participantID
370 *
371 * @throws \CiviCRM_API3_Exception
372 */
373 private function cancelParticipant($participantID) {
374 // @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
375 $participantParams['id'] = $participantID;
376 $participantParams['status_id'] = 'Cancelled';
377 civicrm_api3('Participant', 'create', $participantParams);
378 }
379
380 /**
381 * Logic to cancel a membership record when the related contribution changes to failed/cancelled.
382 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
383 * @param \CRM_Member_BAO_Membership $membership
384 * @param int $membershipStatusID
385 * @param boolean $onlyCancelPendingMembership
386 * Do we only cancel pending memberships? OR memberships in any status? (see CRM-18688)
387 * @fixme Historically failed() cancelled membership in any status, cancelled() cancelled only pending memberships so we retain that behaviour for now.
388 *
389 */
390 private function cancelMembership($membership, $membershipStatusID, $onlyCancelPendingMembership = TRUE) {
391 // @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
392 // Cancel only Pending memberships
393 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
394 if (($membershipStatusID == $pendingMembershipStatusId) || ($onlyCancelPendingMembership == FALSE)) {
395 $cancelledMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Cancelled');
396
397 $membership->status_id = $cancelledMembershipStatusId;
398 $membership->save();
399
400 $params = ['status_id' => $cancelledMembershipStatusId];
401 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
402
403 // @todo Convert the above to API
404 // $membershipParams = [
405 // 'id' => $membership->id,
406 // 'status_id' => $cancelledMembershipStatusId,
407 // ];
408 // civicrm_api3('Membership', 'create', $membershipParams);
409 // CRM_Member_BAO_Membership::updateRelatedMemberships($membershipParams['id'], ['status_id' => $cancelledMembershipStatusId]);
410 }
411
412 }
413
6c786a9b 414 /**
4a1ba425 415 * @deprecated
416 *
3ccde016 417 * Jumbled up function.
1d86918a 418 *
3ccde016
EM
419 * The purpose of this function is to transition a pending transaction to Completed including updating any
420 * related entities.
421 *
422 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
423 * updating related entities.
424 *
425 * It is recommended to avoid calling this function directly and call the api functions:
426 * - contribution.completetransaction
427 * - contribution.repeattransaction
428 *
429 * These functions are the focus of testing efforts and more accurately reflect the division of roles
430 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
431 * and from there it should be possible to pass off transaction management.)
432 *
433 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
434 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
435 *
5ca657dd 436 * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo
3ccde016
EM
437 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
438 * a shared function that updates related components.
439 *
440 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
441 * IPN class is better accessed through the api which de-jumbles it a bit.
442 *
443 * e.g the payment class can have a function like (based on Omnipay extension):
444 *
445 * public function handlePaymentNotification() {
446 * $response = $this->getValidatedOutcome();
447 * if ($response->isSuccessful()) {
448 * try {
449 * // @todo check if it is a repeat transaction & call repeattransaction instead.
450 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
451 * }
452 * catch (CiviCRM_API3_Exception $e) {
453 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
454 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
455 * have occurred. Please check your receipt is correct');
456 * $this->redirectOrExit('success');
457 * }
458 * elseif ($this->transaction_id) {
459 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
460 * 'Failed'));
461 * }
462 *
463 * @param array $input
464 * @param array $ids
465 * @param array $objects
e44c82e1
MWMC
466 *
467 * @throws \CRM_Core_Exception
468 * @throws \CiviCRM_API3_Exception
6c786a9b 469 */
c7497653 470 public function completeTransaction($input, $ids, $objects) {
adb4fb96 471 CRM_Contribute_BAO_Contribution::completeOrder($input, [
472 'related_contact' => $ids['related_contact'] ?? NULL,
473 'participant' => !empty($objects['participant']) ? $objects['participant']->id : NULL,
474 'contributionRecur' => !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
475 ], $objects);
6a488035
TO
476 }
477
6c786a9b 478 /**
e9a11021 479 * @deprecated
1d86918a
EM
480 * Get site billing ID.
481 *
482 * @param array $ids
6c786a9b
EM
483 *
484 * @return bool
485 */
00be9182 486 public function getBillingID(&$ids) {
e9a11021 487 CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_BAO_LocationType::getBilling()');
b576d770 488 $ids['billing'] = CRM_Core_BAO_LocationType::getBilling();
6a488035 489 if (!$ids['billing']) {
be2fb01f 490 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
6a488035
TO
491 echo "Failure: Could not find billing location type<p>";
492 return FALSE;
493 }
494 return TRUE;
495 }
496
c490a46a 497 /**
db59bb73
EM
498 * @deprecated
499 *
6626a693 500 * @todo confirm this function is not being used by any payment processor outside core & remove.
501 *
1d86918a 502 * Note that the compose message part has been moved to contribution
6a488035
TO
503 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
504 *
6a0b768e
TO
505 * @param array $input
506 * Incoming data from Payment processor.
507 * @param array $ids
508 * Related object IDs.
3aaa68fb 509 * @param array $objects
5909727d 510 *
e44c82e1 511 * @throws \CiviCRM_API3_Exception
6c786a9b 512 */
5909727d 513 public function sendMail($input, $ids, $objects) {
514 CRM_Core_Error::deprecatedFunctionWarning('this should be done via completetransaction api');
515 civicrm_api3('Contribution', 'sendconfirmation', [
516 'id' => $objects['contribution']->id,
517 ]);
6a488035
TO
518 }
519
b2b0530a 520}