From 4c95cc1a9b63c6479a4b7a86a3426ad5e8e804d2 Mon Sep 17 00:00:00 2001
From: Matthew Wire <mjw@mjwconsult.co.uk>
Date: Mon, 13 Jul 2020 15:10:47 +0100
Subject: [PATCH] Record refund against the already recorded payment in CiviCRM
 so we update financial items correctly

---
 CRM/Core/Payment/StripeIPN.php | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/CRM/Core/Payment/StripeIPN.php b/CRM/Core/Payment/StripeIPN.php
index fe72b2b4..c488c33f 100644
--- a/CRM/Core/Payment/StripeIPN.php
+++ b/CRM/Core/Payment/StripeIPN.php
@@ -322,6 +322,18 @@ class CRM_Core_Payment_StripeIPN extends CRM_Core_Payment_BaseIPN {
           'trxn_id' => $this->charge_id,
           'order_reference' => $this->invoice_id ?? NULL,
         ];
+        if (isset($this->contribution['payments'])) {
+          $refundStatusID = (int) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
+          foreach ($this->contribution['payments'] as $payment) {
+            if (((int) $payment['status_id'] === $refundStatusID) && ((float) $payment['total_amount'] === $params['total_amount'])) {
+              // Already refunded
+              return TRUE;
+            }
+          }
+          // This triggers the financial transactions/items to be updated correctly.
+          $params['cancelled_payment_id'] = reset($this->contribution['payments'])['id'];
+        }
+
         $this->updateContributionRefund($params);
         return TRUE;
 
-- 
GitLab