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