Bug: [BUG] map error message and connector transaction_id in case connector returns failure status in 2xx response status.



### Bug Description

When connector returns failure status in 2xx response, error messages are not persisted for some connectors.

### Expected Behavior

When connector returns failure status in 2xx response, error messages should be persisted for all connectors.

### Actual Behavior

When connector returns failure status in 2xx response, error messages are not persisted for some connectors.

### Steps To Reproduce

Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Simulate a failed payment in noon or payme 
2. Status will be failed but error message will be null.


### Context For The Bug

_No response_

### Environment

Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.

If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``


### Have you spent some time checking if this bug has been raised before?

- [X] I checked and didn't find a similar issue

### Have you read the Contributing Guidelines?

- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)

### Are you willing to submit a PR?

Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index de53b991d89..b2a9f14ccce 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -1446,9 +1446,9 @@ impl<F>
                             resource_id: types::ResponseId::NoResponseId,
                             redirection_data,
                             mandate_reference: None,
-                            connector_metadata: Some(
-                                serde_json::json!({"three_ds_data":three_ds_data}),
-                            ),
+                            connector_metadata: Some(serde_json::json!({
+                                "three_ds_data": three_ds_data
+                            })),
                             network_txn_id: None,
                             connector_response_reference_id,
                             incremental_authorization_allowed: None,
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index fb806fda68f..d4697e3ba14 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -4,7 +4,8 @@ use reqwest::Url;
 use serde::{Deserialize, Serialize};
 
 use crate::{
-    connector::utils::{self, CryptoData},
+    connector::utils::{self, is_payment_failure, CryptoData},
+    consts,
     core::errors,
     services,
     types::{self, api, storage::enums},
@@ -155,14 +156,30 @@ impl<F, T>
             types::PaymentsResponseData,
         >,
     ) -> Result<Self, Self::Error> {
-        let redirection_data = item
-            .response
-            .data
-            .hosted_page_url
-            .map(|x| services::RedirectForm::from((x, services::Method::Get)));
-        Ok(Self {
-            status: enums::AttemptStatus::from(item.response.data.status),
-            response: Ok(types::PaymentsResponseData::TransactionResponse {
+        let status = enums::AttemptStatus::from(item.response.data.status.clone());
+        let response = if is_payment_failure(status) {
+            let payment_response = &item.response.data;
+            Err(types::ErrorResponse {
+                code: payment_response
+                    .name
+                    .clone()
+                    .unwrap_or(consts::NO_ERROR_CODE.to_string()),
+                message: payment_response
+                    .status_context
+                    .clone()
+                    .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+                reason: payment_response.status_context.clone(),
+                status_code: item.http_code,
+                attempt_status: None,
+                connector_transaction_id: Some(payment_response.id.clone()),
+            })
+        } else {
+            let redirection_data = item
+                .response
+                .data
+                .hosted_page_url
+                .map(|x| services::RedirectForm::from((x, services::Method::Get)));
+            Ok(types::PaymentsResponseData::TransactionResponse {
                 resource_id: types::ResponseId::ConnectorTransactionId(
                     item.response.data.id.clone(),
                 ),
@@ -176,7 +193,11 @@ impl<F, T>
                     .custom_id
                     .or(Some(item.response.data.id)),
                 incremental_authorization_allowed: None,
-            }),
+            })
+        };
+        Ok(Self {
+            status,
+            response,
             ..item.data
         })
     }
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index 2f5f342d7ae..bbd7da234b6 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize};
 
 use crate::{
     connector::utils::{
-        self as conn_utils, CardData, PaymentsAuthorizeRequestData, RevokeMandateRequestData,
-        RouterData, WalletData,
+        self as conn_utils, is_refund_failure, CardData, PaymentsAuthorizeRequestData,
+        RevokeMandateRequestData, RouterData, WalletData,
     },
     core::{errors, mandate::MandateBehaviour},
     services,
@@ -555,6 +555,8 @@ impl<F, T>
     fn try_from(
         item: types::ResponseRouterData<F, NoonPaymentsResponse, T, types::PaymentsResponseData>,
     ) -> Result<Self, Self::Error> {
+        let order = item.response.result.order;
+        let status = enums::AttemptStatus::foreign_from((order.status, item.data.status));
         let redirection_data = item.response.result.checkout_data.map(|redirection_data| {
             services::RedirectForm::Form {
                 endpoint: redirection_data.post_url.to_string(),
@@ -570,17 +572,16 @@ impl<F, T>
                     connector_mandate_id: Some(subscription_data.identifier),
                     payment_method_id: None,
                 });
-        let order = item.response.result.order;
         Ok(Self {
-            status: enums::AttemptStatus::foreign_from((order.status, item.data.status)),
+            status,
             response: match order.error_message {
                 Some(error_message) => Err(ErrorResponse {
                     code: order.error_code.to_string(),
                     message: error_message.clone(),
                     reason: Some(error_message),
                     status_code: item.http_code,
-                    attempt_status: None,
-                    connector_transaction_id: None,
+                    attempt_status: Some(status),
+                    connector_transaction_id: Some(order.id.to_string()),
                 }),
                 _ => {
                     let connector_response_reference_id =
@@ -784,13 +785,18 @@ pub struct NoonPaymentsTransactionResponse {
 }
 
 #[derive(Default, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
 pub struct NoonRefundResponseResult {
     transaction: NoonPaymentsTransactionResponse,
 }
 
 #[derive(Default, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
 pub struct RefundResponse {
     result: NoonRefundResponseResult,
+    result_code: u32,
+    class_description: String,
+    message: String,
 }
 
 impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
@@ -800,11 +806,26 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
     fn try_from(
         item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
     ) -> Result<Self, Self::Error> {
-        Ok(Self {
-            response: Ok(types::RefundsResponseData {
+        let response = &item.response;
+        let refund_status =
+            enums::RefundStatus::from(response.result.transaction.status.to_owned());
+        let response = if is_refund_failure(refund_status) {
+            Err(ErrorResponse {
+                status_code: item.http_code,
+                code: response.result_code.to_string(),
+                message: response.class_description.clone(),
+                reason: Some(response.message.clone()),
+                attempt_status: None,
+                connector_transaction_id: Some(response.result.transaction.id.clone()),
+            })
+        } else {
+            Ok(types::RefundsResponseData {
                 connector_refund_id: item.response.result.transaction.id,
-                refund_status: enums::RefundStatus::from(item.response.result.transaction.status),
-            }),
+                refund_status,
+            })
+        };
+        Ok(Self {
+            response,
             ..item.data
         })
     }
@@ -819,13 +840,18 @@ pub struct NoonRefundResponseTransactions {
 }
 
 #[derive(Default, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
 pub struct NoonRefundSyncResponseResult {
     transactions: Vec<NoonRefundResponseTransactions>,
 }
 
 #[derive(Default, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
 pub struct RefundSyncResponse {
     result: NoonRefundSyncResponseResult,
+    result_code: u32,
+    class_description: String,
+    message: String,
 }
 
 impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
@@ -849,12 +875,25 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
                     })
             })
             .ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
-
-        Ok(Self {
-            response: Ok(types::RefundsResponseData {
+        let refund_status = enums::RefundStatus::from(noon_transaction.status.to_owned());
+        let response = if is_refund_failure(refund_status) {
+            let response = &item.response;
+            Err(ErrorResponse {
+                status_code: item.http_code,
+                code: response.result_code.to_string(),
+                message: response.class_description.clone(),
+                reason: Some(response.message.clone()),
+                attempt_status: None,
+                connector_transaction_id: Some(noon_transaction.id.clone()),
+            })
+        } else {
+            Ok(types::RefundsResponseData {
                 connector_refund_id: noon_transaction.id.to_owned(),
-                refund_status: enums::RefundStatus::from(noon_transaction.status.to_owned()),
-            }),
+                refund_status,
+            })
+        };
+        Ok(Self {
+            response,
             ..item.data
         })
     }
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 77dcb6429c9..e0f13741b64 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -12,9 +12,9 @@ use url::Url;
 
 use crate::{
     connector::utils::{
-        self, missing_field_err, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
-        PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, PaymentsSyncRequestData,
-        RouterData,
+        self, is_payment_failure, is_refund_failure, missing_field_err, AddressDetailsData,
+        CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
+        PaymentsPreProcessingData, PaymentsSyncRequestData, RouterData,
     },
     consts,
     core::errors,
@@ -198,14 +198,15 @@ impl<F, T>
     fn try_from(
         item: types::ResponseRouterData<F, PaymePaySaleResponse, T, types::PaymentsResponseData>,
     ) -> Result<Self, Self::Error> {
-        let response = if item.response.sale_status == SaleStatus::Failed {
+        let status = enums::AttemptStatus::from(item.response.sale_status.clone());
+        let response = if is_payment_failure(status) {
             // To populate error message in case of failure
             Err(types::ErrorResponse::from((&item.response, item.http_code)))
         } else {
             Ok(types::PaymentsResponseData::try_from(&item.response)?)
         };
         Ok(Self {
-            status: enums::AttemptStatus::from(item.response.sale_status),
+            status,
             response,
             ..item.data
         })
@@ -227,7 +228,7 @@ impl From<(&PaymePaySaleResponse, u16)> for types::ErrorResponse {
             reason: pay_sale_response.status_error_details.to_owned(),
             status_code: http_code,
             attempt_status: None,
-            connector_transaction_id: None,
+            connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()),
         }
     }
 }
@@ -281,7 +282,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay
             .first()
             .cloned()
             .ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
-        let response = if transaction_response.sale_status == SaleStatus::Failed {
+        let status = enums::AttemptStatus::from(transaction_response.sale_status.clone());
+        let response = if is_payment_failure(status) {
             // To populate error message in case of failure
             Err(types::ErrorResponse::from((
                 &transaction_response,
@@ -291,7 +293,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay
             Ok(types::PaymentsResponseData::from(&transaction_response))
         };
         Ok(Self {
-            status: enums::AttemptStatus::from(transaction_response.sale_status),
+            status,
             response,
             ..item.data
         })
@@ -312,7 +314,7 @@ impl From<(&SaleQuery, u16)> for types::ErrorResponse {
             reason: sale_query_response.sale_error_text.clone(),
             status_code: http_code,
             attempt_status: None,
-            connector_transaction_id: None,
+            connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()),
         }
     }
 }
@@ -982,6 +984,7 @@ impl TryFrom<SaleStatus> for enums::RefundStatus {
 pub struct PaymeRefundResponse {
     sale_status: SaleStatus,
     payme_transaction_id: String,
+    status_error_code: i64,
 }
 
 impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>>
@@ -991,11 +994,25 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>
     fn try_from(
         item: types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>,
     ) -> Result<Self, Self::Error> {
-        Ok(Self {
-            response: Ok(types::RefundsResponseData {
+        let refund_status = enums::RefundStatus::try_from(item.response.sale_status.clone())?;
+        let response = if is_refund_failure(refund_status) {
+            let payme_response = &item.response;
+            Err(types::ErrorResponse {
+                code: payme_response.status_error_code.to_string(),
+                message: payme_response.status_error_code.to_string(),
+                reason: Some(payme_response.status_error_code.to_string()),
+                status_code: item.http_code,
+                attempt_status: None,
+                connector_transaction_id: Some(payme_response.payme_transaction_id.clone()),
+            })
+        } else {
+            Ok(types::RefundsResponseData {
                 connector_refund_id: item.response.payme_transaction_id,
-                refund_status: enums::RefundStatus::try_from(item.response.sale_status)?,
-            }),
+                refund_status,
+            })
+        };
+        Ok(Self {
+            response,
             ..item.data
         })
     }
@@ -1031,13 +1048,24 @@ impl<F, T>
             .items
             .first()
             .ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
-        Ok(Self {
-            response: Ok(types::RefundsResponseData {
-                refund_status: enums::RefundStatus::try_from(
-                    pay_sale_response.sale_status.clone(),
-                )?,
+        let refund_status = enums::RefundStatus::try_from(pay_sale_response.sale_status.clone())?;
+        let response = if is_refund_failure(refund_status) {
+            Err(types::ErrorResponse {
+                code: consts::NO_ERROR_CODE.to_string(),
+                message: consts::NO_ERROR_CODE.to_string(),
+                reason: None,
+                status_code: item.http_code,
+                attempt_status: None,
+                connector_transaction_id: Some(pay_sale_response.payme_transaction_id.clone()),
+            })
+        } else {
+            Ok(types::RefundsResponseData {
+                refund_status,
                 connector_refund_id: pay_sale_response.payme_transaction_id.clone(),
-            }),
+            })
+        };
+        Ok(Self {
+            response,
             ..item.data
         })
     }
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 87d50bb68a2..7951246790f 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1786,6 +1786,7 @@ pub fn is_refund_failure(status: enums::RefundStatus) -> bool {
         | common_enums::RefundStatus::Success => false,
     }
 }
+
 #[cfg(test)]
 mod error_code_error_message_tests {
     #![allow(clippy::unwrap_used)]

## Type of Change
<!-- Put an `x` in the boxes that apply -->

- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD

## Description
<!-- Describe your changes in detail -->
Store payment_id and refund_id and error_details in case connector returns 2xx for a failed payment.

### Additional Changes

- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables

<!--
Provide links to the files with corresponding changes.

Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->


## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.

If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->


## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Manual

Noon:
<img width="1310" alt="noon error mapping" src="https://github.com/juspay/hyperswitch/assets/61539176/84877c5e-ea00-45c9-b32b-fc514859512d">

Payme:
<img width="1347" alt="payme error mapping" src="https://github.com/juspay/hyperswitch/assets/61539176/18e9fb84-bba8-48b7-8859-ce1eabe1aef8">

Refund:

Noon: Refund create
<img width="1728" alt="Noon refund creat" src="https://github.com/juspay/hyperswitch/assets/61539176/c199585a-ed3a-428c-9d44-228f39dc93e9">

Noon: Refund force sync
<img width="1728" alt="Noon refund force sync" src="https://github.com/juspay/hyperswitch/assets/61539176/571dc7ae-d1de-4155-8f7e-523476c32b7a">

Payme: refund create:
<img width="1728" alt="payme refund create" src="https://github.com/juspay/hyperswitch/assets/61539176/ff640556-e23a-4a54-b327-a8e2f34dfd77">

Payme: refund Force sync
<img width="1728" alt="payme refund force sync" src="https://github.com/juspay/hyperswitch/assets/61539176/f93bcd2e-50c2-46f5-b117-e41c669a5639">


## Checklist
<!-- Put an `x` in the boxes that apply -->

- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
