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