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