From 33c99b15094aaff9a9df222cb8cedbf1bed8bf7a Mon Sep 17 00:00:00 2001
From: Matthew Wire <mjw@mjwconsult.co.uk>
Date: Wed, 3 Nov 2021 15:54:45 +0000
Subject: [PATCH] Provide a more helpful reason instead of 'Bad Request' when
 payment fails due to expired CSRF token from firewall

---
 CRM/Stripe/Check.php           |  2 +-
 api/v3/StripePaymentintent.php | 18 ++++++++++++------
 2 files changed, 13 insertions(+), 7 deletions(-)

diff --git a/CRM/Stripe/Check.php b/CRM/Stripe/Check.php
index 41990ff8..76c33b6c 100644
--- a/CRM/Stripe/Check.php
+++ b/CRM/Stripe/Check.php
@@ -26,7 +26,7 @@ class CRM_Stripe_Check {
    * @var string
    */
   const MIN_VERSION_MJWSHARED = '1.1';
-  const MIN_VERSION_FIREWALL = '1.2.1';
+  const MIN_VERSION_FIREWALL = '1.3';
 
   /**
    * @var array
diff --git a/api/v3/StripePaymentintent.php b/api/v3/StripePaymentintent.php
index 6ce7dd0e..2af387a2 100644
--- a/api/v3/StripePaymentintent.php
+++ b/api/v3/StripePaymentintent.php
@@ -9,6 +9,7 @@
  +--------------------------------------------------------------------+
  */
 
+use Civi\Firewall\Firewall;
 use CRM_Stripe_ExtensionUtil as E;
 
 /**
@@ -31,8 +32,9 @@ function civicrm_api3_stripe_paymentintent_create($params) {
  */
 function civicrm_api3_stripe_paymentintent_createorupdate($params) {
   if (class_exists('\Civi\Firewall\Firewall')) {
-    if (!\Civi\Firewall\Firewall::isCSRFTokenValid(CRM_Utils_Type::validate($params['csrfToken'], 'String'))) {
-      _civicrm_api3_stripe_paymentintent_returnInvalid();
+    $firewall = new Firewall();
+    if (!$firewall->checkIsCSRFTokenValid(CRM_Utils_Type::validate($params['csrfToken'], 'String'))) {
+      _civicrm_api3_stripe_paymentintent_returnInvalid($firewall->getReasonDescription());
     }
   }
   if (!empty($params['stripe_intent_id'])) {
@@ -156,8 +158,9 @@ function _civicrm_api3_stripe_paymentintent_process_spec(&$spec) {
  */
 function civicrm_api3_stripe_paymentintent_process($params) {
   if (class_exists('\Civi\Firewall\Firewall')) {
-    if (!\Civi\Firewall\Firewall::isCSRFTokenValid(CRM_Utils_Type::validate($params['csrfToken'], 'String'))) {
-      _civicrm_api3_stripe_paymentintent_returnInvalid();
+    $firewall = new Firewall();
+    if (!$firewall->checkIsCSRFTokenValid(CRM_Utils_Type::validate($params['csrfToken'], 'String'))) {
+      _civicrm_api3_stripe_paymentintent_returnInvalid($firewall->getReasonDescription());
     }
   }
   $paymentMethodID = CRM_Utils_Type::validate($params['payment_method_id'] ?? '', 'String');
@@ -302,7 +305,10 @@ function civicrm_api3_stripe_paymentintent_process($params) {
 /**
  * Passed parameters were invalid
  */
-function _civicrm_api3_stripe_paymentintent_returnInvalid() {
-  http_response_code(400);
+function _civicrm_api3_stripe_paymentintent_returnInvalid($message = '') {
+  if (empty($message)) {
+    $message = E::ts('Bad Request');
+  }
+  header("HTTP/1.1 400 {$message}");
   exit(1);
 }
-- 
GitLab