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