2ec2c0f509ea19697954d1cb5580d4f4694948f3
[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 // set transaction type
99 $txnType = $this->getTrxnType();
100 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
101 switch ($txnType) {
102 case 'subscr_signup':
103 $recur->create_date = $now;
104 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
105
106 $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
107 $recur->id, 'contribution_status_id'
108 );
109 if ($statusID != $contributionStatuses['In Progress']) {
110 $recur->contribution_status_id = $contributionStatuses['Pending'];
111 }
112 $recur->processor_id = $this->retrieve('subscr_id', 'String');
113 $recur->trxn_id = $recur->processor_id;
114 break;
115
116 case 'subscr_eot':
117 if ($recur->contribution_status_id != $contributionStatuses['Cancelled']) {
118 $recur->contribution_status_id = $contributionStatuses['Completed'];
119 }
120 $recur->end_date = $now;
121 break;
122
123 case 'subscr_cancel':
124 $recur->contribution_status_id = $contributionStatuses['Cancelled'];
125 $recur->cancel_date = $now;
126 break;
127
128 case 'subscr_failed':
129 $recur->contribution_status_id = $contributionStatuses['Failed'];
130 $recur->modified_date = $now;
131 break;
132
133 case 'subscr_modify':
134 Civi::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id . ').');
135 echo "Failure: We do not handle modifications to subscriptions right now<p>";
136 return;
137
138 case 'subscr_payment':
139 if ($first) {
140 $recur->start_date = $now;
141 }
142 else {
143 $recur->modified_date = $now;
144 }
145
146 // make sure the contribution status is not done
147 // since order of ipn's is unknown
148 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
149 $recur->contribution_status_id = $contributionStatuses['In Progress'];
150 }
151 break;
152 }
153
154 $recur->save();
155
156 if ($this->getFirstOrLastInSeriesStatus()) {
157 //send recurring Notification email for user
158 CRM_Contribute_BAO_ContributionPage::recurringNotify($this->getFirstOrLastInSeriesStatus(),
159 $ids['contact'],
160 $ids['contributionPage'],
161 $recur,
162 !empty($ids['membership'])
163 );
164 }
165
166 if ($txnType !== 'subscr_payment') {
167 return;
168 }
169
170 if (!$first) {
171 // check if this contribution transaction is already processed
172 // if not create a contribution and then get it processed
173 $contribution = new CRM_Contribute_BAO_Contribution();
174 $contribution->trxn_id = $input['trxn_id'];
175 if ($contribution->trxn_id && $contribution->find()) {
176 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id . ')');
177 echo "Success: Contribution has already been handled<p>";
178 return;
179 }
180
181 if ($input['paymentStatus'] !== 'Completed') {
182 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
183 }
184
185 // In future moving to create pending & then complete, but this OK for now.
186 // Also consider accepting 'Failed' like other processors.
187 $input['contribution_status_id'] = $contributionStatuses['Completed'];
188 $input['original_contribution_id'] = $ids['contribution'];
189 $input['contribution_recur_id'] = $ids['contributionRecur'];
190
191 civicrm_api3('Contribution', 'repeattransaction', $input);
192 return;
193 }
194
195 $this->single($input, [
196 'related_contact' => $ids['related_contact'] ?? NULL,
197 'participant' => $ids['participant'] ?? NULL,
198 'contributionRecur' => $recur->id,
199 ], $contribution, TRUE);
200 }
201
202 /**
203 * @param array $input
204 * @param array $ids
205 * @param \CRM_Contribute_BAO_Contribution $contribution
206 * @param bool $recur
207 *
208 * @return void
209 * @throws \CRM_Core_Exception
210 * @throws \CiviCRM_API3_Exception
211 */
212 public function single($input, $ids, $contribution, $recur = FALSE) {
213
214 // make sure the invoice is valid and matches what we have in the contribution record
215 if ($contribution->invoice_id != $input['invoice']) {
216 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
217 echo "Failure: Invoice values dont match between database and IPN request<p>";
218 return;
219 }
220
221 if (!$recur) {
222 if ($contribution->total_amount != $input['amount']) {
223 Civi::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
224 echo "Failure: Amount values dont match between database and IPN request<p>";
225 return;
226 }
227 }
228 else {
229 $contribution->total_amount = $input['amount'];
230 }
231
232 // check if contribution is already completed, if so we ignore this ipn
233 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
234 if ($contribution->contribution_status_id == $completedStatusId) {
235 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id . ').');
236 echo 'Success: Contribution has already been handled<p>';
237 return;
238 }
239
240 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $contribution);
241 }
242
243 /**
244 * Main function.
245 *
246 * @throws \API_Exception
247 * @throws \CiviCRM_API3_Exception
248 * @throws \Civi\API\Exception\UnauthorizedException
249 */
250 public function main() {
251 try {
252 $ids = $input = [];
253 $component = $this->retrieve('module', 'String');
254 $input['component'] = $component;
255
256 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
257 $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
258 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
259 $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE);
260
261 $this->getInput($input);
262
263 if ($component == 'event') {
264 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
265 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
266 }
267 else {
268 // get the optional ids
269 $ids['membership'] = $membershipID;
270 $ids['contributionRecur'] = $contributionRecurID;
271 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
272 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
273 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
274 }
275
276 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids);
277
278 Civi::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
279
280 // Debugging related to possible missing membership linkage
281 if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) {
282 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($contributionRecurID);
283 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
284 'contribution_id' => $templateContribution['id'],
285 'membership_id' => $membershipID,
286 ]);
287 $lineItems = civicrm_api3('LineItem', 'get', [
288 'contribution_id' => $templateContribution['id'],
289 'entity_id' => $membershipID,
290 'entity_table' => 'civicrm_membership',
291 ]);
292 Civi::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID
293 . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is '
294 . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count']
295 . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.'
296 . ' it is expected the original contribution will be linked by both entities to the membership.'
297 );
298 if (empty($membershipPayment['count']) && empty($lineItems['count'])) {
299 Civi::log()->debug('PayPalIPN: Will attempt to compensate');
300 $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE);
301 }
302 if ($contributionRecurID) {
303 $recurLinks = civicrm_api3('ContributionRecur', 'get', [
304 'membership_id' => $membershipID,
305 'contribution_recur_id' => $contributionRecurID,
306 ]);
307 Civi::log()->debug('PayPalIPN: Membership should be linked to contribution recur record ' . $contributionRecurID
308 . ' ' . $recurLinks['count'] . 'links found'
309 );
310 }
311 }
312 $contribution = new CRM_Contribute_BAO_Contribution();
313 $contribution->id = $ids['contribution'];
314 if (!$contribution->find(TRUE)) {
315 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)]);
316 }
317
318 // make sure contact exists and is valid
319 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
320 $contact = new CRM_Contact_BAO_Contact();
321 $contact->id = $contribution->contact_id;
322 $contact->find(TRUE);
323 if ($contact->id != $ids['contact']) {
324 // 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
325 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");
326 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
327 $ids['contact'] = $contribution->contact_id;
328 }
329
330 if (!empty($ids['contributionRecur'])) {
331 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
332 $contributionRecur->id = $ids['contributionRecur'];
333 if (!$contributionRecur->find(TRUE)) {
334 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
335 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
336 return FALSE;
337 }
338 }
339
340 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
341 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
342 // We don't need to worry if about removing contribution page id as it will be set later in
343 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
344 unset($ids['contributionPage']);
345 }
346 $ids['paymentProcessor'] = $paymentProcessorID;
347 if (!$contribution->loadRelatedObjects($input, $ids)) {
348 return;
349 }
350
351 $input['payment_processor_id'] = $paymentProcessorID;
352
353 if (!empty($ids['contributionRecur'])) {
354 // check if first contribution is completed, else complete first contribution
355 $first = TRUE;
356 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
357 if ($contribution->contribution_status_id == $completedStatusId) {
358 $first = FALSE;
359 }
360 $this->recur($input, $ids, $contributionRecur, $contribution, $first);
361 return;
362 }
363
364 $status = $input['paymentStatus'];
365 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
366 Contribution::update(FALSE)->setValues([
367 'cancel_date' => 'now',
368 'contribution_status_id:name' => 'Failed',
369 ])->addWhere('id', '=', $contributionID)->execute();
370 Civi::log()->debug("Setting contribution status to Failed");
371 return;
372 }
373 if ($status === 'Pending') {
374 Civi::log()->debug('Returning since contribution status is Pending');
375 return;
376 }
377 if ($status === 'Refunded' || $status === 'Reversed') {
378 Contribution::update(FALSE)->setValues([
379 'cancel_date' => 'now',
380 'contribution_status_id:name' => 'Cancelled',
381 ])->addWhere('id', '=', $contributionID)->execute();
382 Civi::log()->debug("Setting contribution status to Cancelled");
383 return;
384 }
385 if ($status !== 'Completed') {
386 Civi::log()->debug('Returning since contribution status is not handled');
387 return;
388 }
389 $this->single($input, [
390 'related_contact' => $ids['related_contact'] ?? NULL,
391 'participant' => $ids['participant'] ?? NULL,
392 'contributionRecur' => $contributionRecurID,
393 ], $contribution);
394 }
395 catch (CRM_Core_Exception $e) {
396 Civi::log()->debug($e->getMessage());
397 echo 'Invalid or missing data';
398 }
399 }
400
401 /**
402 * @param array $input
403 *
404 * @throws \CRM_Core_Exception
405 */
406 public function getInput(&$input) {
407 $billingID = CRM_Core_BAO_LocationType::getBilling();
408 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
409 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
410 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
411 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
412 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
413
414 $lookup = [
415 "first_name" => 'first_name',
416 "last_name" => 'last_name',
417 "street_address-{$billingID}" => 'address_street',
418 "city-{$billingID}" => 'address_city',
419 "state-{$billingID}" => 'address_state',
420 "postal_code-{$billingID}" => 'address_zip',
421 "country-{$billingID}" => 'address_country_code',
422 ];
423 foreach ($lookup as $name => $paypalName) {
424 $value = $this->retrieve($paypalName, 'String', FALSE);
425 $input[$name] = $value ? $value : NULL;
426 }
427
428 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
429 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
430 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
431 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
432
433 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
434 if (!empty($paymentDate)) {
435 $receiveDateTime = new DateTime($paymentDate);
436 /**
437 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
438 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
439 */
440 $input['receive_date'] = CRM_Utils_Date::convertDateToLocalTime($receiveDateTime);
441 }
442 }
443
444 /**
445 * Gets PaymentProcessorID for PayPal
446 *
447 * @param array $input
448 * @param array $ids
449 *
450 * @return int
451 * @throws \CRM_Core_Exception
452 * @throws \CiviCRM_API3_Exception
453 */
454 public function getPayPalPaymentProcessorID($input, $ids) {
455 // First we try and retrieve from POST params
456 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
457 if (!empty($paymentProcessorID)) {
458 return $paymentProcessorID;
459 }
460
461 // Then we try and get it from recurring contribution ID
462 if (!empty($ids['contributionRecur'])) {
463 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
464 'id' => $ids['contributionRecur'],
465 'return' => ['payment_processor_id'],
466 ]);
467 if (!empty($contributionRecur['payment_processor_id'])) {
468 return $contributionRecur['payment_processor_id'];
469 }
470 }
471
472 // This is an unreliable method as there could be more than one instance.
473 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
474 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
475 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
476 // & call completetransaction or call fail? (which may not exist yet).
477
478 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');
479 // Then we try and retrieve based on business email ID
480 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
481 $processorParams = [
482 'user_name' => $this->retrieve('business', 'String', FALSE),
483 'payment_processor_type_id' => $paymentProcessorTypeID,
484 'is_test' => empty($input['is_test']) ? 0 : 1,
485 'options' => ['limit' => 1],
486 'return' => ['id'],
487 ];
488 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
489 if (empty($paymentProcessorID)) {
490 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
491 }
492 return $paymentProcessorID;
493 }
494
495 /**
496 * @return mixed
497 * @throws \CRM_Core_Exception
498 */
499 protected function getTrxnType() {
500 $txnType = $this->retrieve('txn_type', 'String');
501 return $txnType;
502 }
503
504 /**
505 * Get status code for first or last recurring in the series.
506 *
507 * If this is the first or last then return the status code, else
508 * null.
509 *
510 * @return string|null
511 * @throws \CRM_Core_Exception
512 */
513 protected function getFirstOrLastInSeriesStatus(): ?string {
514 $subscriptionPaymentStatus = NULL;
515 if ($this->getTrxnType() === 'subscr_signup') {
516 return CRM_Core_Payment::RECURRING_PAYMENT_START;
517 }
518 if ($this->getTrxnType() === 'subscr_eot') {
519 return CRM_Core_Payment::RECURRING_PAYMENT_END;
520 }
521 return NULL;
522 }
523
524 }