INFRA-132 - Drupal.WhiteSpace.ScopeIndent.Incorrect
[civicrm-core.git] / CRM / Core / Payment / PayPalIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Core_Payment_PayPalIPN extends CRM_Core_Payment_BaseIPN {
36
37 static $_paymentProcessor = NULL;
b5c2afd0
EM
38
39 /**
40 * Constructor
41 */
00be9182 42 public function __construct() {
6a488035
TO
43 parent::__construct();
44 }
45
6c786a9b 46 /**
100fef9d 47 * @param string $name
6c786a9b
EM
48 * @param $type
49 * @param string $location
50 * @param bool $abort
51 *
52 * @return mixed
53 */
00be9182 54 public static function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
6a488035
TO
55 static $store = NULL;
56 $value = CRM_Utils_Request::retrieve($name, $type, $store,
57 FALSE, NULL, $location
58 );
59 if ($abort && $value === NULL) {
60 CRM_Core_Error::debug_log_message("Could not find an entry for $name in $location");
61 echo "Failure: Missing Parameter<p>";
62 exit();
63 }
64 return $value;
65 }
66
6c786a9b
EM
67 /**
68 * @param $input
69 * @param $ids
70 * @param $objects
71 * @param $first
72 */
00be9182 73 public function recur(&$input, &$ids, &$objects, $first) {
6a488035
TO
74 if (!isset($input['txnType'])) {
75 CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
76 echo "Failure: Invalid parameters<p>";
77 return FALSE;
78 }
79
80 if ($input['txnType'] == 'subscr_payment' &&
81 $input['paymentStatus'] != 'Completed'
82 ) {
83 CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
84 echo "Failure: Invalid parameters<p>";
85 return FALSE;
86 }
87
88 $recur = &$objects['contributionRecur'];
89
90 // make sure the invoice ids match
91 // make sure the invoice is valid and matches what we have in the contribution record
92 if ($recur->invoice_id != $input['invoice']) {
93 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
94 echo "Failure: Invoice values dont match between database and IPN request<p>";
95 return FALSE;
96 }
97
98 $now = date('YmdHis');
99
100 // fix dates that already exist
101 $dates = array('create', 'start', 'end', 'cancel', 'modified');
102 foreach ($dates as $date) {
103 $name = "{$date}_date";
104 if ($recur->$name) {
105 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
106 }
107 }
108 $sendNotification = FALSE;
109 $subscriptionPaymentStatus = NULL;
110 //set transaction type
111 $txnType = $_POST['txn_type'];
112 switch ($txnType) {
113 case 'subscr_signup':
114 $recur->create_date = $now;
115 //some times subscr_signup response come after the
116 //subscr_payment and set to pending mode.
117 $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
118 $recur->id, 'contribution_status_id'
119 );
120 if ($statusID != 5) {
121 $recur->contribution_status_id = 2;
122 }
123 $recur->processor_id = $_POST['subscr_id'];
124 $recur->trxn_id = $recur->processor_id;
125 $sendNotification = TRUE;
126 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
127 break;
128
129 case 'subscr_eot':
130 if ($recur->contribution_status_id != 3) {
131 $recur->contribution_status_id = 1;
132 }
133 $recur->end_date = $now;
134 $sendNotification = TRUE;
135 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
136 break;
137
138 case 'subscr_cancel':
139 $recur->contribution_status_id = 3;
140 $recur->cancel_date = $now;
141 break;
142
143 case 'subscr_failed':
144 $recur->contribution_status_id = 4;
145 $recur->modified_date = $now;
146 break;
147
148 case 'subscr_modify':
149 CRM_Core_Error::debug_log_message("We do not handle modifications to subscriptions right now");
150 echo "Failure: We do not handle modifications to subscriptions right now<p>";
151 return FALSE;
152
153 case 'subscr_payment':
154 if ($first) {
155 $recur->start_date = $now;
156 }
157 else {
158 $recur->modified_date = $now;
159 }
160
161 // make sure the contribution status is not done
162 // since order of ipn's is unknown
163 if ($recur->contribution_status_id != 1) {
164 $recur->contribution_status_id = 5;
165 }
166 break;
167 }
168
169 $recur->save();
170
171 if ($sendNotification) {
172
173 $autoRenewMembership = FALSE;
174 if ($recur->id &&
175 isset($ids['membership']) && $ids['membership']
176 ) {
177 $autoRenewMembership = TRUE;
178 }
179
180 //send recurring Notification email for user
181 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
182 $ids['contact'],
183 $ids['contributionPage'],
184 $recur,
185 $autoRenewMembership
186 );
187 }
188
189 if ($txnType != 'subscr_payment') {
190 return;
191 }
192
193 if (!$first) {
bc66bc9e
PJ
194 //check if this contribution transaction is already processed
195 //if not create a contribution and then get it processed
6a488035 196 $contribution = new CRM_Contribute_BAO_Contribution();
bc66bc9e
PJ
197 $contribution->trxn_id = $input['trxn_id'];
198 if ($contribution->trxn_id && $contribution->find()) {
199 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
200 echo "Success: Contribution has already been handled<p>";
201 return TRUE;
202 }
203
6a488035 204 $contribution->contact_id = $ids['contact'];
353ffa53 205 $contribution->financial_type_id = $objects['contributionType']->id;
6a488035
TO
206 $contribution->contribution_page_id = $ids['contributionPage'];
207 $contribution->contribution_recur_id = $ids['contributionRecur'];
208 $contribution->receive_date = $now;
209 $contribution->currency = $objects['contribution']->currency;
210 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
211 $contribution->amount_level = $objects['contribution']->amount_level;
94d1bc8d 212 $contribution->campaign_id = $objects['contribution']->campaign_id;
6a488035
TO
213
214 $objects['contribution'] = &$contribution;
215 }
216
217 $this->single($input, $ids, $objects,
218 TRUE, $first
219 );
220 }
221
6c786a9b
EM
222 /**
223 * @param $input
224 * @param $ids
225 * @param $objects
226 * @param bool $recur
227 * @param bool $first
228 */
8d7a9d07 229 public function single(
f9f40af3 230 &$input, &$ids, &$objects,
6a488035
TO
231 $recur = FALSE,
232 $first = FALSE
233 ) {
234 $contribution = &$objects['contribution'];
235
236 // make sure the invoice is valid and matches what we have in the contribution record
237 if ((!$recur) || ($recur && $first)) {
238 if ($contribution->invoice_id != $input['invoice']) {
239 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
240 echo "Failure: Invoice values dont match between database and IPN request<p>";
241 return FALSE;
242 }
243 }
244 else {
245 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
246 }
247
248 if (!$recur) {
249 if ($contribution->total_amount != $input['amount']) {
250 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
251 echo "Failure: Amount values dont match between database and IPN request<p>";
252 return FALSE;
253 }
254 }
255 else {
256 $contribution->total_amount = $input['amount'];
257 }
258
259 $transaction = new CRM_Core_Transaction();
260
6a488035
TO
261 $participant = &$objects['participant'];
262 $membership = &$objects['membership'];
263
264 $status = $input['paymentStatus'];
265 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
266 return $this->failed($objects, $transaction);
267 }
268 elseif ($status == 'Pending') {
269 return $this->pending($objects, $transaction);
270 }
271 elseif ($status == 'Refunded' || $status == 'Reversed') {
272 return $this->cancelled($objects, $transaction);
273 }
274 elseif ($status != 'Completed') {
275 return $this->unhandled($objects, $transaction);
276 }
277
278 // check if contribution is already completed, if so we ignore this ipn
279 if ($contribution->contribution_status_id == 1) {
280 $transaction->commit();
281 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
282 echo "Success: Contribution has already been handled<p>";
283 return TRUE;
284 }
285
286 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
287 }
288
00be9182 289 public function main() {
2aa397bc 290 //@todo - this could be refactored like PayPalProIPN & a test could be added
6a488035
TO
291
292 $objects = $ids = $input = array();
d5346e1b 293 $component = CRM_Utils_Array::value('module', $_GET);
6a488035
TO
294 $input['component'] = $component;
295
296 // get the contribution and contact ids from the GET params
297 $ids['contact'] = self::retrieve('contactID', 'Integer', 'GET', TRUE);
298 $ids['contribution'] = self::retrieve('contributionID', 'Integer', 'GET', TRUE);
299
300 $this->getInput($input, $ids);
301
302 if ($component == 'event') {
303 $ids['event'] = self::retrieve('eventID', 'Integer', 'GET', TRUE);
304 $ids['participant'] = self::retrieve('participantID', 'Integer', 'GET', TRUE);
305 }
306 else {
307 // get the optional ids
308 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
309 $ids['contributionRecur'] = self::retrieve('contributionRecurID', 'Integer', 'GET', FALSE);
310 $ids['contributionPage'] = self::retrieve('contributionPageID', 'Integer', 'GET', FALSE);
311 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
312 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
313 }
314
315 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
316 'PayPal_Standard', 'id', 'name'
317 );
318
319 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
320 return FALSE;
321 }
322
323 self::$_paymentProcessor = &$objects['paymentProcessor'];
324 if ($component == 'contribute') {
325 if ($ids['contributionRecur']) {
326 // check if first contribution is completed, else complete first contribution
327 $first = TRUE;
328 if ($objects['contribution']->contribution_status_id == 1) {
329 $first = FALSE;
330 }
331 return $this->recur($input, $ids, $objects, $first);
332 }
333 else {
334 return $this->single($input, $ids, $objects, FALSE, FALSE);
335 }
336 }
337 else {
338 return $this->single($input, $ids, $objects, FALSE, FALSE);
339 }
340 }
341
6c786a9b
EM
342 /**
343 * @param $input
344 * @param $ids
345 */
00be9182 346 public function getInput(&$input, &$ids) {
6a488035
TO
347 if (!$this->getBillingID($ids)) {
348 return FALSE;
349 }
350
351 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
352 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
353 $input['invoice'] = self::retrieve('invoice', 'String', 'POST', TRUE);
354 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
355 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
356
357 $billingID = $ids['billing'];
358 $lookup = array(
359 "first_name" => 'first_name',
360 "last_name" => 'last_name',
361 "street_address-{$billingID}" => 'address_street',
362 "city-{$billingID}" => 'address_city',
363 "state-{$billingID}" => 'address_state',
364 "postal_code-{$billingID}" => 'address_zip',
365 "country-{$billingID}" => 'address_country_code',
366 );
367 foreach ($lookup as $name => $paypalName) {
368 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
369 $input[$name] = $value ? $value : NULL;
370 }
371
353ffa53 372 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
6a488035
TO
373 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
374 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
353ffa53 375 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
6a488035 376 }
96025800 377
6a488035 378}