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