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