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