Merge pull request #3454 from kenwest/CRM-14815
[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
214 switch ($txnType) {
215 case 'recurring_payment_profile_created':
216 $recur->create_date = $now;
217 $recur->contribution_status_id = 2;
218 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
219 $recur->trxn_id = $recur->processor_id;
220 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
221 $sendNotification = TRUE;
222 break;
223
224 case 'recurring_payment':
225 if ($first) {
226 $recur->start_date = $now;
227 }
228 else {
229 $recur->modified_date = $now;
230 }
231
232 //contribution installment is completed
233 if ($this->retrieve('profile_status', 'String') == 'Expired') {
234 $recur->contribution_status_id = 1;
235 $recur->end_date = $now;
236 $sendNotification = TRUE;
237 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
238 }
239
240 // make sure the contribution status is not done
241 // since order of ipn's is unknown
242 if ($recur->contribution_status_id != 1) {
243 $recur->contribution_status_id = 5;
244 }
245 break;
246 }
247
248 $recur->save();
249
250 if ($sendNotification) {
251 $autoRenewMembership = FALSE;
252 if ($recur->id &&
253 isset($ids['membership']) && $ids['membership']
254 ) {
255 $autoRenewMembership = TRUE;
256 }
257 //send recurring Notification email for user
258 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
259 $ids['contact'],
260 $ids['contributionPage'],
261 $recur,
262 $autoRenewMembership
263 );
264 }
265
266 if ($txnType != 'recurring_payment') {
267 return;
268 }
269
270 if (!$first) {
271 //check if this contribution transaction is already processed
272 //if not create a contribution and then get it processed
273 $contribution = new CRM_Contribute_BAO_Contribution();
274 $contribution->trxn_id = $input['trxn_id'];
275 if ($contribution->trxn_id && $contribution->find()) {
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 $contribution->contact_id = $recur->contact_id;
282 $contribution->financial_type_id = $objects['contributionType']->id;
283 $contribution->contribution_page_id = $ids['contributionPage'];
284 $contribution->contribution_recur_id = $ids['contributionRecur'];
285 $contribution->currency = $objects['contribution']->currency;
286 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
287 $contribution->amount_level = $objects['contribution']->amount_level;
288 $contribution->campaign_id = $objects['contribution']->campaign_id;
289 $objects['contribution'] = &$contribution;
290 }
291 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
292 $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])): $now;
293
294 $this->single($input, $ids, $objects,
295 TRUE, $first
296 );
297 }
298
299 /**
300 * @param $input
301 * @param $ids
302 * @param $objects
303 * @param bool $recur
304 * @param bool $first
305 */
306 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
307 $contribution = &$objects['contribution'];
308
309 // make sure the invoice is valid and matches what we have in the contribution record
310 if ((!$recur) || ($recur && $first)) {
311 if ($contribution->invoice_id != $input['invoice']) {
312 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
313 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
314 return FALSE;
315 }
316 }
317 else {
318 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
319 }
320
321 if (!$recur) {
322 if ($contribution->total_amount != $input['amount']) {
323 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
324 echo "Failure: Amount values dont match between database and IPN request<p>";
325 return FALSE;
326 }
327 }
328 else {
329 $contribution->total_amount = $input['amount'];
330 }
331
332 $transaction = new CRM_Core_Transaction();
333
334 $participant = &$objects['participant'];
335 $membership = &$objects['membership'];
336
337 $status = $input['paymentStatus'];
338 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
339 return $this->failed($objects, $transaction);
340 }
341 elseif ($status == 'Pending') {
342 return $this->pending($objects, $transaction);
343 }
344 elseif ($status == 'Refunded' || $status == 'Reversed') {
345 return $this->cancelled($objects, $transaction);
346 }
347 elseif ($status != 'Completed') {
348 return $this->unhandled($objects, $transaction);
349 }
350
351 // check if contribution is already completed, if so we ignore this ipn
352 if ($contribution->contribution_status_id == 1) {
353 $transaction->commit();
354 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
355 echo "Success: Contribution has already been handled<p>";
356 return TRUE;
357 }
358
359 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
360 }
361
362 /**
363 * This is the main function to call. It should be sufficient to instantiate the class
364 * (with the input parameters) & call this & all will be done
365 *
366 * @todo the references to POST throughout this class need to be removed
367 * @return void|boolean|Ambigous <void, boolean>
368 */
369 function main() {
370 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
371 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
372 if($this->_isPaymentExpress) {
373 $this->handlePaymentExpress();
374 return;
375 }
376 $objects = $ids = $input = array();
377 $this->_component = $input['component'] = self::getValue('m');
378 $input['invoice'] = self::getValue('i', TRUE);
379 // get the contribution and contact ids from the GET params
380 $ids['contact'] = self::getValue('c', TRUE);
381 $ids['contribution'] = self::getValue('b', TRUE);
382
383 $this->getInput($input, $ids);
384
385 if ($this->_component == 'event') {
386 $ids['event'] = self::getValue('e', TRUE);
387 $ids['participant'] = self::getValue('p', TRUE);
388 $ids['contributionRecur'] = self::getValue('r', FALSE);
389 }
390 else {
391 // get the optional ids
392 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
393 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
394 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
395 $ids['contributionRecur'] = self::getValue('r', FALSE);
396 $ids['contributionPage'] = self::getValue('p', FALSE);
397 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
398 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
399 }
400
401 if (!$ids['membership'] && $ids['contributionRecur']) {
402 $sql = "
403 SELECT m.id
404 FROM civicrm_membership m
405 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
406 WHERE m.contribution_recur_id = %2
407 LIMIT 1";
408 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
409 2 => array($ids['contributionRecur'], 'Integer'),
410 );
411 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
412 $ids['membership'] = $membershipId;
413 }
414 }
415
416 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
417 'PayPal', 'id', 'name'
418 );
419
420 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
421 return FALSE;
422 }
423
424 self::$_paymentProcessor = &$objects['paymentProcessor'];
425 //?? how on earth would we not have component be one of these?
426 // they are the only valid settings & this IPN file can't even be called without one of them
427 // grepping for this class doesn't find other paths to call this class
428 if ($this->_component == 'contribute' || $this->_component == 'event') {
429 if ($ids['contributionRecur']) {
430 // check if first contribution is completed, else complete first contribution
431 $first = TRUE;
432 if ($objects['contribution']->contribution_status_id == 1) {
433 $first = FALSE;
434 }
435 return $this->recur($input, $ids, $objects, $first);
436 }
437 else {
438 return $this->single($input, $ids, $objects, FALSE, FALSE);
439 }
440 }
441 else {
442 return $this->single($input, $ids, $objects, FALSE, FALSE);
443 }
444 }
445
446 /**
447 * @param $input
448 * @param $ids
449 *
450 * @throws CRM_Core_Exception
451 */
452 function getInput(&$input, &$ids) {
453
454 if (!$this->getBillingID($ids)) {
455 return FALSE;
456 }
457
458 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
459 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
460
461 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
462 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
463
464 $billingID = $ids['billing'];
465 $lookup = array(
466 "first_name" => 'first_name',
467 "last_name" => 'last_name',
468 "street_address-{$billingID}" => 'address_street',
469 "city-{$billingID}" => 'address_city',
470 "state-{$billingID}" => 'address_state',
471 "postal_code-{$billingID}" => 'address_zip',
472 "country-{$billingID}" => 'address_country_code',
473 );
474 foreach ($lookup as $name => $paypalName) {
475 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
476 $input[$name] = $value ? $value : NULL;
477 }
478
479 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
480 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
481 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
482 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
483 $input['payment_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
484 }
485
486 /**
487 * Handle payment express IPNs
488 * For one off IPNS no actual response is required
489 * Recurring is more difficult as we have limited confirmation material
490 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
491 * duplicated
492 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
493 * then the quasi security of the ids array might be required - although better to
494 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
495 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
496 * only contribute is handled
497 */
498 function handlePaymentExpress() {
499 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
500 // keep discreet
501 // also note that a lot of the complexity above could be removed if we used
502 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
503 // as membership id etc can be derived by the load objects fn
504 $objects = $ids = $input = array();
505 $isFirst = FALSE;
506 $input['txnType'] = $this->retrieve('txn_type', 'String');
507 if($input['txnType'] != 'recurring_payment') {
508 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
509 }
510 $input['invoice'] = self::getValue('i', FALSE);
511 $this->getInput($input, $ids);
512 if($this-> transactionExists($input['trxn_id'])) {
513 throw new CRM_Core_Exception('This transaction has already been processed');
514 }
515
516 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array('return' => 'contact_id, id', 'invoice_id' => $input['invoice']));
517 $ids['contact'] = $contributionRecur['contact_id'];
518 $ids['contributionRecur'] = $contributionRecur['id'];
519 $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice'], ));
520
521 $ids['contribution'] = $result['id'];
522 //@todo hard - coding 'pending' for now
523 if($result['contribution_status_id'] == 2) {
524 $isFirst = True;
525 }
526 // arg api won't get this - fix it
527 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(1 => array($ids['contribution'], 'Integer')));
528 // only handle component at this stage - not terribly sure how a recurring event payment would arise
529 // & suspec main function may be a victom of copy & paste
530 // membership would be an easy add - but not relevant to my customer...
531 $this->_component = $input['component'] = 'contribute';
532 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self::retrieve('time_created', 'String')));
533 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
534 'PayPal', 'id', 'name'
535 );
536
537 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
538 throw new CRM_Core_Exception('Data did not validate');
539 }
540 return $this->recur($input, $ids, $objects, $isFirst);
541 }
542
543 /**
544 * Function check if transaction already exists
545 * @param string $trxn_id
546 */
547 function transactionExists($trxn_id) {
548 if(CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
549 array(
550 1 => array($trxn_id, 'String')
551 ))) {
552 return TRUE;
553 }
554 }
555 }
556