Merge pull request #19044 from seamuslee001/dev_drupal_149
[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 $autoRenewMembership = FALSE;
261 if ($recur->id &&
262 isset($ids['membership']) && $ids['membership']
263 ) {
264 $autoRenewMembership = TRUE;
265 }
266 //send recurring Notification email for user
267 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
268 $ids['contact'],
269 $ids['contributionPage'],
270 $recur,
271 $autoRenewMembership
272 );
273 }
274
275 if ($txnType != 'recurring_payment') {
276 return;
277 }
278
279 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
280 $contribution->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
281
282 $this->single($input, [
283 'related_contact' => $ids['related_contact'] ?? NULL,
284 'participant' => $ids['participant'] ?? NULL,
285 'contributionRecur' => $recur->id ?? NULL,
286 ], $contribution, TRUE, $first);
287 }
288
289 /**
290 * @param array $input
291 * @param array $ids
292 * @param \CRM_Contribute_BAO_Contribution $contribution
293 * @param bool $recur
294 * @param bool $first
295 *
296 * @return void
297 * @throws \API_Exception
298 * @throws \CRM_Core_Exception
299 * @throws \CiviCRM_API3_Exception
300 * @throws \Civi\API\Exception\UnauthorizedException
301 */
302 public function single($input, $ids, $contribution, $recur = FALSE, $first = FALSE) {
303
304 // make sure the invoice is valid and matches what we have in the contribution record
305 if ((!$recur) || ($recur && $first)) {
306 if ($contribution->invoice_id != $input['invoice']) {
307 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
308 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
309 return;
310 }
311 }
312 else {
313 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
314 }
315
316 if (!$recur) {
317 if ($contribution->total_amount != $input['amount']) {
318 Civi::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
319 echo "Failure: Amount values dont match between database and IPN request<p>";
320 return;
321 }
322 }
323 else {
324 $contribution->total_amount = $input['amount'];
325 }
326
327 $status = $input['paymentStatus'];
328 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
329 Contribution::update(FALSE)->setValues([
330 'cancel_date' => 'now',
331 'contribution_status_id:name' => 'Failed',
332 ])->addWhere('id', '=', $contribution->id)->execute();
333 Civi::log()->debug("Setting contribution status to Failed");
334 return;
335 }
336 if ($status === 'Pending') {
337 Civi::log()->debug('Returning since contribution status is Pending');
338 return;
339 }
340 if ($status === 'Refunded' || $status === 'Reversed') {
341 Contribution::update(FALSE)->setValues([
342 'cancel_date' => 'now',
343 'contribution_status_id:name' => 'Cancelled',
344 ])->addWhere('id', '=', $contribution->id)->execute();
345 Civi::log()->debug("Setting contribution status to Cancelled");
346 return;
347 }
348 elseif ($status !== 'Completed') {
349 Civi::log()->debug('Returning since contribution status is not handled');
350 return;
351 }
352
353 // check if contribution is already completed, if so we ignore this ipn
354 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
355 if ($contribution->contribution_status_id == $completedStatusId) {
356 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
357 echo 'Success: Contribution has already been handled<p>';
358 return;
359 }
360
361 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $contribution);
362 }
363
364 /**
365 * Gets PaymentProcessorID for PayPal
366 *
367 * @return int
368 */
369 public function getPayPalPaymentProcessorID() {
370 // This is an unreliable method as there could be more than one instance.
371 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
372 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
373 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
374 // & call completetransaction or call fail? (which may not exist yet).
375
376 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');
377
378 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
379 'PayPal', 'id', 'name'
380 );
381 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
382 'is_test' => 0,
383 'options' => ['limit' => 1],
384 'payment_processor_type_id' => $paymentProcessorTypeID,
385 'return' => 'id',
386 ]);
387
388 }
389
390 /**
391 * This is the main function to call. It should be sufficient to instantiate the class
392 * (with the input parameters) & call this & all will be done
393 *
394 * @todo the references to POST throughout this class need to be removed
395 * @return void
396 */
397 public function main() {
398 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
399 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
400 try {
401 if ($this->_isPaymentExpress) {
402 $this->handlePaymentExpress();
403 return;
404 }
405 $objects = $ids = $input = [];
406 $this->_component = $input['component'] = self::getValue('m');
407 $input['invoice'] = self::getValue('i', TRUE);
408 // get the contribution and contact ids from the GET params
409 $ids['contact'] = self::getValue('c', TRUE);
410 $ids['contribution'] = self::getValue('b', TRUE);
411
412 $this->getInput($input);
413
414 if ($this->_component == 'event') {
415 $ids['event'] = self::getValue('e', TRUE);
416 $ids['participant'] = self::getValue('p', TRUE);
417 $ids['contributionRecur'] = self::getValue('r', FALSE);
418 }
419 else {
420 // get the optional ids
421 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
422 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
423 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
424 $ids['contributionRecur'] = self::getValue('r', FALSE);
425 $ids['contributionPage'] = self::getValue('p', FALSE);
426 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
427 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
428 }
429
430 if (!$ids['membership'] && $ids['contributionRecur']) {
431 $sql = "
432 SELECT m.id
433 FROM civicrm_membership m
434 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
435 WHERE m.contribution_recur_id = %2
436 LIMIT 1";
437 $sqlParams = [
438 1 => [$ids['contribution'], 'Integer'],
439 2 => [$ids['contributionRecur'], 'Integer'],
440 ];
441 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
442 $ids['membership'] = $membershipId;
443 }
444 }
445
446 $paymentProcessorID = CRM_Utils_Array::value('processor_id', $this->_inputParameters);
447 if (!$paymentProcessorID) {
448 $paymentProcessorID = self::getPayPalPaymentProcessorID();
449 }
450
451 // Check if the contribution exists
452 // make sure contribution exists and is valid
453 $contribution = new CRM_Contribute_BAO_Contribution();
454 $contribution->id = $ids['contribution'];
455 if (!$contribution->find(TRUE)) {
456 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)]);
457 }
458
459 // make sure contact exists and is valid
460 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
461 $contact = new CRM_Contact_BAO_Contact();
462 $contact->id = $contribution->contact_id;
463 $contact->find(TRUE);
464 if ($contact->id != $ids['contact']) {
465 // 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
466 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");
467 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
468 $ids['contact'] = $contribution->contact_id;
469 }
470
471 if (!empty($ids['contributionRecur'])) {
472 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
473 $contributionRecur->id = $ids['contributionRecur'];
474 if (!$contributionRecur->find(TRUE)) {
475 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
476 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
477 return;
478 }
479 }
480
481 $objects['contact'] = &$contact;
482 $objects['contribution'] = &$contribution;
483
484 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
485 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
486 // We don't need to worry if about removing contribution page id as it will be set later in
487 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
488 unset($ids['contributionPage']);
489 }
490
491 if (!$this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID)) {
492 return;
493 }
494
495 $input['payment_processor_id'] = $paymentProcessorID;
496
497 if ($ids['contributionRecur']) {
498 // check if first contribution is completed, else complete first contribution
499 $first = TRUE;
500 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
501 if ($objects['contribution']->contribution_status_id == $completedStatusId) {
502 $first = FALSE;
503 }
504 $this->recur($input, $ids, $objects['contributionRecur'], $objects['contribution'], $first);
505 return;
506 }
507
508 $this->single($input, [
509 'related_contact' => $ids['related_contact'] ?? NULL,
510 'participant' => $ids['participant'] ?? NULL,
511 'contributionRecur' => $ids['contributionRecur'] ?? NULL,
512 ], $objects['contribution'], FALSE, FALSE);
513 }
514 catch (CRM_Core_Exception $e) {
515 Civi::log()->debug($e->getMessage());
516 echo 'Invalid or missing data';
517 }
518 }
519
520 /**
521 * @param array $input
522 *
523 * @return void
524 * @throws CRM_Core_Exception
525 */
526 public function getInput(&$input) {
527 $billingID = CRM_Core_BAO_LocationType::getBilling();
528
529 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
530 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
531
532 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
533 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
534
535 $lookup = [
536 "first_name" => 'first_name',
537 "last_name" => 'last_name',
538 "street_address-{$billingID}" => 'address_street',
539 "city-{$billingID}" => 'address_city',
540 "state-{$billingID}" => 'address_state',
541 "postal_code-{$billingID}" => 'address_zip',
542 "country-{$billingID}" => 'address_country_code',
543 ];
544 foreach ($lookup as $name => $paypalName) {
545 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
546 $input[$name] = $value ? $value : NULL;
547 }
548
549 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
550 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
551 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
552 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
553 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
554 $input['total_amount'] = $input['amount'];
555 }
556
557 /**
558 * Handle payment express IPNs.
559 *
560 * For one off IPNS no actual response is required
561 * Recurring is more difficult as we have limited confirmation material
562 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
563 * duplicated
564 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
565 * then the quasi security of the ids array might be required - although better to
566 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
567 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
568 * only contribute is handled
569 */
570 public function handlePaymentExpress() {
571 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
572 // keep discreet
573 // also note that a lot of the complexity above could be removed if we used
574 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
575 // as membership id etc can be derived by the load objects fn
576 $objects = $ids = $input = [];
577 $isFirst = FALSE;
578 $input['invoice'] = self::getValue('i', FALSE);
579 //Avoid return in case of unit test.
580 if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
581 return;
582 }
583 $input['txnType'] = $this->retrieve('txn_type', 'String');
584 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
585 'return' => 'contact_id, id, payment_processor_id',
586 'invoice_id' => $input['invoice'],
587 ]);
588
589 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
590 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
591 }
592
593 $this->getInput($input, $ids);
594 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
595 throw new CRM_Core_Exception('This transaction has already been processed');
596 }
597
598 $ids['contact'] = $contributionRecur['contact_id'];
599 $ids['contributionRecur'] = $contributionRecur['id'];
600 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
601
602 $ids['contribution'] = $result['id'];
603 //@todo hardcoding 'pending' for now
604 $pendingStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
605 if ($result['contribution_status_id'] == $pendingStatusId) {
606 $isFirst = TRUE;
607 }
608 // arg api won't get this - fix it
609 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
610 1 => [
611 $ids['contribution'],
612 'Integer',
613 ],
614 ]);
615 // only handle component at this stage - not terribly sure how a recurring event payment would arise
616 // & suspec main function may be a victom of copy & paste
617 // membership would be an easy add - but not relevant to my customer...
618 $this->_component = $input['component'] = 'contribute';
619 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime(self::retrieve('time_created', 'String')));
620 $paymentProcessorID = $contributionRecur['payment_processor_id'];
621
622 // Check if the contribution exists
623 // make sure contribution exists and is valid
624 $contribution = new CRM_Contribute_BAO_Contribution();
625 $contribution->id = $ids['contribution'];
626 if (!$contribution->find(TRUE)) {
627 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)]);
628 }
629
630 if (!empty($ids['contributionRecur'])) {
631 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
632 $contributionRecur->id = $ids['contributionRecur'];
633 if (!$contributionRecur->find(TRUE)) {
634 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
635 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
636 return FALSE;
637 }
638 }
639
640 $objects['contribution'] = &$contribution;
641
642 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
643 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
644 // We don't need to worry if about removing contribution page id as it will be set later in
645 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
646 unset($ids['contributionPage']);
647 }
648
649 if (!$this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID)) {
650 throw new CRM_Core_Exception('Data did not validate');
651 }
652 $this->recur($input, $ids, $objects['contributionRecur'], $objects['contribution'], $isFirst);
653 }
654
655 /**
656 * Function check if transaction already exists.
657 * @param string $trxn_id
658 * @return bool|void
659 */
660 public function transactionExists($trxn_id) {
661 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
662 [
663 1 => [$trxn_id, 'String'],
664 ])
665 ) {
666 return TRUE;
667 }
668 }
669
670 }