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