[REF] Stop passing contribution into completeOrder, id is enough
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.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 use Civi\Api4\Contribution;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19 class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
20
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 */
26 protected $_inputParameters = [];
27
28 /**
29 * Store for the variables from the invoice string.
30 * @var array
31 */
32 protected $_invoiceData = [];
33
34 /**
35 * Is this a payment express transaction.
36 * @var bool
37 */
38 protected $_isPaymentExpress = FALSE;
39
40 /**
41 * Component.
42 *
43 * Are we dealing with an event an 'anything else' (contribute).
44 *
45 * @var string
46 */
47 protected $_component = 'contribute';
48
49 /**
50 * Constructor function.
51 *
52 * @param array $inputData
53 * Contents of HTTP REQUEST.
54 *
55 * @throws CRM_Core_Exception
56 */
57 public function __construct($inputData) {
58 $this->setInputParameters($inputData);
59 $this->setInvoiceData();
60 parent::__construct();
61 }
62
63 /**
64 * get the values from the rp_invoice_id string.
65 *
66 * @param string $name
67 * E.g. i, values are stored in the string with letter codes.
68 * @param bool $abort
69 * Throw exception if not found
70 *
71 * @throws CRM_Core_Exception
72 * @return mixed
73 */
74 public function getValue($name, $abort = TRUE) {
75 if ($abort && empty($this->_invoiceData[$name])) {
76 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
77 }
78 else {
79 return $this->_invoiceData[$name] ?? NULL;
80 }
81 }
82
83 /**
84 * Set $this->_invoiceData from the input array
85 */
86 public function setInvoiceData() {
87 if (empty($this->_inputParameters['rp_invoice_id'])) {
88 $this->_isPaymentExpress = TRUE;
89 return;
90 }
91 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
92 // for clarify let's also store without the single letter unreadable
93 //@todo after more refactoring we might ditch storing the one letter stuff
94 $mapping = [
95 'i' => 'invoice_id',
96 'm' => 'component',
97 'c' => 'contact_id',
98 'b' => 'contribution_id',
99 'r' => 'contribution_recur_id',
100 'p' => 'participant_id',
101 'e' => 'event_id',
102 ];
103 foreach ($rpInvoiceArray as $rpInvoiceValue) {
104 $rpValueArray = explode('=', $rpInvoiceValue);
105 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
106 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
107 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
108 // alphabet with more letters.
109 // the mode will always be resolved before the mystery p is reached
110 if ($rpValueArray[1] === 'contribute') {
111 $mapping['p'] = 'contribution_page_id';
112 }
113 }
114 if (empty($this->_inputParameters['component'])) {
115 $this->_isPaymentExpress = TRUE;
116 }
117 }
118
119 /**
120 * @param string $name
121 * Of variable to return.
122 * @param string $type
123 * Data type.
124 * - String
125 * - Integer
126 * @param string $location
127 * Deprecated.
128 * @param bool $abort
129 * Abort if empty.
130 *
131 * @throws CRM_Core_Exception
132 * @return mixed
133 */
134 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
135 $value = CRM_Utils_Type::validate(
136 CRM_Utils_Array::value($name, $this->_inputParameters),
137 $type,
138 FALSE
139 );
140 if ($abort && $value === NULL) {
141 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
142 }
143 return $value;
144 }
145
146 /**
147 * Process recurring contributions.
148 *
149 * @param array $input
150 * @param array $ids
151 * @param \CRM_Contribute_BAO_ContributionRecur $recur
152 * @param \CRM_Contribute_BAO_Contribution $contribution
153 * @param bool $first
154 *
155 * @throws \API_Exception
156 * @throws \CRM_Core_Exception
157 * @throws \CiviCRM_API3_Exception
158 * @throws \Civi\API\Exception\UnauthorizedException
159 */
160 public function recur($input, $ids, $recur, $contribution, $first) {
161 if (!isset($input['txnType'])) {
162 Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
163 echo 'Failure: Invalid parameters<p>';
164 return;
165 }
166
167 // make sure the invoice ids match
168 // make sure the invoice is valid and matches what we have in
169 // the contribution record
170 if ($recur->invoice_id != $input['invoice']) {
171 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']);
172 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . " input is " . $input['invoice'];
173 return;
174 }
175
176 $now = date('YmdHis');
177
178 $sendNotification = FALSE;
179 $subscriptionPaymentStatus = NULL;
180 //List of Transaction Type
181 /*
182 recurring_payment_profile_created RP Profile Created
183 recurring_payment RP Successful Payment
184 recurring_payment_failed RP Failed Payment
185 recurring_payment_profile_cancel RP Profile Cancelled
186 recurring_payment_expired RP Profile Expired
187 recurring_payment_skipped RP Profile Skipped
188 recurring_payment_outstanding_payment RP Successful Outstanding Payment
189 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
190 recurring_payment_suspended RP Profile Suspended
191 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
192 */
193
194 //set transaction type
195 $txnType = $this->retrieve('txn_type', 'String');
196 //Changes for paypal pro recurring payment
197 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
198 switch ($txnType) {
199 case 'recurring_payment_profile_created':
200 if (in_array($recur->contribution_status_id, [
201 $contributionStatuses['Pending'],
202 $contributionStatuses['In Progress'],
203 ])
204 && !empty($recur->processor_id)
205 ) {
206 echo "already handled";
207 return;
208 }
209 $recur->create_date = $now;
210 $recur->contribution_status_id = $contributionStatuses['Pending'];
211 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
212 $recur->trxn_id = $recur->processor_id;
213 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
214 $sendNotification = TRUE;
215 break;
216
217 case 'recurring_payment':
218 if ($first) {
219 $recur->start_date = $now;
220 }
221 else {
222 if ($input['paymentStatus'] != 'Completed') {
223 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
224 }
225
226 // In future moving to create pending & then complete, but this OK for now.
227 // Also consider accepting 'Failed' like other processors.
228 $input['contribution_status_id'] = $contributionStatuses['Completed'];
229 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
230 $input['original_contribution_id'] = $ids['contribution'];
231 $input['contribution_recur_id'] = $ids['contributionRecur'];
232
233 civicrm_api3('Contribution', 'repeattransaction', $input);
234 return;
235 }
236
237 //contribution installment is completed
238 if ($this->retrieve('profile_status', 'String') == 'Expired') {
239 if (!empty($recur->end_date)) {
240 echo "already handled";
241 return;
242 }
243 $recur->contribution_status_id = $contributionStatuses['Completed'];
244 $recur->end_date = $now;
245 $sendNotification = TRUE;
246 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
247 }
248
249 // make sure the contribution status is not done
250 // since order of ipn's is unknown
251 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
252 $recur->contribution_status_id = $contributionStatuses['In Progress'];
253 }
254 break;
255 }
256
257 $recur->save();
258
259 if ($sendNotification) {
260 //send recurring Notification email for user
261 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
262 $ids['contact'],
263 $ids['contributionPage'],
264 $recur,
265 !empty($ids['membership'])
266 );
267 }
268
269 if ($txnType !== 'recurring_payment') {
270 return;
271 }
272
273 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
274 $contribution->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
275
276 $this->single($input, [
277 'participant' => $ids['participant'] ?? NULL,
278 'contributionRecur' => $recur->id ?? NULL,
279 ], $contribution, TRUE, $first);
280 }
281
282 /**
283 * @param array $input
284 * @param array $ids
285 * @param \CRM_Contribute_BAO_Contribution $contribution
286 * @param bool $recur
287 * @param bool $first
288 *
289 * @return void
290 * @throws \API_Exception
291 * @throws \CRM_Core_Exception
292 * @throws \CiviCRM_API3_Exception
293 * @throws \Civi\API\Exception\UnauthorizedException
294 */
295 public function single($input, $ids, $contribution, $recur = FALSE, $first = FALSE) {
296
297 // make sure the invoice is valid and matches what we have in the contribution record
298 if ((!$recur) || ($recur && $first)) {
299 if ($contribution->invoice_id != $input['invoice']) {
300 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
301 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
302 return;
303 }
304 }
305 else {
306 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
307 }
308
309 if (!$recur) {
310 if ($contribution->total_amount != $input['amount']) {
311 Civi::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
312 echo "Failure: Amount values dont match between database and IPN request<p>";
313 return;
314 }
315 }
316 else {
317 $contribution->total_amount = $input['amount'];
318 }
319
320 $status = $input['paymentStatus'];
321 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
322 Contribution::update(FALSE)->setValues([
323 'cancel_date' => 'now',
324 'contribution_status_id:name' => 'Failed',
325 ])->addWhere('id', '=', $contribution->id)->execute();
326 Civi::log()->debug("Setting contribution status to Failed");
327 return;
328 }
329 if ($status === 'Pending') {
330 Civi::log()->debug('Returning since contribution status is Pending');
331 return;
332 }
333 if ($status === 'Refunded' || $status === 'Reversed') {
334 Contribution::update(FALSE)->setValues([
335 'cancel_date' => 'now',
336 'contribution_status_id:name' => 'Cancelled',
337 ])->addWhere('id', '=', $contribution->id)->execute();
338 Civi::log()->debug("Setting contribution status to Cancelled");
339 return;
340 }
341 elseif ($status !== 'Completed') {
342 Civi::log()->debug('Returning since contribution status is not handled');
343 return;
344 }
345
346 // check if contribution is already completed, if so we ignore this ipn
347 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
348 if ($contribution->contribution_status_id == $completedStatusId) {
349 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
350 echo 'Success: Contribution has already been handled<p>';
351 return;
352 }
353
354 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $contribution->id ?? NULL);
355 }
356
357 /**
358 * Gets PaymentProcessorID for PayPal
359 *
360 * @return int
361 */
362 public function getPayPalPaymentProcessorID() {
363 // This is an unreliable method as there could be more than one instance.
364 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
365 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
366 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
367 // & call completetransaction or call fail? (which may not exist yet).
368
369 Civi::log()->warning('Unreliable method used to get payment_processor_id for PayPal Pro IPN - this will cause problems if you have more than one instance');
370
371 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
372 'PayPal', 'id', 'name'
373 );
374 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
375 'is_test' => 0,
376 'options' => ['limit' => 1],
377 'payment_processor_type_id' => $paymentProcessorTypeID,
378 'return' => 'id',
379 ]);
380
381 }
382
383 /**
384 * This is the main function to call. It should be sufficient to instantiate the class
385 * (with the input parameters) & call this & all will be done
386 *
387 * @todo the references to POST throughout this class need to be removed
388 * @return void
389 */
390 public function main() {
391 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
392 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
393 try {
394 if ($this->_isPaymentExpress) {
395 $this->handlePaymentExpress();
396 return;
397 }
398 $ids = $input = [];
399 $this->_component = $input['component'] = self::getValue('m');
400 $input['invoice'] = self::getValue('i', TRUE);
401 // get the contribution and contact ids from the GET params
402 $ids['contact'] = self::getValue('c', TRUE);
403 $ids['contribution'] = self::getValue('b', TRUE);
404
405 $this->getInput($input);
406
407 if ($this->_component == 'event') {
408 $ids['event'] = self::getValue('e', TRUE);
409 $ids['participant'] = self::getValue('p', TRUE);
410 $ids['contributionRecur'] = self::getValue('r', FALSE);
411 }
412 else {
413 // get the optional ids
414 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
415 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
416 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
417 $ids['contributionRecur'] = self::getValue('r', FALSE);
418 $ids['contributionPage'] = self::getValue('p', FALSE);
419 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
420 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
421 }
422
423 if (!$ids['membership'] && $ids['contributionRecur']) {
424 $sql = "
425 SELECT m.id
426 FROM civicrm_membership m
427 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
428 WHERE m.contribution_recur_id = %2
429 LIMIT 1";
430 $sqlParams = [
431 1 => [$ids['contribution'], 'Integer'],
432 2 => [$ids['contributionRecur'], 'Integer'],
433 ];
434 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
435 $ids['membership'] = $membershipId;
436 }
437 }
438
439 $paymentProcessorID = CRM_Utils_Array::value('processor_id', $this->_inputParameters);
440 if (!$paymentProcessorID) {
441 $paymentProcessorID = self::getPayPalPaymentProcessorID();
442 }
443
444 // Check if the contribution exists
445 // make sure contribution exists and is valid
446 $contribution = new CRM_Contribute_BAO_Contribution();
447 $contribution->id = $ids['contribution'];
448 if (!$contribution->find(TRUE)) {
449 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)]);
450 }
451
452 // make sure contact exists and is valid
453 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
454 $contact = new CRM_Contact_BAO_Contact();
455 $contact->id = $contribution->contact_id;
456 $contact->find(TRUE);
457 if ($contact->id != $ids['contact']) {
458 // 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
459 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");
460 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
461 $ids['contact'] = $contribution->contact_id;
462 }
463
464 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
465 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
466 // We don't need to worry if about removing contribution page id as it will be set later in
467 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
468 unset($ids['contributionPage']);
469 }
470
471 $ids['paymentProcessor'] = $paymentProcessorID;
472 $contribution->loadRelatedObjects($input, $ids);
473
474 $input['payment_processor_id'] = $paymentProcessorID;
475
476 if ($ids['contributionRecur']) {
477 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
478 $contributionRecur->id = $ids['contributionRecur'];
479 if (!$contributionRecur->find(TRUE)) {
480 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
481 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
482 return;
483 }
484 // check if first contribution is completed, else complete first contribution
485 $first = TRUE;
486 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
487 if ($contribution->contribution_status_id == $completedStatusId) {
488 $first = FALSE;
489 }
490 $this->recur($input, $ids, $contributionRecur, $contribution, $first);
491 return;
492 }
493
494 $this->single($input, [
495 'participant' => $ids['participant'] ?? NULL,
496 'contributionRecur' => $ids['contributionRecur'] ?? NULL,
497 ], $contribution, FALSE, FALSE);
498 }
499 catch (CRM_Core_Exception $e) {
500 Civi::log()->debug($e->getMessage());
501 echo 'Invalid or missing data';
502 }
503 }
504
505 /**
506 * @param array $input
507 *
508 * @return void
509 * @throws CRM_Core_Exception
510 */
511 public function getInput(&$input) {
512 $billingID = CRM_Core_BAO_LocationType::getBilling();
513
514 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
515 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
516
517 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
518 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
519
520 $lookup = [
521 "first_name" => 'first_name',
522 "last_name" => 'last_name',
523 "street_address-{$billingID}" => 'address_street',
524 "city-{$billingID}" => 'address_city',
525 "state-{$billingID}" => 'address_state',
526 "postal_code-{$billingID}" => 'address_zip',
527 "country-{$billingID}" => 'address_country_code',
528 ];
529 foreach ($lookup as $name => $paypalName) {
530 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
531 $input[$name] = $value ? $value : NULL;
532 }
533
534 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
535 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
536 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
537 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
538 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
539 $input['total_amount'] = $input['amount'];
540 }
541
542 /**
543 * Handle payment express IPNs.
544 *
545 * For one off IPNS no actual response is required
546 * Recurring is more difficult as we have limited confirmation material
547 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
548 * duplicated
549 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
550 * then the quasi security of the ids array might be required - although better to
551 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
552 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
553 * only contribute is handled
554 */
555 public function handlePaymentExpress() {
556 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
557 // keep discreet
558 // also note that a lot of the complexity above could be removed if we used
559 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
560 // as membership id etc can be derived by the load objects fn
561 $objects = $ids = $input = [];
562 $isFirst = FALSE;
563 $input['invoice'] = self::getValue('i', FALSE);
564 //Avoid return in case of unit test.
565 if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
566 return;
567 }
568 $input['txnType'] = $this->retrieve('txn_type', 'String');
569 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
570 'return' => 'contact_id, id, payment_processor_id',
571 'invoice_id' => $input['invoice'],
572 ]);
573
574 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
575 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
576 }
577
578 $this->getInput($input, $ids);
579 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
580 throw new CRM_Core_Exception('This transaction has already been processed');
581 }
582
583 $ids['contact'] = $contributionRecur['contact_id'];
584 $ids['contributionRecur'] = $contributionRecur['id'];
585 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
586
587 $ids['contribution'] = $result['id'];
588 //@todo hardcoding 'pending' for now
589 $pendingStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
590 if ($result['contribution_status_id'] == $pendingStatusId) {
591 $isFirst = TRUE;
592 }
593 // arg api won't get this - fix it
594 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
595 1 => [
596 $ids['contribution'],
597 'Integer',
598 ],
599 ]);
600 // only handle component at this stage - not terribly sure how a recurring event payment would arise
601 // & suspec main function may be a victom of copy & paste
602 // membership would be an easy add - but not relevant to my customer...
603 $this->_component = $input['component'] = 'contribute';
604 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime(self::retrieve('time_created', 'String')));
605 $paymentProcessorID = $contributionRecur['payment_processor_id'];
606
607 // Check if the contribution exists
608 // make sure contribution exists and is valid
609 $contribution = new CRM_Contribute_BAO_Contribution();
610 $contribution->id = $ids['contribution'];
611 if (!$contribution->find(TRUE)) {
612 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)]);
613 }
614
615 if (!empty($ids['contributionRecur'])) {
616 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
617 $contributionRecur->id = $ids['contributionRecur'];
618 if (!$contributionRecur->find(TRUE)) {
619 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
620 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
621 return FALSE;
622 }
623 }
624
625 $objects['contribution'] = &$contribution;
626
627 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
628 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
629 // We don't need to worry if about removing contribution page id as it will be set later in
630 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
631 unset($ids['contributionPage']);
632 }
633
634 $contribution = &$objects['contribution'];
635 $ids['paymentProcessor'] = $paymentProcessorID;
636 $contribution->loadRelatedObjects($input, $ids);
637 $objects = array_merge($objects, $contribution->_relatedObjects);
638
639 $this->recur($input, $ids, $objects['contributionRecur'], $objects['contribution'], $isFirst);
640 }
641
642 /**
643 * Function check if transaction already exists.
644 * @param string $trxn_id
645 * @return bool|void
646 */
647 public function transactionExists($trxn_id) {
648 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
649 [
650 1 => [$trxn_id, 'String'],
651 ])
652 ) {
653 return TRUE;
654 }
655 }
656
657 }