Merge pull request #19182 from eileenmcnaughton/else
[civicrm-core.git] / CRM / Core / Payment / PayPalIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
a201e208 12use Civi\Api4\Contribution;
13
6a488035
TO
14/**
15 *
16 * @package CRM
ca5cec67 17 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
18 */
19class CRM_Core_Payment_PayPalIPN extends CRM_Core_Payment_BaseIPN {
20
b5c2afd0 21 /**
f78c9258 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
b5c2afd0 25 */
be2fb01f 26 protected $_inputParameters = [];
f78c9258 27
28 /**
29 * Constructor function.
30 *
31 * @param array $inputData
32 * Contents of HTTP REQUEST.
33 *
34 * @throws CRM_Core_Exception
35 */
36 public function __construct($inputData) {
d2803851 37 // CRM-19676
0aeed2bc
BS
38 $params = (!empty($inputData['custom'])) ?
39 array_merge($inputData, json_decode($inputData['custom'], TRUE)) :
40 $inputData;
41 $this->setInputParameters($params);
6a488035
TO
42 parent::__construct();
43 }
44
6c786a9b 45 /**
100fef9d 46 * @param string $name
d2803851 47 * @param string $type
6c786a9b
EM
48 * @param bool $abort
49 *
50 * @return mixed
d2803851 51 * @throws \CRM_Core_Exception
6c786a9b 52 */
f78c9258 53 public function retrieve($name, $type, $abort = TRUE) {
d2803851 54 $value = CRM_Utils_Type::validate(CRM_Utils_Array::value($name, $this->_inputParameters), $type, FALSE);
6a488035 55 if ($abort && $value === NULL) {
d2803851 56 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
6a488035
TO
57 }
58 return $value;
59 }
60
6c786a9b 61 /**
d2803851
MW
62 * @param array $input
63 * @param array $ids
f6973d25 64 * @param CRM_Contribute_BAO_ContributionRecur $recur
65 * @param CRM_Contribute_BAO_Contribution $contribution
d2803851
MW
66 * @param bool $first
67 *
68 * @return void
7a9ab499 69 *
d2803851
MW
70 * @throws \CRM_Core_Exception
71 * @throws \CiviCRM_API3_Exception
6c786a9b 72 */
f6973d25 73 public function recur($input, $ids, $recur, $contribution, $first) {
6a488035 74 if (!isset($input['txnType'])) {
d2803851 75 Civi::log()->debug('PayPalIPN: Could not find txn_type in input request');
6a488035 76 echo "Failure: Invalid parameters<p>";
d2803851 77 return;
6a488035
TO
78 }
79
729245ca 80 if ($input['txnType'] === 'subscr_payment' &&
81 $input['paymentStatus'] !== 'Completed'
6a488035 82 ) {
d2803851 83 Civi::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
729245ca 84 echo 'Failure: Invalid parameters<p>';
d2803851 85 return;
6a488035
TO
86 }
87
6a488035
TO
88 // make sure the invoice ids match
89 // make sure the invoice is valid and matches what we have in the contribution record
90 if ($recur->invoice_id != $input['invoice']) {
d2803851 91 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id . ').');
6a488035 92 echo "Failure: Invoice values dont match between database and IPN request<p>";
d2803851 93 return;
6a488035
TO
94 }
95
96 $now = date('YmdHis');
97
6a488035 98 $subscriptionPaymentStatus = NULL;
d2803851 99 // set transaction type
f78c9258 100 $txnType = $this->retrieve('txn_type', 'String');
d2803851 101 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
6a488035
TO
102 switch ($txnType) {
103 case 'subscr_signup':
104 $recur->create_date = $now;
d2803851
MW
105 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
106
6a488035
TO
107 $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
108 $recur->id, 'contribution_status_id'
109 );
d2803851
MW
110 if ($statusID != $contributionStatuses['In Progress']) {
111 $recur->contribution_status_id = $contributionStatuses['Pending'];
6a488035 112 }
f78c9258 113 $recur->processor_id = $this->retrieve('subscr_id', 'String');
6a488035 114 $recur->trxn_id = $recur->processor_id;
6a488035
TO
115 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
116 break;
117
118 case 'subscr_eot':
d2803851
MW
119 if ($recur->contribution_status_id != $contributionStatuses['Cancelled']) {
120 $recur->contribution_status_id = $contributionStatuses['Completed'];
6a488035
TO
121 }
122 $recur->end_date = $now;
6a488035
TO
123 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
124 break;
125
126 case 'subscr_cancel':
d2803851 127 $recur->contribution_status_id = $contributionStatuses['Cancelled'];
6a488035
TO
128 $recur->cancel_date = $now;
129 break;
130
131 case 'subscr_failed':
d2803851 132 $recur->contribution_status_id = $contributionStatuses['Failed'];
6a488035
TO
133 $recur->modified_date = $now;
134 break;
135
136 case 'subscr_modify':
d2803851 137 Civi::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id . ').');
6a488035 138 echo "Failure: We do not handle modifications to subscriptions right now<p>";
d2803851 139 return;
6a488035
TO
140
141 case 'subscr_payment':
142 if ($first) {
143 $recur->start_date = $now;
144 }
145 else {
146 $recur->modified_date = $now;
147 }
148
149 // make sure the contribution status is not done
150 // since order of ipn's is unknown
d2803851
MW
151 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
152 $recur->contribution_status_id = $contributionStatuses['In Progress'];
6a488035
TO
153 }
154 break;
155 }
156
157 $recur->save();
158
e8c64ee0 159 if (in_array($this->retrieve('txn_type', 'String'), ['subscr_signup', 'subscr_eot'])) {
6a488035
TO
160 $autoRenewMembership = FALSE;
161 if ($recur->id &&
162 isset($ids['membership']) && $ids['membership']
163 ) {
164 $autoRenewMembership = TRUE;
165 }
166
167 //send recurring Notification email for user
168 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
169 $ids['contact'],
170 $ids['contributionPage'],
171 $recur,
172 $autoRenewMembership
173 );
174 }
175
176 if ($txnType != 'subscr_payment') {
177 return;
178 }
179
180 if (!$first) {
d2803851
MW
181 // check if this contribution transaction is already processed
182 // if not create a contribution and then get it processed
6a488035 183 $contribution = new CRM_Contribute_BAO_Contribution();
bc66bc9e
PJ
184 $contribution->trxn_id = $input['trxn_id'];
185 if ($contribution->trxn_id && $contribution->find()) {
d2803851 186 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id . ')');
bc66bc9e 187 echo "Success: Contribution has already been handled<p>";
d2803851
MW
188 return;
189 }
190
191 if ($input['paymentStatus'] != 'Completed') {
192 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
bc66bc9e
PJ
193 }
194
f5bc4a2d
MW
195 // In future moving to create pending & then complete, but this OK for now.
196 // Also consider accepting 'Failed' like other processors.
197 $input['contribution_status_id'] = $contributionStatuses['Completed'];
f5bc4a2d
MW
198 $input['original_contribution_id'] = $ids['contribution'];
199 $input['contribution_recur_id'] = $ids['contributionRecur'];
200
201 civicrm_api3('Contribution', 'repeattransaction', $input);
202 return;
6a488035
TO
203 }
204
9b344b95 205 $this->single($input, [
206 'related_contact' => $ids['related_contact'] ?? NULL,
85d32733 207 'participant' => $ids['participant'] ?? NULL,
208 'contributionRecur' => $recur->id,
f6973d25 209 ], $contribution, TRUE);
6a488035
TO
210 }
211
6c786a9b 212 /**
d2803851
MW
213 * @param array $input
214 * @param array $ids
667af247 215 * @param \CRM_Contribute_BAO_Contribution $contribution
6c786a9b 216 * @param bool $recur
7a9ab499 217 *
d2803851 218 * @return void
84801709 219 * @throws \CRM_Core_Exception
220 * @throws \CiviCRM_API3_Exception
6c786a9b 221 */
667af247 222 public function single($input, $ids, $contribution, $recur = FALSE) {
6a488035
TO
223
224 // make sure the invoice is valid and matches what we have in the contribution record
175f6d95 225 if ($contribution->invoice_id != $input['invoice']) {
226 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
227 echo "Failure: Invoice values dont match between database and IPN request<p>";
228 return;
6a488035
TO
229 }
230
231 if (!$recur) {
232 if ($contribution->total_amount != $input['amount']) {
d2803851 233 Civi::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
6a488035 234 echo "Failure: Amount values dont match between database and IPN request<p>";
d2803851 235 return;
6a488035
TO
236 }
237 }
238 else {
239 $contribution->total_amount = $input['amount'];
240 }
241
6a488035 242 // check if contribution is already completed, if so we ignore this ipn
4a413eb6 243 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
d2803851 244 if ($contribution->contribution_status_id == $completedStatusId) {
d2803851 245 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id . ').');
85ce114d 246 echo 'Success: Contribution has already been handled<p>';
d2803851 247 return;
6a488035
TO
248 }
249
667af247 250 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $contribution);
6a488035
TO
251 }
252
2e2605fe
EM
253 /**
254 * Main function.
255 *
61470a1a 256 * @throws \API_Exception
d2803851 257 * @throws \CiviCRM_API3_Exception
61470a1a 258 * @throws \Civi\API\Exception\UnauthorizedException
2e2605fe 259 */
00be9182 260 public function main() {
cd0f2a34 261 try {
fcc57b56 262 $ids = $input = [];
cd0f2a34 263 $component = $this->retrieve('module', 'String');
264 $input['component'] = $component;
6a488035 265
cd0f2a34 266 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
267 $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
268 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
269 $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE);
6a488035 270
cd0f2a34 271 $this->getInput($input);
6a488035 272
cd0f2a34 273 if ($component == 'event') {
274 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
275 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
fefee636 276 }
cd0f2a34 277 else {
278 // get the optional ids
279 $ids['membership'] = $membershipID;
280 $ids['contributionRecur'] = $contributionRecurID;
281 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
282 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
283 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
284 }
285
286 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids);
287
288 Civi::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
289
290 // Debugging related to possible missing membership linkage
291 if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) {
292 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($contributionRecurID);
293 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
294 'contribution_id' => $templateContribution['id'],
fefee636 295 'membership_id' => $membershipID,
fefee636 296 ]);
cd0f2a34 297 $lineItems = civicrm_api3('LineItem', 'get', [
298 'contribution_id' => $templateContribution['id'],
299 'entity_id' => $membershipID,
300 'entity_table' => 'civicrm_membership',
301 ]);
302 Civi::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID
303 . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is '
304 . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count']
305 . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.'
306 . ' it is expected the original contribution will be linked by both entities to the membership.'
fefee636 307 );
cd0f2a34 308 if (empty($membershipPayment['count']) && empty($lineItems['count'])) {
309 Civi::log()->debug('PayPalIPN: Will attempt to compensate');
310 $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE);
311 }
312 if ($contributionRecurID) {
313 $recurLinks = civicrm_api3('ContributionRecur', 'get', [
314 'membership_id' => $membershipID,
315 'contribution_recur_id' => $contributionRecurID,
316 ]);
317 Civi::log()->debug('PayPalIPN: Membership should be linked to contribution recur record ' . $contributionRecurID
318 . ' ' . $recurLinks['count'] . 'links found'
319 );
320 }
321 }
a2921b1f 322 $contribution = new CRM_Contribute_BAO_Contribution();
323 $contribution->id = $ids['contribution'];
324 if (!$contribution->find(TRUE)) {
325 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)]);
326 }
327
328 // make sure contact exists and is valid
329 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
330 $contact = new CRM_Contact_BAO_Contact();
331 $contact->id = $contribution->contact_id;
332 $contact->find(TRUE);
333 if ($contact->id != $ids['contact']) {
334 // 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
335 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");
336 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
337 $ids['contact'] = $contribution->contact_id;
338 }
339
340 if (!empty($ids['contributionRecur'])) {
341 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
342 $contributionRecur->id = $ids['contributionRecur'];
343 if (!$contributionRecur->find(TRUE)) {
344 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
345 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
346 return FALSE;
347 }
348 }
349
a2921b1f 350 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
351 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
352 // We don't need to worry if about removing contribution page id as it will be set later in
353 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
354 unset($ids['contributionPage']);
355 }
b5f812f7 356 $ids['paymentProcessor'] = $paymentProcessorID;
357 if (!$contribution->loadRelatedObjects($input, $ids)) {
358 return;
359 }
6a488035 360
dc65872a
MW
361 $input['payment_processor_id'] = $paymentProcessorID;
362
e813005b 363 if (!empty($ids['contributionRecur'])) {
364 // check if first contribution is completed, else complete first contribution
365 $first = TRUE;
366 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
fcc57b56 367 if ($contribution->contribution_status_id == $completedStatusId) {
e813005b 368 $first = FALSE;
6a488035 369 }
fcc57b56 370 $this->recur($input, $ids, $contributionRecur, $contribution, $first);
e813005b 371 return;
6a488035 372 }
e813005b 373
a83a1f47 374 $status = $input['paymentStatus'];
375 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
61470a1a 376 Contribution::update(FALSE)->setValues([
377 'cancel_date' => 'now',
378 'contribution_status_id:name' => 'Failed',
379 ])->addWhere('id', '=', $contributionID)->execute();
380 Civi::log()->debug("Setting contribution status to Failed");
a83a1f47 381 return;
382 }
383 if ($status === 'Pending') {
384 Civi::log()->debug('Returning since contribution status is Pending');
385 return;
386 }
387 if ($status === 'Refunded' || $status === 'Reversed') {
a201e208 388 Contribution::update(FALSE)->setValues([
389 'cancel_date' => 'now',
390 'contribution_status_id:name' => 'Cancelled',
391 ])->addWhere('id', '=', $contributionID)->execute();
392 Civi::log()->debug("Setting contribution status to Cancelled");
a83a1f47 393 return;
394 }
395 if ($status !== 'Completed') {
396 Civi::log()->debug('Returning since contribution status is not handled');
397 return;
398 }
9b344b95 399 $this->single($input, [
400 'related_contact' => $ids['related_contact'] ?? NULL,
0d74d91c 401 'participant' => $ids['participant'] ?? NULL,
85d32733 402 'contributionRecur' => $contributionRecurID,
fcc57b56 403 ], $contribution);
cd0f2a34 404 }
405 catch (CRM_Core_Exception $e) {
406 Civi::log()->debug($e->getMessage());
407 echo 'Invalid or missing data';
6a488035 408 }
6a488035
TO
409 }
410
6c786a9b 411 /**
d2803851 412 * @param array $input
7a9ab499 413 *
d2803851 414 * @throws \CRM_Core_Exception
6c786a9b 415 */
41ce57e7 416 public function getInput(&$input) {
417 $billingID = CRM_Core_BAO_LocationType::getBilling();
f78c9258 418 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
419 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
420 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
421 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
422 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
6a488035 423
be2fb01f 424 $lookup = [
6a488035
TO
425 "first_name" => 'first_name',
426 "last_name" => 'last_name',
427 "street_address-{$billingID}" => 'address_street',
428 "city-{$billingID}" => 'address_city',
429 "state-{$billingID}" => 'address_state',
430 "postal_code-{$billingID}" => 'address_zip',
431 "country-{$billingID}" => 'address_country_code',
be2fb01f 432 ];
6a488035 433 foreach ($lookup as $name => $paypalName) {
f78c9258 434 $value = $this->retrieve($paypalName, 'String', FALSE);
6a488035
TO
435 $input[$name] = $value ? $value : NULL;
436 }
437
f78c9258 438 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
439 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
440 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
441 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
f5bc4a2d
MW
442
443 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
444 if (!empty($paymentDate)) {
445 $receiveDateTime = new DateTime($paymentDate);
6800eef1
JGJ
446 /**
447 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
448 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
449 */
602836ee 450 $input['receive_date'] = CRM_Utils_Date::convertDateToLocalTime($receiveDateTime);
f5bc4a2d
MW
451 }
452 }
453
f5bc4a2d
MW
454 /**
455 * Gets PaymentProcessorID for PayPal
456 *
457 * @param array $input
458 * @param array $ids
459 *
460 * @return int
461 * @throws \CRM_Core_Exception
462 * @throws \CiviCRM_API3_Exception
463 */
464 public function getPayPalPaymentProcessorID($input, $ids) {
465 // First we try and retrieve from POST params
466 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
467 if (!empty($paymentProcessorID)) {
468 return $paymentProcessorID;
469 }
470
471 // Then we try and get it from recurring contribution ID
472 if (!empty($ids['contributionRecur'])) {
be2fb01f 473 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
f5bc4a2d
MW
474 'id' => $ids['contributionRecur'],
475 'return' => ['payment_processor_id'],
be2fb01f 476 ]);
f5bc4a2d
MW
477 if (!empty($contributionRecur['payment_processor_id'])) {
478 return $contributionRecur['payment_processor_id'];
479 }
480 }
481
482 // This is an unreliable method as there could be more than one instance.
483 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
484 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
485 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
486 // & call completetransaction or call fail? (which may not exist yet).
487
488 Civi::log()->warning('Unreliable method used to get payment_processor_id for PayPal IPN - this will cause problems if you have more than one instance');
489 // Then we try and retrieve based on business email ID
490 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
491 $processorParams = [
492 'user_name' => $this->retrieve('business', 'String', FALSE),
493 'payment_processor_type_id' => $paymentProcessorTypeID,
494 'is_test' => empty($input['is_test']) ? 0 : 1,
495 'options' => ['limit' => 1],
496 'return' => ['id'],
497 ];
498 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
499 if (empty($paymentProcessorID)) {
518fa0ee 500 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
f5bc4a2d
MW
501 }
502 return $paymentProcessorID;
6a488035 503 }
96025800 504
6a488035 505}