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