remove a couple of unrequired lines from test
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.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_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
36
37 static $_paymentProcessor = NULL;
c8aa607b 38
39 /**
40 * Input parameters from payment processor. Store these so that
41 * the code does not need to keep retrieving from the http request
42 * @var array
43 */
44 protected $_inputParameters = array();
45
46 /**
47 * store for the variables from the invoice string
48 * @var array
49 */
50 protected $_invoiceData = array();
51
52 /**
53 * Is this a payment express transaction
54 */
55 protected $_isPaymentExpress = FALSE;
56
57 /**
58 * Are we dealing with an event an 'anything else' (contribute)
59 * @var string component
60 */
61 protected $_component = 'contribute';
62 /**
63 * constructor function
64 */
65 function __construct($inputData) {
66 $this->setInputParameters($inputData);
67 $this->setInvoiceData();
6a488035
TO
68 parent::__construct();
69 }
70
c8aa607b 71 /**
72 * function exists to get the values from the rp_invoice_id string
73 * @param string $name e.g. i, values are stored in the string with letter codes
74 * @param boolean $abort fatal if not found?
75 * @return unknown
76 */
6a488035 77 function getValue($name, $abort = TRUE) {
c8aa607b 78 if ($abort && empty($this->_invoiceData[$name])) {
79 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
6a488035
TO
80 }
81 else {
c8aa607b 82 return CRM_Utils_Array::value($name, $this->_invoiceData);
83 }
84 }
85
86 /**
87 * Set $this->_invoiceData from the input array
88 */
89 function setInvoiceData() {
90 if(empty($this->_inputParameters['rp_invoice_id'])) {
91 $this->_isPaymentExpress = TRUE;
92 return;
93 }
94 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
95 // for clarify let's also store without the single letter unreadable
96 //@todo after more refactoring we might ditch storing the one letter stuff
97 $mapping = array(
98 'i' => 'invoice_id',
99 'm' => 'component',
100 'c' => 'contact_id',
101 'b' => 'contribution_id',
102 'r' => 'contribution_recur_id',
103 'p' => 'participant_id',
104 'e' => 'event_id',
105 );
106 foreach ($rpInvoiceArray as $rpInvoiceValue) {
107 $rpValueArray = explode('=', $rpInvoiceValue);
108 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
109 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
110 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
111 // alphabet with more letters.
112 // the mode will always be resolved before the mystery p is reached
113 if($rpValueArray[1] == 'contribute') {
114 $mapping['p'] = 'contribution_page_id';
115 }
6a488035
TO
116 }
117 }
118
c8aa607b 119 /**
120 * @param string $name of variable to return
121 * @param string $type data type
122 * - String
123 * - Integer
124 * @param string $location - deprecated
125 * @param boolean $abort abort if empty
126 * @return Ambigous <mixed, NULL, value, unknown, array, number>
127 */
128 function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
129 $value = CRM_Utils_Type::validate(
130 CRM_Utils_Array::value($name, $this->_inputParameters),
131 $type,
132 FALSE
6a488035
TO
133 );
134 if ($abort && $value === NULL) {
c8aa607b 135 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
6a488035
TO
136 }
137 return $value;
138 }
139
c8aa607b 140 /**
141 * Process recurring contributions
142 * @param array $input
143 * @param array $ids
144 * @param array $objects
145 * @param boolean $first
146 * @return void|boolean
147 */
6a488035
TO
148 function recur(&$input, &$ids, &$objects, $first) {
149 if (!isset($input['txnType'])) {
150 CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
151 echo "Failure: Invalid parameters<p>";
152 return FALSE;
153 }
154
155 if ($input['txnType'] == 'recurring_payment' &&
156 $input['paymentStatus'] != 'Completed'
157 ) {
158 CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
159 echo "Failure: Invalid parameters<p>";
160 return FALSE;
161 }
162
163 $recur = &$objects['contributionRecur'];
164
165 // make sure the invoice ids match
166 // make sure the invoice is valid and matches what we have in
167 // the contribution record
168 if ($recur->invoice_id != $input['invoice']) {
169 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
170 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
171 return FALSE;
172 }
173
174 $now = date('YmdHis');
175
176 // fix dates that already exist
177 $dates = array('create', 'start', 'end', 'cancel', 'modified');
178 foreach ($dates as $date) {
179 $name = "{$date}_date";
180 if ($recur->$name) {
181 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
182 }
183 }
184
185 $sendNotification = FALSE;
186 $subscriptionPaymentStatus = NULL;
187 //List of Transaction Type
188 /*
189 recurring_payment_profile_created RP Profile Created
190 recurring_payment RP Sucessful Payment
191 recurring_payment_failed RP Failed Payment
192 recurring_payment_profile_cancel RP Profile Cancelled
193 recurring_payment_expired RP Profile Expired
194 recurring_payment_skipped RP Profile Skipped
195 recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
196 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
197 recurring_payment_suspended RP Profile Suspended
198 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
199 */
200
201
202 //set transaction type
c8aa607b 203 $txnType = $this->retrieve('txn_type', 'String');
6a488035
TO
204 //Changes for paypal pro recurring payment
205
206 switch ($txnType) {
207 case 'recurring_payment_profile_created':
208 $recur->create_date = $now;
209 $recur->contribution_status_id = 2;
c8aa607b 210 $recur->processor_id = $this->retrieve('recurring_payment_id', 'Integer');
6a488035
TO
211 $recur->trxn_id = $recur->processor_id;
212 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
213 $sendNotification = TRUE;
214 break;
215
216 case 'recurring_payment':
217 if ($first) {
218 $recur->start_date = $now;
219 }
220 else {
221 $recur->modified_date = $now;
222 }
223
224 //contribution installment is completed
c8aa607b 225 if ($this->retrieve('profile_status', 'String') == 'Expired') {
6a488035
TO
226 $recur->contribution_status_id = 1;
227 $recur->end_date = $now;
228 $sendNotification = TRUE;
229 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
230 }
231
232 // make sure the contribution status is not done
233 // since order of ipn's is unknown
234 if ($recur->contribution_status_id != 1) {
235 $recur->contribution_status_id = 5;
236 }
237 break;
238 }
239
240 $recur->save();
241
242 if ($sendNotification) {
243 $autoRenewMembership = FALSE;
244 if ($recur->id &&
245 isset($ids['membership']) && $ids['membership']
246 ) {
247 $autoRenewMembership = TRUE;
248 }
249 //send recurring Notification email for user
250 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
251 $ids['contact'],
252 $ids['contributionPage'],
253 $recur,
254 $autoRenewMembership
255 );
256 }
257
258 if ($txnType != 'recurring_payment') {
259 return;
260 }
261
262 if (!$first) {
bc66bc9e
PJ
263 //check if this contribution transaction is already processed
264 //if not create a contribution and then get it processed
6a488035 265 $contribution = new CRM_Contribute_BAO_Contribution();
bc66bc9e
PJ
266 $contribution->trxn_id = $input['trxn_id'];
267 if ($contribution->trxn_id && $contribution->find()) {
268 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
269 echo "Success: Contribution has already been handled<p>";
270 return TRUE;
271 }
272
6a488035 273 $contribution->contact_id = $ids['contact'];
94d1bc8d 274 $contribution->financial_type_id = $objects['contributionType']->id;
6a488035
TO
275 $contribution->contribution_page_id = $ids['contributionPage'];
276 $contribution->contribution_recur_id = $ids['contributionRecur'];
277 $contribution->receive_date = $now;
278 $contribution->currency = $objects['contribution']->currency;
279 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
280 $contribution->amount_level = $objects['contribution']->amount_level;
94d1bc8d
PJ
281 $contribution->honor_contact_id = $objects['contribution']->honor_contact_id;
282 $contribution->honor_type_id = $objects['contribution']->honor_type_id;
283 $contribution->campaign_id = $objects['contribution']->campaign_id;
6a488035
TO
284
285 $objects['contribution'] = &$contribution;
286 }
287
288 $this->single($input, $ids, $objects,
289 TRUE, $first
290 );
291 }
292
293 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
294 $contribution = &$objects['contribution'];
295
296 // make sure the invoice is valid and matches what we have in the contribution record
297 if ((!$recur) || ($recur && $first)) {
298 if ($contribution->invoice_id != $input['invoice']) {
299 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
300 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
301 return FALSE;
302 }
303 }
304 else {
305 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
306 }
307
308 if (!$recur) {
309 if ($contribution->total_amount != $input['amount']) {
310 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
311 echo "Failure: Amount values dont match between database and IPN request<p>";
312 return FALSE;
313 }
314 }
315 else {
316 $contribution->total_amount = $input['amount'];
317 }
318
319 $transaction = new CRM_Core_Transaction();
320
6a488035
TO
321 $participant = &$objects['participant'];
322 $membership = &$objects['membership'];
323
324 $status = $input['paymentStatus'];
325 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
326 return $this->failed($objects, $transaction);
327 }
328 elseif ($status == 'Pending') {
329 return $this->pending($objects, $transaction);
330 }
331 elseif ($status == 'Refunded' || $status == 'Reversed') {
332 return $this->cancelled($objects, $transaction);
333 }
334 elseif ($status != 'Completed') {
335 return $this->unhandled($objects, $transaction);
336 }
337
338 // check if contribution is already completed, if so we ignore this ipn
339 if ($contribution->contribution_status_id == 1) {
340 $transaction->commit();
341 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
342 echo "Success: Contribution has already been handled<p>";
343 return TRUE;
344 }
345
346 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
347 }
348
c8aa607b 349 /**
350 * This is the main function to call. It should be sufficient to instantiate the class
351 * (with the input parameters) & call this & all will be done
352 *
353 * @todo the references to POST throughout this class need to be removed
354 * @return void|boolean|Ambigous <void, boolean>
355 */
d5346e1b 356 function main() {
6a488035
TO
357 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
358 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
c8aa607b 359 if($this->_isPaymentExpress) {
360 $this->handlePaymentExpress();
361 return;
362 }
6a488035 363 $objects = $ids = $input = array();
c8aa607b 364 $this->_component = $input['component'] = self::getValue('m');
6a488035
TO
365
366 // get the contribution and contact ids from the GET params
367 $ids['contact'] = self::getValue('c', TRUE);
368 $ids['contribution'] = self::getValue('b', TRUE);
369
370 $this->getInput($input, $ids);
371
c8aa607b 372 if ($this->_component == 'event') {
6a488035
TO
373 $ids['event'] = self::getValue('e', TRUE);
374 $ids['participant'] = self::getValue('p', TRUE);
375 $ids['contributionRecur'] = self::getValue('r', FALSE);
376 }
377 else {
378 // get the optional ids
c8aa607b 379 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
380 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
6a488035
TO
381 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
382 $ids['contributionRecur'] = self::getValue('r', FALSE);
383 $ids['contributionPage'] = self::getValue('p', FALSE);
384 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
385 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
386 }
387
388 if (!$ids['membership'] && $ids['contributionRecur']) {
389 $sql = "
390 SELECT m.id
391 FROM civicrm_membership m
392INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
393 WHERE m.contribution_recur_id = %2
394 LIMIT 1";
395 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
396 2 => array($ids['contributionRecur'], 'Integer'),
397 );
398 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
399 $ids['membership'] = $membershipId;
400 }
401 }
402
403 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
404 'PayPal', 'id', 'name'
405 );
406
407 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
408 return FALSE;
409 }
410
411 self::$_paymentProcessor = &$objects['paymentProcessor'];
c8aa607b 412 //?? how on earth would we not have component be one of these?
413 // they are the only valid settings & this IPN file can't even be called without one of them
414 // grepping for this class doesn't find other paths to call this class
415 if ($this->_component == 'contribute' || $this->_component == 'event') {
6a488035
TO
416 if ($ids['contributionRecur']) {
417 // check if first contribution is completed, else complete first contribution
418 $first = TRUE;
419 if ($objects['contribution']->contribution_status_id == 1) {
420 $first = FALSE;
421 }
422 return $this->recur($input, $ids, $objects, $first);
423 }
424 else {
425 return $this->single($input, $ids, $objects, FALSE, FALSE);
426 }
427 }
428 else {
429 return $this->single($input, $ids, $objects, FALSE, FALSE);
430 }
431 }
432
433 function getInput(&$input, &$ids) {
434
435 if (!$this->getBillingID($ids)) {
436 return FALSE;
437 }
438
439 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
440 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
441 $input['invoice'] = self::getValue('i', TRUE);
442
443 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
444 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
445
446 $billingID = $ids['billing'];
447 $lookup = array(
448 "first_name" => 'first_name',
449 "last_name" => 'last_name',
450 "street_address-{$billingID}" => 'address_street',
451 "city-{$billingID}" => 'address_city',
452 "state-{$billingID}" => 'address_state',
453 "postal_code-{$billingID}" => 'address_zip',
454 "country-{$billingID}" => 'address_country_code',
455 );
456 foreach ($lookup as $name => $paypalName) {
457 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
458 $input[$name] = $value ? $value : NULL;
459 }
460
461 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
462 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
463 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
464 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
465 }
c8aa607b 466
467 /**
468 * Handle payment express IPNs
469 * For one off IPNS no actual response is required
470 * Recurring is more difficult as we have limited confirmation material
471 */
472 function handlePaymentExpress() {
473 throw new CRM_Core_Exception('Payment Express IPNS not currently handled');
474 }
6a488035
TO
475}
476