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