Merge pull request #814 from eileenmcnaughton/CRM-12642
[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 // create a contribution and then get it processed
197 $contribution = new CRM_Contribute_BAO_Contribution();
198 $contribution->contact_id = $ids['contact'];
199 $contribution->financial_type_id = $objects['contributionType']->id;
200 $contribution->contribution_page_id = $ids['contributionPage'];
201 $contribution->contribution_recur_id = $ids['contributionRecur'];
202 $contribution->receive_date = $now;
203 $contribution->currency = $objects['contribution']->currency;
204 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
205 $contribution->amount_level = $objects['contribution']->amount_level;
206 $contribution->honor_contact_id = $objects['contribution']->honor_contact_id;
207 $contribution->honor_type_id = $objects['contribution']->honor_type_id;
208 $contribution->campaign_id = $objects['contribution']->campaign_id;
209
210 $objects['contribution'] = &$contribution;
211 }
212
213 $this->single($input, $ids, $objects,
214 TRUE, $first
215 );
216 }
217
218 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
219 $contribution = &$objects['contribution'];
220
221 // make sure the invoice is valid and matches what we have in the contribution record
222 if ((!$recur) || ($recur && $first)) {
223 if ($contribution->invoice_id != $input['invoice']) {
224 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
225 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
226 return FALSE;
227 }
228 }
229 else {
230 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
231 }
232
233 if (!$recur) {
234 if ($contribution->total_amount != $input['amount']) {
235 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
236 echo "Failure: Amount values dont match between database and IPN request<p>";
237 return FALSE;
238 }
239 }
240 else {
241 $contribution->total_amount = $input['amount'];
242 }
243
244 $transaction = new CRM_Core_Transaction();
245
246 // fix for CRM-2842
247 // if ( ! $this->createContact( $input, $ids, $objects ) ) {
248 // return false;
249 // }
250
251 $participant = &$objects['participant'];
252 $membership = &$objects['membership'];
253
254 $status = $input['paymentStatus'];
255 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
256 return $this->failed($objects, $transaction);
257 }
258 elseif ($status == 'Pending') {
259 return $this->pending($objects, $transaction);
260 }
261 elseif ($status == 'Refunded' || $status == 'Reversed') {
262 return $this->cancelled($objects, $transaction);
263 }
264 elseif ($status != 'Completed') {
265 return $this->unhandled($objects, $transaction);
266 }
267
268 // check if contribution is already completed, if so we ignore this ipn
269 if ($contribution->contribution_status_id == 1) {
270 $transaction->commit();
271 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
272 echo "Success: Contribution has already been handled<p>";
273 return TRUE;
274 }
275
276 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
277 }
278
279 function main($component = 'contribute') {
280 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
281 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
282
283
284 $objects = $ids = $input = array();
285 $input['component'] = $component;
286
287 // get the contribution and contact ids from the GET params
288 $ids['contact'] = self::getValue('c', TRUE);
289 $ids['contribution'] = self::getValue('b', TRUE);
290
291 $this->getInput($input, $ids);
292
293 if ($component == 'event') {
294 $ids['event'] = self::getValue('e', TRUE);
295 $ids['participant'] = self::getValue('p', TRUE);
296 $ids['contributionRecur'] = self::getValue('r', FALSE);
297 }
298 else {
299 // get the optional ids
300 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
301 $ids['contributionRecur'] = self::getValue('r', FALSE);
302 $ids['contributionPage'] = self::getValue('p', FALSE);
303 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
304 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
305 }
306
307 if (!$ids['membership'] && $ids['contributionRecur']) {
308 $sql = "
309 SELECT m.id
310 FROM civicrm_membership m
311 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
312 WHERE m.contribution_recur_id = %2
313 LIMIT 1";
314 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
315 2 => array($ids['contributionRecur'], 'Integer'),
316 );
317 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
318 $ids['membership'] = $membershipId;
319 }
320 }
321
322 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
323 'PayPal', 'id', 'name'
324 );
325
326 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
327 return FALSE;
328 }
329
330 self::$_paymentProcessor = &$objects['paymentProcessor'];
331 if ($component == 'contribute' || $component == 'event') {
332 if ($ids['contributionRecur']) {
333 // check if first contribution is completed, else complete first contribution
334 $first = TRUE;
335 if ($objects['contribution']->contribution_status_id == 1) {
336 $first = FALSE;
337 }
338 return $this->recur($input, $ids, $objects, $first);
339 }
340 else {
341 return $this->single($input, $ids, $objects, FALSE, FALSE);
342 }
343 }
344 else {
345 return $this->single($input, $ids, $objects, FALSE, FALSE);
346 }
347 }
348
349 function getInput(&$input, &$ids) {
350
351 if (!$this->getBillingID($ids)) {
352 return FALSE;
353 }
354
355 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
356 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
357 $input['invoice'] = self::getValue('i', TRUE);
358
359 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
360 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
361
362 $billingID = $ids['billing'];
363 $lookup = array(
364 "first_name" => 'first_name',
365 "last_name" => 'last_name',
366 "street_address-{$billingID}" => 'address_street',
367 "city-{$billingID}" => 'address_city',
368 "state-{$billingID}" => 'address_state',
369 "postal_code-{$billingID}" => 'address_zip',
370 "country-{$billingID}" => 'address_country_code',
371 );
372 foreach ($lookup as $name => $paypalName) {
373 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
374 $input[$name] = $value ? $value : NULL;
375 }
376
377 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
378 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
379 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
380 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
381 }
382 }
383