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