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