dev/joomla#13 CiviCase: use correct caps for CRM_Core_PseudoConstant
[civicrm-core.git] / CRM / Core / Payment / PayPalIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 *
33 */
34class CRM_Core_Payment_PayPalIPN extends CRM_Core_Payment_BaseIPN {
35
518fa0ee 36 public static $_paymentProcessor = NULL;
b5c2afd0
EM
37
38 /**
f78c9258 39 * Input parameters from payment processor. Store these so that
40 * the code does not need to keep retrieving from the http request
41 * @var array
b5c2afd0 42 */
be2fb01f 43 protected $_inputParameters = [];
f78c9258 44
45 /**
46 * Constructor function.
47 *
48 * @param array $inputData
49 * Contents of HTTP REQUEST.
50 *
51 * @throws CRM_Core_Exception
52 */
53 public function __construct($inputData) {
d2803851 54 // CRM-19676
0aeed2bc
BS
55 $params = (!empty($inputData['custom'])) ?
56 array_merge($inputData, json_decode($inputData['custom'], TRUE)) :
57 $inputData;
58 $this->setInputParameters($params);
6a488035
TO
59 parent::__construct();
60 }
61
6c786a9b 62 /**
100fef9d 63 * @param string $name
d2803851 64 * @param string $type
6c786a9b
EM
65 * @param bool $abort
66 *
67 * @return mixed
d2803851 68 * @throws \CRM_Core_Exception
6c786a9b 69 */
f78c9258 70 public function retrieve($name, $type, $abort = TRUE) {
d2803851 71 $value = CRM_Utils_Type::validate(CRM_Utils_Array::value($name, $this->_inputParameters), $type, FALSE);
6a488035 72 if ($abort && $value === NULL) {
d2803851 73 Civi::log()->debug("PayPalIPN: Could not find an entry for $name");
6f9ece22 74 echo "Failure: Missing Parameter<p>" . CRM_Utils_Type::escape($name, 'String');
d2803851 75 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
6a488035
TO
76 }
77 return $value;
78 }
79
6c786a9b 80 /**
d2803851
MW
81 * @param array $input
82 * @param array $ids
83 * @param array $objects
84 * @param bool $first
85 *
86 * @return void
7a9ab499 87 *
d2803851
MW
88 * @throws \CRM_Core_Exception
89 * @throws \CiviCRM_API3_Exception
6c786a9b 90 */
00be9182 91 public function recur(&$input, &$ids, &$objects, $first) {
6a488035 92 if (!isset($input['txnType'])) {
d2803851 93 Civi::log()->debug('PayPalIPN: Could not find txn_type in input request');
6a488035 94 echo "Failure: Invalid parameters<p>";
d2803851 95 return;
6a488035
TO
96 }
97
98 if ($input['txnType'] == 'subscr_payment' &&
99 $input['paymentStatus'] != 'Completed'
100 ) {
d2803851 101 Civi::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
6a488035 102 echo "Failure: Invalid parameters<p>";
d2803851 103 return;
6a488035
TO
104 }
105
106 $recur = &$objects['contributionRecur'];
107
108 // make sure the invoice ids match
109 // make sure the invoice is valid and matches what we have in the contribution record
110 if ($recur->invoice_id != $input['invoice']) {
d2803851 111 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id . ').');
6a488035 112 echo "Failure: Invoice values dont match between database and IPN request<p>";
d2803851 113 return;
6a488035
TO
114 }
115
116 $now = date('YmdHis');
117
118 // fix dates that already exist
be2fb01f 119 $dates = ['create', 'start', 'end', 'cancel', 'modified'];
6a488035
TO
120 foreach ($dates as $date) {
121 $name = "{$date}_date";
122 if ($recur->$name) {
123 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
124 }
125 }
126 $sendNotification = FALSE;
127 $subscriptionPaymentStatus = NULL;
d2803851 128 // set transaction type
f78c9258 129 $txnType = $this->retrieve('txn_type', 'String');
d2803851 130 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
6a488035
TO
131 switch ($txnType) {
132 case 'subscr_signup':
133 $recur->create_date = $now;
d2803851
MW
134 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
135
6a488035
TO
136 $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
137 $recur->id, 'contribution_status_id'
138 );
d2803851
MW
139 if ($statusID != $contributionStatuses['In Progress']) {
140 $recur->contribution_status_id = $contributionStatuses['Pending'];
6a488035 141 }
f78c9258 142 $recur->processor_id = $this->retrieve('subscr_id', 'String');
6a488035
TO
143 $recur->trxn_id = $recur->processor_id;
144 $sendNotification = TRUE;
145 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
146 break;
147
148 case 'subscr_eot':
d2803851
MW
149 if ($recur->contribution_status_id != $contributionStatuses['Cancelled']) {
150 $recur->contribution_status_id = $contributionStatuses['Completed'];
6a488035
TO
151 }
152 $recur->end_date = $now;
153 $sendNotification = TRUE;
154 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
155 break;
156
157 case 'subscr_cancel':
d2803851 158 $recur->contribution_status_id = $contributionStatuses['Cancelled'];
6a488035
TO
159 $recur->cancel_date = $now;
160 break;
161
162 case 'subscr_failed':
d2803851 163 $recur->contribution_status_id = $contributionStatuses['Failed'];
6a488035
TO
164 $recur->modified_date = $now;
165 break;
166
167 case 'subscr_modify':
d2803851 168 Civi::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id . ').');
6a488035 169 echo "Failure: We do not handle modifications to subscriptions right now<p>";
d2803851 170 return;
6a488035
TO
171
172 case 'subscr_payment':
173 if ($first) {
174 $recur->start_date = $now;
175 }
176 else {
177 $recur->modified_date = $now;
178 }
179
180 // make sure the contribution status is not done
181 // since order of ipn's is unknown
d2803851
MW
182 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
183 $recur->contribution_status_id = $contributionStatuses['In Progress'];
6a488035
TO
184 }
185 break;
186 }
187
188 $recur->save();
189
190 if ($sendNotification) {
6a488035
TO
191 $autoRenewMembership = FALSE;
192 if ($recur->id &&
193 isset($ids['membership']) && $ids['membership']
194 ) {
195 $autoRenewMembership = TRUE;
196 }
197
198 //send recurring Notification email for user
199 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
200 $ids['contact'],
201 $ids['contributionPage'],
202 $recur,
203 $autoRenewMembership
204 );
205 }
206
207 if ($txnType != 'subscr_payment') {
208 return;
209 }
210
211 if (!$first) {
d2803851
MW
212 // check if this contribution transaction is already processed
213 // if not create a contribution and then get it processed
6a488035 214 $contribution = new CRM_Contribute_BAO_Contribution();
bc66bc9e
PJ
215 $contribution->trxn_id = $input['trxn_id'];
216 if ($contribution->trxn_id && $contribution->find()) {
d2803851 217 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id . ')');
bc66bc9e 218 echo "Success: Contribution has already been handled<p>";
d2803851
MW
219 return;
220 }
221
222 if ($input['paymentStatus'] != 'Completed') {
223 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
bc66bc9e
PJ
224 }
225
f5bc4a2d
MW
226 // In future moving to create pending & then complete, but this OK for now.
227 // Also consider accepting 'Failed' like other processors.
228 $input['contribution_status_id'] = $contributionStatuses['Completed'];
f5bc4a2d
MW
229 $input['original_contribution_id'] = $ids['contribution'];
230 $input['contribution_recur_id'] = $ids['contributionRecur'];
231
232 civicrm_api3('Contribution', 'repeattransaction', $input);
233 return;
6a488035
TO
234 }
235
236 $this->single($input, $ids, $objects,
237 TRUE, $first
238 );
239 }
240
6c786a9b 241 /**
d2803851
MW
242 * @param array $input
243 * @param array $ids
244 * @param array $objects
6c786a9b
EM
245 * @param bool $recur
246 * @param bool $first
7a9ab499 247 *
d2803851 248 * @return void
6c786a9b 249 */
d2803851 250 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
6a488035
TO
251 $contribution = &$objects['contribution'];
252
253 // make sure the invoice is valid and matches what we have in the contribution record
254 if ((!$recur) || ($recur && $first)) {
255 if ($contribution->invoice_id != $input['invoice']) {
d2803851 256 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
6a488035 257 echo "Failure: Invoice values dont match between database and IPN request<p>";
d2803851 258 return;
6a488035
TO
259 }
260 }
261 else {
262 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
263 }
264
265 if (!$recur) {
266 if ($contribution->total_amount != $input['amount']) {
d2803851 267 Civi::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
6a488035 268 echo "Failure: Amount values dont match between database and IPN request<p>";
d2803851 269 return;
6a488035
TO
270 }
271 }
272 else {
273 $contribution->total_amount = $input['amount'];
274 }
275
276 $transaction = new CRM_Core_Transaction();
277
6a488035
TO
278 $status = $input['paymentStatus'];
279 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
280 return $this->failed($objects, $transaction);
281 }
282 elseif ($status == 'Pending') {
283 return $this->pending($objects, $transaction);
284 }
285 elseif ($status == 'Refunded' || $status == 'Reversed') {
286 return $this->cancelled($objects, $transaction);
287 }
288 elseif ($status != 'Completed') {
289 return $this->unhandled($objects, $transaction);
290 }
291
292 // check if contribution is already completed, if so we ignore this ipn
d2803851
MW
293 $completedStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
294 if ($contribution->contribution_status_id == $completedStatusId) {
6a488035 295 $transaction->commit();
d2803851 296 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id . ').');
6a488035 297 echo "Success: Contribution has already been handled<p>";
d2803851 298 return;
6a488035
TO
299 }
300
301 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
302 }
303
2e2605fe
EM
304 /**
305 * Main function.
306 *
d2803851
MW
307 * @throws \CRM_Core_Exception
308 * @throws \CiviCRM_API3_Exception
2e2605fe 309 */
00be9182 310 public function main() {
be2fb01f 311 $objects = $ids = $input = [];
f78c9258 312 $component = $this->retrieve('module', 'String');
6a488035
TO
313 $input['component'] = $component;
314
f78c9258 315 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
316 $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
6a488035
TO
317
318 $this->getInput($input, $ids);
319
320 if ($component == 'event') {
f78c9258 321 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
322 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
6a488035
TO
323 }
324 else {
325 // get the optional ids
f78c9258 326 $ids['membership'] = $this->retrieve('membershipID', 'Integer', FALSE);
327 $ids['contributionRecur'] = $this->retrieve('contributionRecurID', 'Integer', FALSE);
328 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
329 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
330 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
6a488035
TO
331 }
332
f5bc4a2d 333 $paymentProcessorID = self::getPayPalPaymentProcessorID($input, $ids);
f78c9258 334
f5bc4a2d 335 Civi::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
6a488035 336
b1dc9447 337 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
f5bc4a2d 338 return;
6a488035
TO
339 }
340
341 self::$_paymentProcessor = &$objects['paymentProcessor'];
342 if ($component == 'contribute') {
343 if ($ids['contributionRecur']) {
344 // check if first contribution is completed, else complete first contribution
345 $first = TRUE;
d2803851
MW
346 $completedStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
347 if ($objects['contribution']->contribution_status_id == $completedStatusId) {
6a488035
TO
348 $first = FALSE;
349 }
d2803851
MW
350 $this->recur($input, $ids, $objects, $first);
351 return;
6a488035
TO
352 }
353 }
d2803851 354 $this->single($input, $ids, $objects, FALSE, FALSE);
6a488035
TO
355 }
356
6c786a9b 357 /**
d2803851
MW
358 * @param array $input
359 * @param array $ids
7a9ab499 360 *
d2803851 361 * @throws \CRM_Core_Exception
6c786a9b 362 */
00be9182 363 public function getInput(&$input, &$ids) {
6a488035 364 if (!$this->getBillingID($ids)) {
d2803851 365 return;
6a488035
TO
366 }
367
f78c9258 368 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
369 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
370 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
371 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
372 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
6a488035
TO
373
374 $billingID = $ids['billing'];
be2fb01f 375 $lookup = [
6a488035
TO
376 "first_name" => 'first_name',
377 "last_name" => 'last_name',
378 "street_address-{$billingID}" => 'address_street',
379 "city-{$billingID}" => 'address_city',
380 "state-{$billingID}" => 'address_state',
381 "postal_code-{$billingID}" => 'address_zip',
382 "country-{$billingID}" => 'address_country_code',
be2fb01f 383 ];
6a488035 384 foreach ($lookup as $name => $paypalName) {
f78c9258 385 $value = $this->retrieve($paypalName, 'String', FALSE);
6a488035
TO
386 $input[$name] = $value ? $value : NULL;
387 }
388
f78c9258 389 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
390 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
391 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
392 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
f5bc4a2d
MW
393
394 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
395 if (!empty($paymentDate)) {
396 $receiveDateTime = new DateTime($paymentDate);
6800eef1
JGJ
397 /**
398 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
399 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
400 */
e8780288 401 $systemTimeZone = new DateTimeZone(CRM_Core_Config::singleton()->userSystem->getTimeZoneString());
f045e2e1 402 $receiveDateTime->setTimezone($systemTimeZone);
f5bc4a2d
MW
403 $input['receive_date'] = $receiveDateTime->format('YmdHis');
404 }
405 }
406
f5bc4a2d
MW
407 /**
408 * Gets PaymentProcessorID for PayPal
409 *
410 * @param array $input
411 * @param array $ids
412 *
413 * @return int
414 * @throws \CRM_Core_Exception
415 * @throws \CiviCRM_API3_Exception
416 */
417 public function getPayPalPaymentProcessorID($input, $ids) {
418 // First we try and retrieve from POST params
419 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
420 if (!empty($paymentProcessorID)) {
421 return $paymentProcessorID;
422 }
423
424 // Then we try and get it from recurring contribution ID
425 if (!empty($ids['contributionRecur'])) {
be2fb01f 426 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
f5bc4a2d
MW
427 'id' => $ids['contributionRecur'],
428 'return' => ['payment_processor_id'],
be2fb01f 429 ]);
f5bc4a2d
MW
430 if (!empty($contributionRecur['payment_processor_id'])) {
431 return $contributionRecur['payment_processor_id'];
432 }
433 }
434
435 // This is an unreliable method as there could be more than one instance.
436 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
437 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
438 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
439 // & call completetransaction or call fail? (which may not exist yet).
440
441 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');
442 // Then we try and retrieve based on business email ID
443 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
444 $processorParams = [
445 'user_name' => $this->retrieve('business', 'String', FALSE),
446 'payment_processor_type_id' => $paymentProcessorTypeID,
447 'is_test' => empty($input['is_test']) ? 0 : 1,
448 'options' => ['limit' => 1],
449 'return' => ['id'],
450 ];
451 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
452 if (empty($paymentProcessorID)) {
518fa0ee 453 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
f5bc4a2d
MW
454 }
455 return $paymentProcessorID;
6a488035 456 }
96025800 457
6a488035 458}