Merge pull request #12534 from civicrm/5.4
[civicrm-core.git] / CRM / Core / Payment / PayPalIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
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
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 *
33 */
34class CRM_Core_Payment_PayPalIPN extends CRM_Core_Payment_BaseIPN {
35
36 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 */
f78c9258 43 protected $_inputParameters = array();
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
119 $dates = array('create', 'start', 'end', 'cancel', 'modified');
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
6a488035 226 $contribution->contact_id = $ids['contact'];
353ffa53 227 $contribution->financial_type_id = $objects['contributionType']->id;
6a488035
TO
228 $contribution->contribution_page_id = $ids['contributionPage'];
229 $contribution->contribution_recur_id = $ids['contributionRecur'];
230 $contribution->receive_date = $now;
231 $contribution->currency = $objects['contribution']->currency;
232 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
233 $contribution->amount_level = $objects['contribution']->amount_level;
94d1bc8d 234 $contribution->campaign_id = $objects['contribution']->campaign_id;
6a488035
TO
235
236 $objects['contribution'] = &$contribution;
237 }
238
239 $this->single($input, $ids, $objects,
240 TRUE, $first
241 );
242 }
243
6c786a9b 244 /**
d2803851
MW
245 * @param array $input
246 * @param array $ids
247 * @param array $objects
6c786a9b
EM
248 * @param bool $recur
249 * @param bool $first
7a9ab499 250 *
d2803851 251 * @return void
6c786a9b 252 */
d2803851 253 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
6a488035
TO
254 $contribution = &$objects['contribution'];
255
256 // make sure the invoice is valid and matches what we have in the contribution record
257 if ((!$recur) || ($recur && $first)) {
258 if ($contribution->invoice_id != $input['invoice']) {
d2803851 259 Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
6a488035 260 echo "Failure: Invoice values dont match between database and IPN request<p>";
d2803851 261 return;
6a488035
TO
262 }
263 }
264 else {
265 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
266 }
267
268 if (!$recur) {
269 if ($contribution->total_amount != $input['amount']) {
d2803851 270 Civi::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
6a488035 271 echo "Failure: Amount values dont match between database and IPN request<p>";
d2803851 272 return;
6a488035
TO
273 }
274 }
275 else {
276 $contribution->total_amount = $input['amount'];
277 }
278
279 $transaction = new CRM_Core_Transaction();
280
6a488035
TO
281 $status = $input['paymentStatus'];
282 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
283 return $this->failed($objects, $transaction);
284 }
285 elseif ($status == 'Pending') {
286 return $this->pending($objects, $transaction);
287 }
288 elseif ($status == 'Refunded' || $status == 'Reversed') {
289 return $this->cancelled($objects, $transaction);
290 }
291 elseif ($status != 'Completed') {
292 return $this->unhandled($objects, $transaction);
293 }
294
295 // check if contribution is already completed, if so we ignore this ipn
d2803851
MW
296 $completedStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
297 if ($contribution->contribution_status_id == $completedStatusId) {
6a488035 298 $transaction->commit();
d2803851 299 Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id . ').');
6a488035 300 echo "Success: Contribution has already been handled<p>";
d2803851 301 return;
6a488035
TO
302 }
303
304 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
305 }
306
2e2605fe
EM
307 /**
308 * Main function.
309 *
d2803851
MW
310 * @throws \CRM_Core_Exception
311 * @throws \CiviCRM_API3_Exception
2e2605fe 312 */
00be9182 313 public function main() {
6a488035 314 $objects = $ids = $input = array();
f78c9258 315 $component = $this->retrieve('module', 'String');
6a488035
TO
316 $input['component'] = $component;
317
f78c9258 318 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
319 $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
6a488035
TO
320
321 $this->getInput($input, $ids);
322
323 if ($component == 'event') {
f78c9258 324 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
325 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
6a488035
TO
326 }
327 else {
328 // get the optional ids
f78c9258 329 $ids['membership'] = $this->retrieve('membershipID', 'Integer', FALSE);
330 $ids['contributionRecur'] = $this->retrieve('contributionRecurID', 'Integer', FALSE);
331 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
332 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
333 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
6a488035
TO
334 }
335
b1dc9447 336 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
d8e1e2fb 337 if (empty($paymentProcessorID)) {
b1dc9447 338 $processorParams = array(
69bae647 339 'user_name' => $this->retrieve('business', 'String', FALSE),
b1dc9447 340 'payment_processor_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name'),
341 'is_test' => empty($input['is_test']) ? 0 : 1,
342 );
f78c9258 343
b1dc9447 344 $processorInfo = array();
345 if (!CRM_Financial_BAO_PaymentProcessor::retrieve($processorParams, $processorInfo)) {
346 return FALSE;
347 }
348 $paymentProcessorID = $processorInfo['id'];
a595a8f9 349 }
6a488035 350
b1dc9447 351 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
6a488035
TO
352 return FALSE;
353 }
354
355 self::$_paymentProcessor = &$objects['paymentProcessor'];
356 if ($component == 'contribute') {
357 if ($ids['contributionRecur']) {
358 // check if first contribution is completed, else complete first contribution
359 $first = TRUE;
d2803851
MW
360 $completedStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
361 if ($objects['contribution']->contribution_status_id == $completedStatusId) {
6a488035
TO
362 $first = FALSE;
363 }
d2803851
MW
364 $this->recur($input, $ids, $objects, $first);
365 return;
6a488035
TO
366 }
367 }
d2803851 368 $this->single($input, $ids, $objects, FALSE, FALSE);
6a488035
TO
369 }
370
6c786a9b 371 /**
d2803851
MW
372 * @param array $input
373 * @param array $ids
7a9ab499 374 *
d2803851 375 * @throws \CRM_Core_Exception
6c786a9b 376 */
00be9182 377 public function getInput(&$input, &$ids) {
6a488035 378 if (!$this->getBillingID($ids)) {
d2803851 379 return;
6a488035
TO
380 }
381
f78c9258 382 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
383 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
384 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
385 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
386 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
6a488035
TO
387
388 $billingID = $ids['billing'];
389 $lookup = array(
390 "first_name" => 'first_name',
391 "last_name" => 'last_name',
392 "street_address-{$billingID}" => 'address_street',
393 "city-{$billingID}" => 'address_city',
394 "state-{$billingID}" => 'address_state',
395 "postal_code-{$billingID}" => 'address_zip',
396 "country-{$billingID}" => 'address_country_code',
397 );
398 foreach ($lookup as $name => $paypalName) {
f78c9258 399 $value = $this->retrieve($paypalName, 'String', FALSE);
6a488035
TO
400 $input[$name] = $value ? $value : NULL;
401 }
402
f78c9258 403 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
404 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
405 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
406 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
6a488035 407 }
96025800 408
6a488035 409}