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