Merge pull request #4578 from pradpnayak/CRM-10206
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35 class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
36
37 static $_paymentProcessor = NULL;
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();
68 parent::__construct();
69 }
70
71 /**
72 * function exists to get the values from the rp_invoice_id string
73 *
74 * @param string $name e.g. i, values are stored in the string with letter codes
75 * @param boolean $abort fatal if not found?
76 *
77 * @throws CRM_Core_Exception
78 * @return unknown
79 */
80 function getValue($name, $abort = TRUE) {
81 if ($abort && empty($this->_invoiceData[$name])) {
82 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
83 }
84 else {
85 return CRM_Utils_Array::value($name, $this->_invoiceData);
86 }
87 }
88
89 /**
90 * Set $this->_invoiceData from the input array
91 */
92 function setInvoiceData() {
93 if(empty($this->_inputParameters['rp_invoice_id'])) {
94 $this->_isPaymentExpress = TRUE;
95 return;
96 }
97 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
98 // for clarify let's also store without the single letter unreadable
99 //@todo after more refactoring we might ditch storing the one letter stuff
100 $mapping = array(
101 'i' => 'invoice_id',
102 'm' => 'component',
103 'c' => 'contact_id',
104 'b' => 'contribution_id',
105 'r' => 'contribution_recur_id',
106 'p' => 'participant_id',
107 'e' => 'event_id',
108 );
109 foreach ($rpInvoiceArray as $rpInvoiceValue) {
110 $rpValueArray = explode('=', $rpInvoiceValue);
111 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
112 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
113 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
114 // alphabet with more letters.
115 // the mode will always be resolved before the mystery p is reached
116 if($rpValueArray[1] == 'contribute') {
117 $mapping['p'] = 'contribution_page_id';
118 }
119 }
120 if(empty($this->_inputParameters['component'])) {
121 $this->_isPaymentExpress = TRUE;
122 }
123 }
124
125 /**
126 * @param string $name of variable to return
127 * @param string $type data type
128 * - String
129 * - Integer
130 * @param string $location - deprecated
131 * @param boolean $abort abort if empty
132 *
133 * @throws CRM_Core_Exception
134 * @return Ambigous <mixed, NULL, value, unknown, array, number>
135 */
136 function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
137 $value = CRM_Utils_Type::validate(
138 CRM_Utils_Array::value($name, $this->_inputParameters),
139 $type,
140 FALSE
141 );
142 if ($abort && $value === NULL) {
143 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
144 }
145 return $value;
146 }
147
148 /**
149 * Process recurring contributions
150 * @param array $input
151 * @param array $ids
152 * @param array $objects
153 * @param boolean $first
154 * @return void|boolean
155 */
156 function recur(&$input, &$ids, &$objects, $first) {
157 if (!isset($input['txnType'])) {
158 CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
159 echo "Failure: Invalid parameters<p>";
160 return FALSE;
161 }
162
163 if ($input['txnType'] == 'recurring_payment' &&
164 $input['paymentStatus'] != 'Completed'
165 ) {
166 CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
167 echo "Failure: Invalid parameters<p>";
168 return FALSE;
169 }
170
171 $recur = &$objects['contributionRecur'];
172
173 // make sure the invoice ids match
174 // make sure the invoice is valid and matches what we have in
175 // the contribution record
176 if ($recur->invoice_id != $input['invoice']) {
177 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
178 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
179 return FALSE;
180 }
181
182 $now = date('YmdHis');
183
184 // fix dates that already exist
185 $dates = array('create', 'start', 'end', 'cancel', 'modified');
186 foreach ($dates as $date) {
187 $name = "{$date}_date";
188 if ($recur->$name) {
189 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
190 }
191 }
192
193 $sendNotification = FALSE;
194 $subscriptionPaymentStatus = NULL;
195 //List of Transaction Type
196 /*
197 recurring_payment_profile_created RP Profile Created
198 recurring_payment RP Sucessful Payment
199 recurring_payment_failed RP Failed Payment
200 recurring_payment_profile_cancel RP Profile Cancelled
201 recurring_payment_expired RP Profile Expired
202 recurring_payment_skipped RP Profile Skipped
203 recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
204 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
205 recurring_payment_suspended RP Profile Suspended
206 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
207 */
208
209
210 //set transaction type
211 $txnType = $this->retrieve('txn_type', 'String');
212 //Changes for paypal pro recurring payment
213 $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
214 $contributionStatuses = $contributionStatuses['values'];
215 switch ($txnType) {
216 case 'recurring_payment_profile_created':
217 if(in_array($recur->contribution_status_id, array(array_search('Pending',$contributionStatuses), array_search('In Progress',$contributionStatuses)))
218 && !empty($recur->processor_id)) {
219 echo "already handled";
220 return;
221 }
222 $recur->create_date = $now;
223 $recur->contribution_status_id = 2;
224 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
225 $recur->trxn_id = $recur->processor_id;
226 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
227 $sendNotification = TRUE;
228 break;
229
230 case 'recurring_payment':
231 if ($first) {
232 $recur->start_date = $now;
233 }
234 else {
235 $recur->modified_date = $now;
236 }
237
238 //contribution installment is completed
239 if ($this->retrieve('profile_status', 'String') == 'Expired') {
240 if(!empty($recur->end_date)) {
241 echo "already handled";
242 return;
243 }
244 $recur->contribution_status_id = 1;
245 $recur->end_date = $now;
246 $sendNotification = TRUE;
247 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
248 }
249
250 // make sure the contribution status is not done
251 // since order of ipn's is unknown
252 if ($recur->contribution_status_id != 1) {
253 $recur->contribution_status_id = 5;
254 }
255 break;
256 }
257
258 $recur->save();
259
260 if ($sendNotification) {
261 $autoRenewMembership = FALSE;
262 if ($recur->id &&
263 isset($ids['membership']) && $ids['membership']
264 ) {
265 $autoRenewMembership = TRUE;
266 }
267 //send recurring Notification email for user
268 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
269 $ids['contact'],
270 $ids['contributionPage'],
271 $recur,
272 $autoRenewMembership
273 );
274 }
275
276 if ($txnType != 'recurring_payment') {
277 return;
278 }
279
280 if (!$first) {
281 //check if this contribution transaction is already processed
282 //if not create a contribution and then get it processed
283 $contribution = new CRM_Contribute_BAO_Contribution();
284 $contribution->trxn_id = $input['trxn_id'];
285 if ($contribution->trxn_id && $contribution->find()) {
286 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
287 echo "Success: Contribution has already been handled<p>";
288 return TRUE;
289 }
290
291 $contribution->contact_id = $recur->contact_id;
292 $contribution->financial_type_id = $objects['contributionType']->id;
293 $contribution->contribution_page_id = $ids['contributionPage'];
294 $contribution->contribution_recur_id = $ids['contributionRecur'];
295 $contribution->currency = $objects['contribution']->currency;
296 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
297 $contribution->amount_level = $objects['contribution']->amount_level;
298 $contribution->campaign_id = $objects['contribution']->campaign_id;
299 $objects['contribution'] = &$contribution;
300 }
301 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
302 $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])): $now;
303
304 $this->single($input, $ids, $objects,
305 TRUE, $first
306 );
307 }
308
309 /**
310 * @param $input
311 * @param $ids
312 * @param $objects
313 * @param bool $recur
314 * @param bool $first
315 */
316 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
317 $contribution = &$objects['contribution'];
318
319 // make sure the invoice is valid and matches what we have in the contribution record
320 if ((!$recur) || ($recur && $first)) {
321 if ($contribution->invoice_id != $input['invoice']) {
322 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
323 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
324 return FALSE;
325 }
326 }
327 else {
328 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
329 }
330
331 if (!$recur) {
332 if ($contribution->total_amount != $input['amount']) {
333 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
334 echo "Failure: Amount values dont match between database and IPN request<p>";
335 return FALSE;
336 }
337 }
338 else {
339 $contribution->total_amount = $input['amount'];
340 }
341
342 $transaction = new CRM_Core_Transaction();
343
344 $participant = &$objects['participant'];
345 $membership = &$objects['membership'];
346
347 $status = $input['paymentStatus'];
348 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
349 return $this->failed($objects, $transaction);
350 }
351 elseif ($status == 'Pending') {
352 return $this->pending($objects, $transaction);
353 }
354 elseif ($status == 'Refunded' || $status == 'Reversed') {
355 return $this->cancelled($objects, $transaction);
356 }
357 elseif ($status != 'Completed') {
358 return $this->unhandled($objects, $transaction);
359 }
360
361 // check if contribution is already completed, if so we ignore this ipn
362 if ($contribution->contribution_status_id == 1) {
363 $transaction->commit();
364 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
365 echo "Success: Contribution has already been handled<p>";
366 return TRUE;
367 }
368
369 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
370 }
371
372 /**
373 * This is the main function to call. It should be sufficient to instantiate the class
374 * (with the input parameters) & call this & all will be done
375 *
376 * @todo the references to POST throughout this class need to be removed
377 * @return void|boolean|Ambigous <void, boolean>
378 */
379 function main() {
380 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
381 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
382 if($this->_isPaymentExpress) {
383 $this->handlePaymentExpress();
384 return;
385 }
386 $objects = $ids = $input = array();
387 $this->_component = $input['component'] = self::getValue('m');
388 $input['invoice'] = self::getValue('i', TRUE);
389 // get the contribution and contact ids from the GET params
390 $ids['contact'] = self::getValue('c', TRUE);
391 $ids['contribution'] = self::getValue('b', TRUE);
392
393 $this->getInput($input, $ids);
394
395 if ($this->_component == 'event') {
396 $ids['event'] = self::getValue('e', TRUE);
397 $ids['participant'] = self::getValue('p', TRUE);
398 $ids['contributionRecur'] = self::getValue('r', FALSE);
399 }
400 else {
401 // get the optional ids
402 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
403 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
404 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
405 $ids['contributionRecur'] = self::getValue('r', FALSE);
406 $ids['contributionPage'] = self::getValue('p', FALSE);
407 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
408 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
409 }
410
411 if (!$ids['membership'] && $ids['contributionRecur']) {
412 $sql = "
413 SELECT m.id
414 FROM civicrm_membership m
415 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
416 WHERE m.contribution_recur_id = %2
417 LIMIT 1";
418 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
419 2 => array($ids['contributionRecur'], 'Integer'),
420 );
421 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
422 $ids['membership'] = $membershipId;
423 }
424 }
425
426 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
427 'PayPal', 'id', 'name'
428 );
429
430 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
431 return FALSE;
432 }
433
434 self::$_paymentProcessor = &$objects['paymentProcessor'];
435 //?? how on earth would we not have component be one of these?
436 // they are the only valid settings & this IPN file can't even be called without one of them
437 // grepping for this class doesn't find other paths to call this class
438 if ($this->_component == 'contribute' || $this->_component == 'event') {
439 if ($ids['contributionRecur']) {
440 // check if first contribution is completed, else complete first contribution
441 $first = TRUE;
442 if ($objects['contribution']->contribution_status_id == 1) {
443 $first = FALSE;
444 }
445 return $this->recur($input, $ids, $objects, $first);
446 }
447 else {
448 return $this->single($input, $ids, $objects, FALSE, FALSE);
449 }
450 }
451 else {
452 return $this->single($input, $ids, $objects, FALSE, FALSE);
453 }
454 }
455
456 /**
457 * @param $input
458 * @param $ids
459 *
460 * @throws CRM_Core_Exception
461 */
462 function getInput(&$input, &$ids) {
463
464 if (!$this->getBillingID($ids)) {
465 return FALSE;
466 }
467
468 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
469 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
470
471 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
472 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
473
474 $billingID = $ids['billing'];
475 $lookup = array(
476 "first_name" => 'first_name',
477 "last_name" => 'last_name',
478 "street_address-{$billingID}" => 'address_street',
479 "city-{$billingID}" => 'address_city',
480 "state-{$billingID}" => 'address_state',
481 "postal_code-{$billingID}" => 'address_zip',
482 "country-{$billingID}" => 'address_country_code',
483 );
484 foreach ($lookup as $name => $paypalName) {
485 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
486 $input[$name] = $value ? $value : NULL;
487 }
488
489 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
490 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
491 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
492 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
493 $input['payment_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
494 }
495
496 /**
497 * Handle payment express IPNs
498 * For one off IPNS no actual response is required
499 * Recurring is more difficult as we have limited confirmation material
500 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
501 * duplicated
502 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
503 * then the quasi security of the ids array might be required - although better to
504 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
505 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
506 * only contribute is handled
507 */
508 function handlePaymentExpress() {
509 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
510 // keep discreet
511 // also note that a lot of the complexity above could be removed if we used
512 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
513 // as membership id etc can be derived by the load objects fn
514 $objects = $ids = $input = array();
515 $isFirst = FALSE;
516 $input['txnType'] = $this->retrieve('txn_type', 'String');
517 if($input['txnType'] != 'recurring_payment') {
518 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
519 }
520 $input['invoice'] = self::getValue('i', FALSE);
521 $this->getInput($input, $ids);
522 if($this-> transactionExists($input['trxn_id'])) {
523 throw new CRM_Core_Exception('This transaction has already been processed');
524 }
525
526 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array('return' => 'contact_id, id', 'invoice_id' => $input['invoice']));
527 $ids['contact'] = $contributionRecur['contact_id'];
528 $ids['contributionRecur'] = $contributionRecur['id'];
529 $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice'], ));
530
531 $ids['contribution'] = $result['id'];
532 //@todo hard - coding 'pending' for now
533 if($result['contribution_status_id'] == 2) {
534 $isFirst = True;
535 }
536 // arg api won't get this - fix it
537 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(1 => array($ids['contribution'], 'Integer')));
538 // only handle component at this stage - not terribly sure how a recurring event payment would arise
539 // & suspec main function may be a victom of copy & paste
540 // membership would be an easy add - but not relevant to my customer...
541 $this->_component = $input['component'] = 'contribute';
542 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self::retrieve('time_created', 'String')));
543 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
544 'PayPal', 'id', 'name'
545 );
546
547 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
548 throw new CRM_Core_Exception('Data did not validate');
549 }
550 return $this->recur($input, $ids, $objects, $isFirst);
551 }
552
553 /**
554 * Function check if transaction already exists
555 * @param string $trxn_id
556 */
557 function transactionExists($trxn_id) {
558 if(CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
559 array(
560 1 => array($trxn_id, 'String')
561 ))) {
562 return TRUE;
563 }
564 }
565 }
566