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