Merge branch 'CRM-13014' of git://github.com/eileenmcnaughton/civicrm-core into pull...
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 */
35 class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
36
37 static $_paymentProcessor = NULL;
38 function __construct() {
39 parent::__construct();
40 }
41
42 function getValue($name, $abort = TRUE) {
43
44 if (!empty($_POST)) {
45 $rpInvoiceArray = array();
46 $value = NULL;
47 $rpInvoiceArray = explode('&', $_POST['rp_invoice_id']);
48 foreach ($rpInvoiceArray as $rpInvoiceValue) {
49 $rpValueArray = explode('=', $rpInvoiceValue);
50 if ($rpValueArray[0] == $name) {
51 $value = $rpValueArray[1];
52 }
53 }
54
55 if ($value == NULL && $abort) {
56 echo "Failure: Missing Parameter $name<p>";
57 exit();
58 }
59 else {
60 return $value;
61 }
62 }
63 else {
64 return NULL;
65 }
66 }
67
68 static function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
69 static $store = NULL;
70 $value = CRM_Utils_Request::retrieve($name, $type, $store,
71 FALSE, NULL, $location
72 );
73 if ($abort && $value === NULL) {
74 CRM_Core_Error::debug_log_message("Could not find an entry for $name in $location");
75 echo "Failure: Missing Parameter<p>";
76 exit();
77 }
78 return $value;
79 }
80
81 function recur(&$input, &$ids, &$objects, $first) {
82 if (!isset($input['txnType'])) {
83 CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
84 echo "Failure: Invalid parameters<p>";
85 return FALSE;
86 }
87
88 if ($input['txnType'] == 'recurring_payment' &&
89 $input['paymentStatus'] != 'Completed'
90 ) {
91 CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
92 echo "Failure: Invalid parameters<p>";
93 return FALSE;
94 }
95
96 $recur = &$objects['contributionRecur'];
97
98 // make sure the invoice ids match
99 // make sure the invoice is valid and matches what we have in
100 // the contribution record
101 if ($recur->invoice_id != $input['invoice']) {
102 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
103 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
104 return FALSE;
105 }
106
107 $now = date('YmdHis');
108
109 // fix dates that already exist
110 $dates = array('create', 'start', 'end', 'cancel', 'modified');
111 foreach ($dates as $date) {
112 $name = "{$date}_date";
113 if ($recur->$name) {
114 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
115 }
116 }
117
118 $sendNotification = FALSE;
119 $subscriptionPaymentStatus = NULL;
120 //List of Transaction Type
121 /*
122 recurring_payment_profile_created RP Profile Created
123 recurring_payment RP Sucessful Payment
124 recurring_payment_failed RP Failed Payment
125 recurring_payment_profile_cancel RP Profile Cancelled
126 recurring_payment_expired RP Profile Expired
127 recurring_payment_skipped RP Profile Skipped
128 recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
129 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
130 recurring_payment_suspended RP Profile Suspended
131 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
132 */
133
134
135 //set transaction type
136 $txnType = $_POST['txn_type'];
137 //Changes for paypal pro recurring payment
138
139 switch ($txnType) {
140 case 'recurring_payment_profile_created':
141 $recur->create_date = $now;
142 $recur->contribution_status_id = 2;
143 $recur->processor_id = $_POST['recurring_payment_id'];
144 $recur->trxn_id = $recur->processor_id;
145 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
146 $sendNotification = TRUE;
147 break;
148
149 case 'recurring_payment':
150 if ($first) {
151 $recur->start_date = $now;
152 }
153 else {
154 $recur->modified_date = $now;
155 }
156
157 //contribution installment is completed
158 if ($_POST['profile_status'] == 'Expired') {
159 $recur->contribution_status_id = 1;
160 $recur->end_date = $now;
161 $sendNotification = TRUE;
162 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
163 }
164
165 // make sure the contribution status is not done
166 // since order of ipn's is unknown
167 if ($recur->contribution_status_id != 1) {
168 $recur->contribution_status_id = 5;
169 }
170 break;
171 }
172
173 $recur->save();
174
175 if ($sendNotification) {
176 $autoRenewMembership = FALSE;
177 if ($recur->id &&
178 isset($ids['membership']) && $ids['membership']
179 ) {
180 $autoRenewMembership = TRUE;
181 }
182 //send recurring Notification email for user
183 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
184 $ids['contact'],
185 $ids['contributionPage'],
186 $recur,
187 $autoRenewMembership
188 );
189 }
190
191 if ($txnType != 'recurring_payment') {
192 return;
193 }
194
195 if (!$first) {
196 //check if this contribution transaction is already processed
197 //if not create a contribution and then get it processed
198 $contribution = new CRM_Contribute_BAO_Contribution();
199 $contribution->trxn_id = $input['trxn_id'];
200 if ($contribution->trxn_id && $contribution->find()) {
201 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
202 echo "Success: Contribution has already been handled<p>";
203 return TRUE;
204 }
205
206 $contribution->contact_id = $ids['contact'];
207 $contribution->financial_type_id = $objects['contributionType']->id;
208 $contribution->contribution_page_id = $ids['contributionPage'];
209 $contribution->contribution_recur_id = $ids['contributionRecur'];
210 $contribution->receive_date = $now;
211 $contribution->currency = $objects['contribution']->currency;
212 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
213 $contribution->amount_level = $objects['contribution']->amount_level;
214
215 $objects['contribution'] = &$contribution;
216 }
217
218 $this->single($input, $ids, $objects,
219 TRUE, $first
220 );
221 }
222
223 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
224 $contribution = &$objects['contribution'];
225
226 // make sure the invoice is valid and matches what we have in the contribution record
227 if ((!$recur) || ($recur && $first)) {
228 if ($contribution->invoice_id != $input['invoice']) {
229 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
230 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
231 return FALSE;
232 }
233 }
234 else {
235 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
236 }
237
238 if (!$recur) {
239 if ($contribution->total_amount != $input['amount']) {
240 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
241 echo "Failure: Amount values dont match between database and IPN request<p>";
242 return FALSE;
243 }
244 }
245 else {
246 $contribution->total_amount = $input['amount'];
247 }
248
249 $transaction = new CRM_Core_Transaction();
250
251 // fix for CRM-2842
252 // if ( ! $this->createContact( $input, $ids, $objects ) ) {
253 // return false;
254 // }
255
256 $participant = &$objects['participant'];
257 $membership = &$objects['membership'];
258
259 $status = $input['paymentStatus'];
260 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
261 return $this->failed($objects, $transaction);
262 }
263 elseif ($status == 'Pending') {
264 return $this->pending($objects, $transaction);
265 }
266 elseif ($status == 'Refunded' || $status == 'Reversed') {
267 return $this->cancelled($objects, $transaction);
268 }
269 elseif ($status != 'Completed') {
270 return $this->unhandled($objects, $transaction);
271 }
272
273 // check if contribution is already completed, if so we ignore this ipn
274 if ($contribution->contribution_status_id == 1) {
275 $transaction->commit();
276 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
277 echo "Success: Contribution has already been handled<p>";
278 return TRUE;
279 }
280
281 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
282 }
283
284 function main($component = 'contribute') {
285 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
286 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
287
288
289 $objects = $ids = $input = array();
290 $input['component'] = $component;
291
292 // get the contribution and contact ids from the GET params
293 $ids['contact'] = self::getValue('c', TRUE);
294 $ids['contribution'] = self::getValue('b', TRUE);
295
296 $this->getInput($input, $ids);
297
298 if ($component == 'event') {
299 $ids['event'] = self::getValue('e', TRUE);
300 $ids['participant'] = self::getValue('p', TRUE);
301 $ids['contributionRecur'] = self::getValue('r', FALSE);
302 }
303 else {
304 // get the optional ids
305 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
306 $ids['contributionRecur'] = self::getValue('r', FALSE);
307 $ids['contributionPage'] = self::getValue('p', FALSE);
308 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
309 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
310 }
311
312 if (!$ids['membership'] && $ids['contributionRecur']) {
313 $sql = "
314 SELECT m.id
315 FROM civicrm_membership m
316 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
317 WHERE m.contribution_recur_id = %2
318 LIMIT 1";
319 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
320 2 => array($ids['contributionRecur'], 'Integer'),
321 );
322 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
323 $ids['membership'] = $membershipId;
324 }
325 }
326
327 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
328 'PayPal', 'id', 'name'
329 );
330
331 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
332 return FALSE;
333 }
334
335 self::$_paymentProcessor = &$objects['paymentProcessor'];
336 if ($component == 'contribute' || $component == 'event') {
337 if ($ids['contributionRecur']) {
338 // check if first contribution is completed, else complete first contribution
339 $first = TRUE;
340 if ($objects['contribution']->contribution_status_id == 1) {
341 $first = FALSE;
342 }
343 return $this->recur($input, $ids, $objects, $first);
344 }
345 else {
346 return $this->single($input, $ids, $objects, FALSE, FALSE);
347 }
348 }
349 else {
350 return $this->single($input, $ids, $objects, FALSE, FALSE);
351 }
352 }
353
354 function getInput(&$input, &$ids) {
355
356 if (!$this->getBillingID($ids)) {
357 return FALSE;
358 }
359
360 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
361 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
362 $input['invoice'] = self::getValue('i', TRUE);
363
364 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
365 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
366
367 $billingID = $ids['billing'];
368 $lookup = array(
369 "first_name" => 'first_name',
370 "last_name" => 'last_name',
371 "street_address-{$billingID}" => 'address_street',
372 "city-{$billingID}" => 'address_city',
373 "state-{$billingID}" => 'address_state',
374 "postal_code-{$billingID}" => 'address_zip',
375 "country-{$billingID}" => 'address_country_code',
376 );
377 foreach ($lookup as $name => $paypalName) {
378 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
379 $input[$name] = $value ? $value : NULL;
380 }
381
382 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
383 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
384 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
385 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
386 }
387 }
388