Merge pull request #24115 from kcristiano/5.52-token
[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 use Civi\Api4\Contribution;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19 class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
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 * Recurring contribution ID.
42 *
43 * @var int|null
44 */
45 protected $contributionRecurID;
46
47 /**
48 * Recurring contribution object.
49 *
50 * @var \CRM_Contribute_BAO_ContributionRecur
51 */
52 protected $contributionRecurObject;
53
54 /**
55 * Contribution object.
56 *
57 * @var \CRM_Contribute_BAO_Contribution
58 */
59 protected $contributionObject;
60 /**
61 * Contribution ID.
62 *
63 * @var int
64 */
65 protected $contributionID;
66
67 /**
68 * Get the recurring contribution ID, if any.
69 *
70 * @return int|null
71 *
72 * @throws \CRM_Core_Exception
73 */
74 public function getContributionRecurID(): ?int {
75 if (!$this->contributionRecurID && $this->getValue('r', FALSE)) {
76 $this->contributionRecurID = (int) $this->getValue('r', FALSE);
77 }
78 return $this->contributionRecurID;
79 }
80
81 /**
82 * Get the relevant contribution ID.
83 *
84 * This is the contribution being paid or the original in the
85 * recurring series.
86 *
87 * @return int
88 *
89 * @throws \CRM_Core_Exception
90 */
91 protected function getContributionID(): int {
92 if (!$this->contributionID && $this->getValue('b', TRUE)) {
93 $this->contributionID = (int) $this->getValue('b', TRUE);
94 }
95 return $this->contributionID;
96 }
97
98 /**
99 * @param int|null $contributionRecurID
100 */
101 public function setContributionRecurID(?int $contributionRecurID): void {
102 $this->contributionRecurID = $contributionRecurID;
103 }
104
105 /**
106 * Set contribution ID.
107 *
108 * @param int $contributionID
109 */
110 public function setContributionID(int $contributionID): void {
111 $this->contributionID = $contributionID;
112 }
113
114 /**
115 * Component.
116 *
117 * Are we dealing with an event an 'anything else' (contribute).
118 *
119 * @var string
120 */
121 protected $_component = 'contribute';
122
123 /**
124 * Constructor function.
125 *
126 * @param array $inputData
127 * Contents of HTTP REQUEST.
128 *
129 * @throws CRM_Core_Exception
130 */
131 public function __construct($inputData) {
132 $this->setInputParameters($inputData);
133 $this->setInvoiceData();
134 parent::__construct();
135 }
136
137 /**
138 * get the values from the rp_invoice_id string.
139 *
140 * @param string $name
141 * E.g. i, values are stored in the string with letter codes.
142 * @param bool $abort
143 * Throw exception if not found
144 *
145 * @throws CRM_Core_Exception
146 * @return mixed
147 */
148 public function getValue($name, $abort = TRUE) {
149 if ($abort && empty($this->_invoiceData[$name])) {
150 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
151 }
152 else {
153 return $this->_invoiceData[$name] ?? NULL;
154 }
155 }
156
157 /**
158 * Set $this->_invoiceData from the input array
159 */
160 public function setInvoiceData() {
161 if (empty($this->_inputParameters['rp_invoice_id'])) {
162 $this->_isPaymentExpress = TRUE;
163 return;
164 }
165 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
166 // for clarify let's also store without the single letter unreadable
167 //@todo after more refactoring we might ditch storing the one letter stuff
168 $mapping = [
169 'i' => 'invoice_id',
170 'm' => 'component',
171 'c' => 'contact_id',
172 'b' => 'contribution_id',
173 'r' => 'contribution_recur_id',
174 'p' => 'participant_id',
175 'e' => 'event_id',
176 ];
177 foreach ($rpInvoiceArray as $rpInvoiceValue) {
178 $rpValueArray = explode('=', $rpInvoiceValue);
179 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
180 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
181 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
182 // alphabet with more letters.
183 // the mode will always be resolved before the mystery p is reached
184 if ($rpValueArray[1] === 'contribute') {
185 $mapping['p'] = 'contribution_page_id';
186 }
187 }
188 if (empty($this->_inputParameters['component'])) {
189 $this->_isPaymentExpress = TRUE;
190 }
191 }
192
193 /**
194 * @param string $name
195 * Of variable to return.
196 * @param string $type
197 * Data type.
198 * - String
199 * - Integer
200 * @param string $location
201 * Deprecated.
202 * @param bool $abort
203 * Abort if empty.
204 *
205 * @throws CRM_Core_Exception
206 * @return mixed
207 */
208 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
209 $value = CRM_Utils_Type::validate(
210 CRM_Utils_Array::value($name, $this->_inputParameters),
211 $type,
212 FALSE
213 );
214 if ($abort && $value === NULL) {
215 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
216 }
217 return $value;
218 }
219
220 /**
221 * Process recurring contributions.
222 *
223 * @param array $input
224 *
225 * @throws \API_Exception
226 * @throws \CRM_Core_Exception
227 * @throws \CiviCRM_API3_Exception
228 * @throws \Civi\API\Exception\UnauthorizedException
229 */
230 public function recur(array $input): void {
231 // check if first contribution is completed, else complete first contribution
232 $first = !$this->isContributionCompleted();
233 $recur = $this->getContributionRecurObject();
234 if (!isset($input['txnType'])) {
235 Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
236 echo 'Failure: Invalid parameters<p>';
237 return;
238 }
239
240 // make sure the invoice ids match
241 // make sure the invoice is valid and matches what we have in
242 // the contribution record
243 if ($recur->invoice_id != $input['invoice']) {
244 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']);
245 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . " input is " . $input['invoice'];
246 return;
247 }
248
249 $now = date('YmdHis');
250
251 $sendNotification = FALSE;
252 $subscriptionPaymentStatus = NULL;
253 //List of Transaction Type
254 /*
255 recurring_payment_profile_created RP Profile Created
256 recurring_payment RP Successful Payment
257 recurring_payment_failed RP Failed Payment
258 recurring_payment_profile_cancel RP Profile Cancelled
259 recurring_payment_expired RP Profile Expired
260 recurring_payment_skipped RP Profile Skipped
261 recurring_payment_outstanding_payment RP Successful Outstanding Payment
262 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
263 recurring_payment_suspended RP Profile Suspended
264 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
265 */
266
267 //set transaction type
268 $txnType = $this->retrieve('txn_type', 'String');
269 //Changes for paypal pro recurring payment
270 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
271 switch ($txnType) {
272 case 'recurring_payment_profile_created':
273 if (in_array($recur->contribution_status_id, [
274 $contributionStatuses['Pending'],
275 $contributionStatuses['In Progress'],
276 ])
277 && !empty($recur->processor_id)
278 ) {
279 echo "already handled";
280 return;
281 }
282 $recur->create_date = $now;
283 $recur->contribution_status_id = $contributionStatuses['Pending'];
284 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
285 $recur->trxn_id = $recur->processor_id;
286 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
287 $sendNotification = TRUE;
288 break;
289
290 case 'recurring_payment':
291 if (!$first) {
292 if ($input['paymentStatus'] !== 'Completed') {
293 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
294 }
295
296 // In future moving to create pending & then complete, but this OK for now.
297 // Also consider accepting 'Failed' like other processors.
298 $input['contribution_status_id'] = $contributionStatuses['Completed'];
299 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
300 $input['original_contribution_id'] = $this->getContributionID();
301 $input['contribution_recur_id'] = $this->getContributionRecurID();
302
303 civicrm_api3('Contribution', 'repeattransaction', $input);
304 return;
305 }
306
307 //contribution installment is completed
308 if ($this->retrieve('profile_status', 'String') == 'Expired') {
309 if (!empty($recur->end_date)) {
310 echo "already handled";
311 return;
312 }
313 $recur->contribution_status_id = $contributionStatuses['Completed'];
314 $recur->end_date = $now;
315 $sendNotification = TRUE;
316 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
317 }
318
319 break;
320 }
321
322 $recur->save();
323
324 if ($sendNotification) {
325 //send recurring Notification email for user
326 CRM_Contribute_BAO_ContributionPage::recurringNotify(
327 $this->getContributionID(),
328 $subscriptionPaymentStatus,
329 $recur
330 );
331 }
332
333 if ($txnType !== 'recurring_payment') {
334 return;
335 }
336
337 $this->single($input);
338 }
339
340 /**
341 * @param array $input
342 *
343 * @return void
344 * @throws \API_Exception
345 * @throws \CRM_Core_Exception
346 * @throws \CiviCRM_API3_Exception
347 */
348 protected function single(array $input): void {
349
350 // make sure the invoice is valid and matches what we have in the contribution record
351 if (!$this->isContributionCompleted()) {
352 if ($this->getContributionObject()->invoice_id !== $input['invoice']) {
353 throw new CRM_Core_Exception('PayPalProIPN: Invoice values dont match between database and IPN request.');
354 }
355 if (!$this->getContributionRecurID() && $this->getContributionObject()->total_amount != $input['amount']) {
356 throw new CRM_Core_Exception('PayPalProIPN: Amount values dont match between database and IPN request.');
357 }
358 }
359
360 $status = $input['paymentStatus'];
361 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
362 Contribution::update(FALSE)->setValues([
363 'cancel_date' => 'now',
364 'contribution_status_id:name' => 'Failed',
365 ])->addWhere('id', '=', $this->getContributionID())->execute();
366 Civi::log()->debug('Setting contribution status to Failed');
367 return;
368 }
369 if ($status === 'Pending') {
370 Civi::log()->debug('Returning since contribution status is Pending');
371 return;
372 }
373 if ($status === 'Refunded' || $status === 'Reversed') {
374 Contribution::update(FALSE)->setValues([
375 'cancel_date' => 'now',
376 'contribution_status_id:name' => 'Cancelled',
377 ])->addWhere('id', '=', $this->getContributionID())->execute();
378 Civi::log()->debug('Setting contribution status to Cancelled');
379 return;
380 }
381 if ($status !== 'Completed') {
382 Civi::log()->debug('Returning since contribution status is not handled');
383 return;
384 }
385
386 if ($this->isContributionCompleted()) {
387 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
388 echo 'Success: Contribution has already been handled<p>';
389 return;
390 }
391
392 CRM_Contribute_BAO_Contribution::completeOrder($input, $this->getContributionRecurID(), $this->getContributionID());
393 }
394
395 /**
396 * Gets PaymentProcessorID for PayPal
397 *
398 * @return int
399 */
400 public function getPayPalPaymentProcessorID() {
401 // This is an unreliable method as there could be more than one instance.
402 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
403 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
404 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
405 // & call completetransaction or call fail? (which may not exist yet).
406
407 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');
408
409 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
410 'PayPal', 'id', 'name'
411 );
412 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
413 'is_test' => 0,
414 'options' => ['limit' => 1],
415 'payment_processor_type_id' => $paymentProcessorTypeID,
416 'return' => 'id',
417 ]);
418
419 }
420
421 /**
422 * This is the main function to call. It should be sufficient to instantiate the class
423 * (with the input parameters) & call this & all will be done
424 *
425 * @todo the references to POST throughout this class need to be removed
426 * @return void
427 */
428 public function main(): void {
429 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
430 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
431 $input = [];
432 try {
433 if ($this->_isPaymentExpress) {
434 $this->handlePaymentExpress();
435 return;
436 }
437 if ($this->getValue('m') === 'event') {
438 // Validate required params.
439 $this->getValue('e');
440 $this->getValue('p');
441 }
442 $input['invoice'] = $this->getValue('i');
443 if ($this->getContributionObject()->contact_id !== $this->getContactID()) {
444 // If the ids do not match then it is possible the contact id in the IPN has been merged into another contact which is why we use the contact_id from the contribution
445 CRM_Core_Error::debug_log_message('Contact ID in IPN ' . $this->getContactID() . ' not found but contact_id found in contribution ' . $this->getContributionID() . ' used instead');
446 echo 'WARNING: Could not find contact record: ' . $this->getContactID() . '<p>';
447 }
448
449 $this->getInput($input);
450 $input['payment_processor_id'] = $this->_inputParameters['processor_id'] ?? $this->getPayPalPaymentProcessorID();
451
452 if ($this->getContributionRecurID()) {
453 $this->recur($input);
454 return;
455 }
456
457 $this->single($input);
458 }
459 catch (Exception $e) {
460 Civi::log()->debug($e->getMessage() . ' input {input}', ['input' => $input]);
461 echo 'Invalid or missing data';
462 }
463 }
464
465 /**
466 * @param array $input
467 *
468 * @return void
469 * @throws CRM_Core_Exception
470 */
471 public function getInput(&$input) {
472 $billingID = CRM_Core_BAO_LocationType::getBilling();
473
474 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
475 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
476
477 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
478 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
479
480 $lookup = [
481 "first_name" => 'first_name',
482 "last_name" => 'last_name',
483 "street_address-{$billingID}" => 'address_street',
484 "city-{$billingID}" => 'address_city',
485 "state-{$billingID}" => 'address_state',
486 "postal_code-{$billingID}" => 'address_zip',
487 "country-{$billingID}" => 'address_country_code',
488 ];
489 foreach ($lookup as $name => $paypalName) {
490 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
491 $input[$name] = $value ? $value : NULL;
492 }
493
494 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
495 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
496 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
497 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
498 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
499 $input['total_amount'] = $input['amount'];
500 }
501
502 /**
503 * Handle payment express IPNs.
504 *
505 * For one off IPNS no actual response is required
506 * Recurring is more difficult as we have limited confirmation material
507 * lets look up invoice id in recur_contribution & rely on the unique
508 * transaction id to ensure no duplicated this may not be acceptable to all
509 * sites - e.g. if they are shipping or delivering something in return then
510 * the quasi security of the ids array might be required - although better to
511 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
512 * but let's assume knowledge on invoice id & schedule is enough for now esp
513 * for donations only contribute is handled
514 *
515 * @throws \API_Exception
516 * @throws \CRM_Core_Exception
517 * @throws \CiviCRM_API3_Exception
518 */
519 public function handlePaymentExpress(): void {
520 $input = ['invoice' => $this->getValue('i', FALSE)];
521 //Avoid return in case of unit test.
522 if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
523 return;
524 }
525 $input['txnType'] = $this->retrieve('txn_type', 'String');
526 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
527 'return' => 'contact_id, id, payment_processor_id',
528 'invoice_id' => $input['invoice'],
529 ]);
530 $this->setContributionRecurID((int) $contributionRecur['id']);
531
532 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
533 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
534 }
535
536 $this->getInput($input);
537 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
538 throw new CRM_Core_Exception('This transaction has already been processed');
539 }
540 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
541 $this->setContributionID((int) $result['id']);
542 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime($this->retrieve('time_created', 'String')));
543 $this->recur($input);
544 }
545
546 /**
547 * Function check if transaction already exists.
548 * @param string $trxn_id
549 * @return bool|void
550 */
551 public function transactionExists($trxn_id) {
552 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
553 [
554 1 => [$trxn_id, 'String'],
555 ])
556 ) {
557 return TRUE;
558 }
559 }
560
561 /**
562 * Get the recurring contribution object.
563 *
564 * @return \CRM_Contribute_BAO_ContributionRecur
565 * @throws \CRM_Core_Exception
566 */
567 protected function getContributionRecurObject(): CRM_Contribute_BAO_ContributionRecur {
568 if (!$this->contributionRecurObject) {
569 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
570 $contributionRecur->id = $this->getContributionRecurID();
571 if (!$contributionRecur->find(TRUE)) {
572 throw new CRM_Core_Exception('Failure: Could not find contribution recur record');
573 }
574 return $this->contributionRecurObject = $contributionRecur;
575 }
576 return $this->contributionRecurObject;
577 }
578
579 /**
580 * @return \CRM_Contribute_BAO_Contribution
581 * @throws \CRM_Core_Exception
582 */
583 protected function getContributionObject(): CRM_Contribute_BAO_Contribution {
584 if (!$this->contributionObject) {
585 // Check if the contribution exists
586 // make sure contribution exists and is valid
587 $contribution = new CRM_Contribute_BAO_Contribution();
588 $contribution->id = $this->getContributionID();
589 if (!$contribution->find(TRUE)) {
590 throw new CRM_Core_Exception('Failure: Could not find contribution record');
591 }
592 // The DAO types it as int but doesn't return it as int.
593 $contribution->contact_id = (int) $contribution->contact_id;
594 $this->contributionObject = $contribution;
595 }
596 return $this->contributionObject;
597 }
598
599 /**
600 * Get the relevant contact ID.
601 *
602 * @return int
603 * @throws \CRM_Core_Exception
604 */
605 protected function getContactID(): int {
606 return $this->getValue('c', TRUE);
607 }
608
609 /**
610 * Is the original contribution completed.
611 *
612 * @return bool
613 * @throws \CRM_Core_Exception
614 */
615 private function isContributionCompleted(): bool {
616 $status = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $this->getContributionObject()->contribution_status_id);
617 return $status === 'Completed';
618 }
619
620 }