Merge pull request #19087 from civicrm/5.32
[civicrm-core.git] / CRM / Core / Payment / PayPalIPN.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_PayPalIPN 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 * Constructor function.
30 *
31 * @param array $inputData
32 * Contents of HTTP REQUEST.
33 *
34 * @throws CRM_Core_Exception
35 */
36 public function __construct($inputData) {
37 // CRM-19676
38 $params = (!empty($inputData['custom'])) ?
39 array_merge($inputData, json_decode($inputData['custom'], TRUE)) :
40 $inputData;
41 $this->setInputParameters($params);
42 parent::__construct();
43 }
44
45 /**
46 * @param string $name
47 * @param string $type
48 * @param bool $abort
49 *
50 * @return mixed
51 * @throws \CRM_Core_Exception
52 */
53 public function retrieve($name, $type, $abort = TRUE) {
54 $value = CRM_Utils_Type::validate(CRM_Utils_Array::value($name, $this->_inputParameters), $type, FALSE);
55 if ($abort && $value === NULL) {
56 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
57 }
58 return $value;
59 }
60
61 /**
62 * @param array $input
63 * @param array $ids
64 * @param CRM_Contribute_BAO_ContributionRecur $recur
65 * @param CRM_Contribute_BAO_Contribution $contribution
66 * @param bool $first
67 *
68 * @return void
69 *
70 * @throws \CRM_Core_Exception
71 * @throws \CiviCRM_API3_Exception
72 */
73 public function recur($input, $ids, $recur, $contribution, $first) {
74 if (!isset($input['txnType'])) {
75 Civi::log()->debug('PayPalIPN: Could not find txn_type in input request');
76 echo "Failure: Invalid parameters<p>";
77 return;
78 }
79
80 if ($input['txnType'] === 'subscr_payment' &&
81 $input['paymentStatus'] !== 'Completed'
82 ) {
83 Civi::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
84 echo 'Failure: Invalid parameters<p>';
85 return;
86 }
87
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']) {
91 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id . ').');
92 echo "Failure: Invoice values dont match between database and IPN request<p>";
93 return;
94 }
95
96 $now = date('YmdHis');
97
98 $subscriptionPaymentStatus = NULL;
99 // set transaction type
100 $txnType = $this->retrieve('txn_type', 'String');
101 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
102 switch ($txnType) {
103 case 'subscr_signup':
104 $recur->create_date = $now;
105 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
106
107 $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
108 $recur->id, 'contribution_status_id'
109 );
110 if ($statusID != $contributionStatuses['In Progress']) {
111 $recur->contribution_status_id = $contributionStatuses['Pending'];
112 }
113 $recur->processor_id = $this->retrieve('subscr_id', 'String');
114 $recur->trxn_id = $recur->processor_id;
115 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
116 break;
117
118 case 'subscr_eot':
119 if ($recur->contribution_status_id != $contributionStatuses['Cancelled']) {
120 $recur->contribution_status_id = $contributionStatuses['Completed'];
121 }
122 $recur->end_date = $now;
123 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
124 break;
125
126 case 'subscr_cancel':
127 $recur->contribution_status_id = $contributionStatuses['Cancelled'];
128 $recur->cancel_date = $now;
129 break;
130
131 case 'subscr_failed':
132 $recur->contribution_status_id = $contributionStatuses['Failed'];
133 $recur->modified_date = $now;
134 break;
135
136 case 'subscr_modify':
137 Civi::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id . ').');
138 echo "Failure: We do not handle modifications to subscriptions right now<p>";
139 return;
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
151 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
152 $recur->contribution_status_id = $contributionStatuses['In Progress'];
153 }
154 break;
155 }
156
157 $recur->save();
158
159 if (in_array($this->retrieve('txn_type', 'String'), ['subscr_signup', 'subscr_eot'])) {
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) {
181 // check if this contribution transaction is already processed
182 // if not create a contribution and then get it processed
183 $contribution = new CRM_Contribute_BAO_Contribution();
184 $contribution->trxn_id = $input['trxn_id'];
185 if ($contribution->trxn_id && $contribution->find()) {
186 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id . ')');
187 echo "Success: Contribution has already been handled<p>";
188 return;
189 }
190
191 if ($input['paymentStatus'] != 'Completed') {
192 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
193 }
194
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'];
198 $input['original_contribution_id'] = $ids['contribution'];
199 $input['contribution_recur_id'] = $ids['contributionRecur'];
200
201 civicrm_api3('Contribution', 'repeattransaction', $input);
202 return;
203 }
204
205 $this->single($input, [
206 'related_contact' => $ids['related_contact'] ?? NULL,
207 'participant' => $ids['participant'] ?? NULL,
208 'contributionRecur' => $recur->id,
209 ], $contribution, TRUE);
210 }
211
212 /**
213 * @param array $input
214 * @param array $ids
215 * @param \CRM_Contribute_BAO_Contribution $contribution
216 * @param bool $recur
217 *
218 * @return void
219 * @throws \CRM_Core_Exception
220 * @throws \CiviCRM_API3_Exception
221 */
222 public function single($input, $ids, $contribution, $recur = FALSE) {
223
224 // make sure the invoice is valid and matches what we have in the contribution record
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;
229 }
230
231 if (!$recur) {
232 if ($contribution->total_amount != $input['amount']) {
233 Civi::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
234 echo "Failure: Amount values dont match between database and IPN request<p>";
235 return;
236 }
237 }
238 else {
239 $contribution->total_amount = $input['amount'];
240 }
241
242 // check if contribution is already completed, if so we ignore this ipn
243 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
244 if ($contribution->contribution_status_id == $completedStatusId) {
245 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id . ').');
246 echo 'Success: Contribution has already been handled<p>';
247 return;
248 }
249
250 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $contribution);
251 }
252
253 /**
254 * Main function.
255 *
256 * @throws \API_Exception
257 * @throws \CiviCRM_API3_Exception
258 * @throws \Civi\API\Exception\UnauthorizedException
259 */
260 public function main() {
261 try {
262 $ids = $input = [];
263 $component = $this->retrieve('module', 'String');
264 $input['component'] = $component;
265
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);
270
271 $this->getInput($input);
272
273 if ($component == 'event') {
274 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
275 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
276 }
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'],
295 'membership_id' => $membershipID,
296 ]);
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.'
307 );
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 }
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
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 }
356 $ids['paymentProcessor'] = $paymentProcessorID;
357 if (!$contribution->loadRelatedObjects($input, $ids)) {
358 return;
359 }
360
361 $input['payment_processor_id'] = $paymentProcessorID;
362
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');
367 if ($contribution->contribution_status_id == $completedStatusId) {
368 $first = FALSE;
369 }
370 $this->recur($input, $ids, $contributionRecur, $contribution, $first);
371 return;
372 }
373
374 $status = $input['paymentStatus'];
375 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
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");
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') {
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");
393 return;
394 }
395 if ($status !== 'Completed') {
396 Civi::log()->debug('Returning since contribution status is not handled');
397 return;
398 }
399 $this->single($input, [
400 'related_contact' => $ids['related_contact'] ?? NULL,
401 'participant' => $ids['participant'] ?? NULL,
402 'contributionRecur' => $contributionRecurID,
403 ], $contribution);
404 }
405 catch (CRM_Core_Exception $e) {
406 Civi::log()->debug($e->getMessage());
407 echo 'Invalid or missing data';
408 }
409 }
410
411 /**
412 * @param array $input
413 *
414 * @throws \CRM_Core_Exception
415 */
416 public function getInput(&$input) {
417 $billingID = CRM_Core_BAO_LocationType::getBilling();
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);
423
424 $lookup = [
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',
432 ];
433 foreach ($lookup as $name => $paypalName) {
434 $value = $this->retrieve($paypalName, 'String', FALSE);
435 $input[$name] = $value ? $value : NULL;
436 }
437
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);
442
443 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
444 if (!empty($paymentDate)) {
445 $receiveDateTime = new DateTime($paymentDate);
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 */
450 $input['receive_date'] = CRM_Utils_Date::convertDateToLocalTime($receiveDateTime);
451 }
452 }
453
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'])) {
473 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
474 'id' => $ids['contributionRecur'],
475 'return' => ['payment_processor_id'],
476 ]);
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)) {
500 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
501 }
502 return $paymentProcessorID;
503 }
504
505 }