Merge pull request #15974 from eileenmcnaughton/ex_clean
[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 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 *
17 */
18 class CRM_Core_Payment_PayPalIPN extends CRM_Core_Payment_BaseIPN {
19
20 public static $_paymentProcessor = NULL;
21
22 /**
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
26 */
27 protected $_inputParameters = [];
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) {
38 // CRM-19676
39 $params = (!empty($inputData['custom'])) ?
40 array_merge($inputData, json_decode($inputData['custom'], TRUE)) :
41 $inputData;
42 $this->setInputParameters($params);
43 parent::__construct();
44 }
45
46 /**
47 * @param string $name
48 * @param string $type
49 * @param bool $abort
50 *
51 * @return mixed
52 * @throws \CRM_Core_Exception
53 */
54 public function retrieve($name, $type, $abort = TRUE) {
55 $value = CRM_Utils_Type::validate(CRM_Utils_Array::value($name, $this->_inputParameters), $type, FALSE);
56 if ($abort && $value === NULL) {
57 Civi::log()->debug("PayPalIPN: Could not find an entry for $name");
58 echo "Failure: Missing Parameter<p>" . CRM_Utils_Type::escape($name, 'String');
59 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
60 }
61 return $value;
62 }
63
64 /**
65 * @param array $input
66 * @param array $ids
67 * @param array $objects
68 * @param bool $first
69 *
70 * @return void
71 *
72 * @throws \CRM_Core_Exception
73 * @throws \CiviCRM_API3_Exception
74 */
75 public function recur($input, $ids, $objects, $first) {
76 if (!isset($input['txnType'])) {
77 Civi::log()->debug('PayPalIPN: Could not find txn_type in input request');
78 echo "Failure: Invalid parameters<p>";
79 return;
80 }
81
82 if ($input['txnType'] === 'subscr_payment' &&
83 $input['paymentStatus'] !== 'Completed'
84 ) {
85 Civi::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
86 echo 'Failure: Invalid parameters<p>';
87 return;
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']) {
95 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id . ').');
96 echo "Failure: Invoice values dont match between database and IPN request<p>";
97 return;
98 }
99
100 $now = date('YmdHis');
101
102 // fix dates that already exist
103 $dates = ['create', 'start', 'end', 'cancel', 'modified'];
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;
112 // set transaction type
113 $txnType = $this->retrieve('txn_type', 'String');
114 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
115 switch ($txnType) {
116 case 'subscr_signup':
117 $recur->create_date = $now;
118 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
119
120 $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
121 $recur->id, 'contribution_status_id'
122 );
123 if ($statusID != $contributionStatuses['In Progress']) {
124 $recur->contribution_status_id = $contributionStatuses['Pending'];
125 }
126 $recur->processor_id = $this->retrieve('subscr_id', 'String');
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':
133 if ($recur->contribution_status_id != $contributionStatuses['Cancelled']) {
134 $recur->contribution_status_id = $contributionStatuses['Completed'];
135 }
136 $recur->end_date = $now;
137 $sendNotification = TRUE;
138 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
139 break;
140
141 case 'subscr_cancel':
142 $recur->contribution_status_id = $contributionStatuses['Cancelled'];
143 $recur->cancel_date = $now;
144 break;
145
146 case 'subscr_failed':
147 $recur->contribution_status_id = $contributionStatuses['Failed'];
148 $recur->modified_date = $now;
149 break;
150
151 case 'subscr_modify':
152 Civi::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id . ').');
153 echo "Failure: We do not handle modifications to subscriptions right now<p>";
154 return;
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
166 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
167 $recur->contribution_status_id = $contributionStatuses['In Progress'];
168 }
169 break;
170 }
171
172 $recur->save();
173
174 if ($sendNotification) {
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) {
196 // check if this contribution transaction is already processed
197 // if not create a contribution and then get it processed
198 $contribution = new CRM_Contribute_BAO_Contribution();
199 $contribution->trxn_id = $input['trxn_id'];
200 if ($contribution->trxn_id && $contribution->find()) {
201 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id . ')');
202 echo "Success: Contribution has already been handled<p>";
203 return;
204 }
205
206 if ($input['paymentStatus'] != 'Completed') {
207 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
208 }
209
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'];
213 $input['original_contribution_id'] = $ids['contribution'];
214 $input['contribution_recur_id'] = $ids['contributionRecur'];
215
216 civicrm_api3('Contribution', 'repeattransaction', $input);
217 return;
218 }
219
220 $this->single($input, $ids, $objects,
221 TRUE, $first
222 );
223 }
224
225 /**
226 * @param array $input
227 * @param array $ids
228 * @param array $objects
229 * @param bool $recur
230 * @param bool $first
231 *
232 * @return void
233 */
234 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
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']) {
240 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
241 echo "Failure: Invoice values dont match between database and IPN request<p>";
242 return;
243 }
244 }
245 else {
246 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
247 }
248
249 if (!$recur) {
250 if ($contribution->total_amount != $input['amount']) {
251 Civi::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
252 echo "Failure: Amount values dont match between database and IPN request<p>";
253 return;
254 }
255 }
256 else {
257 $contribution->total_amount = $input['amount'];
258 }
259
260 $transaction = new CRM_Core_Transaction();
261
262 $status = $input['paymentStatus'];
263 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
264 return $this->failed($objects, $transaction);
265 }
266 elseif ($status == 'Pending') {
267 return $this->pending($objects, $transaction);
268 }
269 elseif ($status == 'Refunded' || $status == 'Reversed') {
270 return $this->cancelled($objects, $transaction);
271 }
272 elseif ($status != 'Completed') {
273 return $this->unhandled($objects, $transaction);
274 }
275
276 // check if contribution is already completed, if so we ignore this ipn
277 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
278 if ($contribution->contribution_status_id == $completedStatusId) {
279 $transaction->commit();
280 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id . ').');
281 echo "Success: Contribution has already been handled<p>";
282 return;
283 }
284
285 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
286 }
287
288 /**
289 * Main function.
290 *
291 * @throws \CRM_Core_Exception
292 * @throws \CiviCRM_API3_Exception
293 */
294 public function main() {
295 $objects = $ids = $input = [];
296 $component = $this->retrieve('module', 'String');
297 $input['component'] = $component;
298
299 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
300 $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
301 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
302 $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE);
303
304 $this->getInput($input, $ids);
305
306 if ($component == 'event') {
307 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
308 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
309 }
310 else {
311 // get the optional ids
312 $ids['membership'] = $membershipID;
313 $ids['contributionRecur'] = $contributionRecurID;
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);
317 }
318
319 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids);
320
321 Civi::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
322
323 // Debugging related to possible missing membership linkage
324 if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) {
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 }
355 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
356 return;
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;
364 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
365 if ($objects['contribution']->contribution_status_id == $completedStatusId) {
366 $first = FALSE;
367 }
368 $this->recur($input, $ids, $objects, $first);
369 return;
370 }
371 }
372 $this->single($input, $ids, $objects, FALSE, FALSE);
373 }
374
375 /**
376 * @param array $input
377 * @param array $ids
378 *
379 * @throws \CRM_Core_Exception
380 */
381 public function getInput(&$input, &$ids) {
382 if (!$this->getBillingID($ids)) {
383 return;
384 }
385
386 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
387 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
388 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
389 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
390 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
391
392 $billingID = $ids['billing'];
393 $lookup = [
394 "first_name" => 'first_name',
395 "last_name" => 'last_name',
396 "street_address-{$billingID}" => 'address_street',
397 "city-{$billingID}" => 'address_city',
398 "state-{$billingID}" => 'address_state',
399 "postal_code-{$billingID}" => 'address_zip',
400 "country-{$billingID}" => 'address_country_code',
401 ];
402 foreach ($lookup as $name => $paypalName) {
403 $value = $this->retrieve($paypalName, 'String', FALSE);
404 $input[$name] = $value ? $value : NULL;
405 }
406
407 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
408 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
409 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
410 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
411
412 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
413 if (!empty($paymentDate)) {
414 $receiveDateTime = new DateTime($paymentDate);
415 /**
416 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
417 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
418 */
419 $input['receive_date'] = CRM_Utils_Date::convertDateToLocalTime($receiveDateTime);
420 }
421 }
422
423 /**
424 * Gets PaymentProcessorID for PayPal
425 *
426 * @param array $input
427 * @param array $ids
428 *
429 * @return int
430 * @throws \CRM_Core_Exception
431 * @throws \CiviCRM_API3_Exception
432 */
433 public function getPayPalPaymentProcessorID($input, $ids) {
434 // First we try and retrieve from POST params
435 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
436 if (!empty($paymentProcessorID)) {
437 return $paymentProcessorID;
438 }
439
440 // Then we try and get it from recurring contribution ID
441 if (!empty($ids['contributionRecur'])) {
442 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
443 'id' => $ids['contributionRecur'],
444 'return' => ['payment_processor_id'],
445 ]);
446 if (!empty($contributionRecur['payment_processor_id'])) {
447 return $contributionRecur['payment_processor_id'];
448 }
449 }
450
451 // This is an unreliable method as there could be more than one instance.
452 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
453 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
454 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
455 // & call completetransaction or call fail? (which may not exist yet).
456
457 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');
458 // Then we try and retrieve based on business email ID
459 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
460 $processorParams = [
461 'user_name' => $this->retrieve('business', 'String', FALSE),
462 'payment_processor_type_id' => $paymentProcessorTypeID,
463 'is_test' => empty($input['is_test']) ? 0 : 1,
464 'options' => ['limit' => 1],
465 'return' => ['id'],
466 ];
467 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
468 if (empty($paymentProcessorID)) {
469 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
470 }
471 return $paymentProcessorID;
472 }
473
474 }