Bug: [BUG] Confirm and PSync call not giving whole_connector_response when all_keys_required is true and connector gives an error



### Bug Description

Confirm and PSync call not giving whole_connector_response when all_keys_required is true and connector gives an error

### Expected Behavior

Confirm and PSync call should give whole_connector_response when all_keys_required is true and connector gives an error

### Actual Behavior

Confirm and PSync call not giving whole_connector_response when all_keys_required is true and connector gives an error

### Steps To Reproduce

Give invalid API Keys for any connector and do a payment will `all_keys_required` as `true`. `whole_connector_response` 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: MacOS
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/services/api.rs b/crates/router/src/services/api.rs
index 6ec0ff9fe75..41a12f35576 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -127,6 +127,27 @@ pub type BoxedBillingConnectorPaymentsSyncIntegrationInterface<T, Req, Res> =
 pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> =
     BoxedConnectorIntegrationInterface<T, common_types::VaultConnectorFlowData, Req, Res>;
 
+fn store_raw_connector_response_if_required<T, Req, Resp>(
+    return_raw_connector_response: Option<bool>,
+    router_data: &mut types::RouterData<T, Req, Resp>,
+    body: &types::Response,
+) -> CustomResult<(), errors::ConnectorError>
+where
+    T: Clone + Debug + 'static,
+    Req: Debug + Clone + 'static,
+    Resp: Debug + Clone + 'static,
+{
+    if return_raw_connector_response == Some(true) {
+        let mut decoded = String::from_utf8(body.response.as_ref().to_vec())
+            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+        if decoded.starts_with('\u{feff}') {
+            decoded = decoded.trim_start_matches('\u{feff}').to_string();
+        }
+        router_data.raw_connector_response = Some(Secret::new(decoded));
+    }
+    Ok(())
+}
+
 /// Handle the flow by interacting with connector module
 /// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger`
 /// In other cases, It will be created if required, even if it is not passed
@@ -305,17 +326,13 @@ where
                                                         val + external_latency
                                                     }),
                                             );
-                                            if return_raw_connector_response == Some(true) {
-                                                let mut decoded = String::from_utf8(body.response.as_ref().to_vec())
-                                                    .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-                                                if decoded.starts_with('\u{feff}') {
-                                                    decoded = decoded
-                                                        .trim_start_matches('\u{feff}')
-                                                        .to_string();
-                                                }
-                                                data.raw_connector_response =
-                                                    Some(Secret::new(decoded));
-                                            }
+
+                                            store_raw_connector_response_if_required(
+                                                return_raw_connector_response,
+                                                &mut data,
+                                                &body,
+                                            )?;
+
                                             Ok(data)
                                         }
                                         Err(err) => {
@@ -342,6 +359,12 @@ where
                                         )),
                                     );
 
+                                    store_raw_connector_response_if_required(
+                                        return_raw_connector_response,
+                                        &mut router_data,
+                                        &body,
+                                    )?;
+
                                     let error = match body.status_code {
                                         500..=511 => {
                                             let error_res = connector_integration

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

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

Closes this [issue](https://github.com/juspay/hyperswitch/issues/8144)

## Description
<!-- Describe your changes in detail -->

send whole_connector_response even when connector sends an error

### 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)?
-->

Postman Test

1. Payments - Create (with invalid creds, `confirm`: `true` and `all_keys_required`: `true`)

Request:

```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_6zQcrKUzlenHXPheZtIUO3WbxTAiPtBxxrLFw1sSRmjRIn0QGPJ1z6NnwlHUKKVa' \
--data-raw '{
    "amount": 35308,
    "currency": "USD",
    "confirm": true,
    "all_keys_required": true,
    "capture_method": "automatic",
    "customer_id": "StripeCustomer",
    "email": "guest@example.com",
    "name": "John Doe",
    "phone": "999999999",
    "phone_country_code": "+1",
    "profile_id": "pro_RdVLVWtGWBgd9sMam8Dg",
    "description": "Its my first payment request",
    "authentication_type": "no_three_ds",
    "return_url": "https://duck.com",
    "payment_method": "card",
    "payment_method_type": "credit",
    "payment_method_data": {
        "card": {
            "card_number": "370000000000002",
            "card_exp_month": "10",
            "card_exp_year": "25",
            "card_holder_name": "joseph Doe",
            "card_cvc": "123"
        }
    },
    "billing": {
        "address": {
            "line1": "1467",
            "line2": "Harrison Street",
            "line3": "Harrison Street",
            "city": "San Fransico",
            "state": "California",
            "zip": "94122",
            "country": "US",
            "first_name": "joseph",
            "last_name": "Doe"
        }
    },
    "shipping": {
        "address": {
            "line1": "1467",
            "line2": "Harrison Street",
            "line3": "Harrison Street",
            "city": "San Fransico",
            "state": "California",
            "zip": "94122",
            "country":"US",
            "first_name": "PiX"
        }
    }  
}'
```

Response:

```
{
    "payment_id": "pay_78k7Xn25MnMHMwoFsJPX",
    "merchant_id": "merchant_1748265048",
    "status": "failed",
    "amount": 35308,
    "net_amount": 35308,
    "shipping_cost": null,
    "amount_capturable": 0,
    "amount_received": null,
    "connector": "authorizedotnet",
    "client_secret": "pay_78k7Xn25MnMHMwoFsJPX_secret_BlNgMRRNeA6Wre5jbtWr",
    "created": "2025-05-26T13:33:49.037Z",
    "currency": "USD",
    "customer_id": "StripeCustomer",
    "customer": {
        "id": "StripeCustomer",
        "name": "John Doe",
        "email": "guest@example.com",
        "phone": "999999999",
        "phone_country_code": "+1"
    },
    "description": "Its my first payment request",
    "refunds": null,
    "disputes": null,
    "mandate_id": null,
    "mandate_data": null,
    "setup_future_usage": null,
    "off_session": null,
    "capture_on": null,
    "capture_method": "automatic",
    "payment_method": "card",
    "payment_method_data": {
        "card": {
            "last4": "0002",
            "card_type": null,
            "card_network": null,
            "card_issuer": null,
            "card_issuing_country": null,
            "card_isin": "370000",
            "card_extended_bin": null,
            "card_exp_month": "10",
            "card_exp_year": "25",
            "card_holder_name": "joseph Doe",
            "payment_checks": null,
            "authentication_data": null
        },
        "billing": null
    },
    "payment_token": null,
    "shipping": {
        "address": {
            "city": "San Fransico",
            "country": "US",
            "line1": "1467",
            "line2": "Harrison Street",
            "line3": "Harrison Street",
            "zip": "94122",
            "state": "California",
            "first_name": "PiX",
            "last_name": null
        },
        "phone": null,
        "email": null
    },
    "billing": {
        "address": {
            "city": "San Fransico",
            "country": "US",
            "line1": "1467",
            "line2": "Harrison Street",
            "line3": "Harrison Street",
            "zip": "94122",
            "state": "California",
            "first_name": "joseph",
            "last_name": "Doe"
        },
        "phone": null,
        "email": null
    },
    "order_details": null,
    "email": "guest@example.com",
    "name": "John Doe",
    "phone": "999999999",
    "return_url": "https://duck.com/",
    "authentication_type": "no_three_ds",
    "statement_descriptor_name": null,
    "statement_descriptor_suffix": null,
    "next_action": null,
    "cancellation_reason": null,
    "error_code": "E00003",
    "error_message": "The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:transactionKey' element is invalid - The value XXXXXXXXXXXXXXXXXXX is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.",
    "unified_code": "UE_9000",
    "unified_message": "Something went wrong",
    "payment_experience": null,
    "payment_method_type": "credit",
    "connector_label": null,
    "business_country": null,
    "business_label": "default",
    "business_sub_label": null,
    "allowed_payment_method_types": null,
    "ephemeral_key": {
        "customer_id": "StripeCustomer",
        "created_at": 1748266429,
        "expires": 1748270029,
        "secret": "epk_3c034be0d8934ec98fcde1b244d55ed6"
    },
    "manual_retry_allowed": true,
    "connector_transaction_id": null,
    "frm_message": null,
    "metadata": null,
    "connector_metadata": null,
    "feature_metadata": null,
    "reference_id": null,
    "payment_link": null,
    "profile_id": "pro_RdVLVWtGWBgd9sMam8Dg",
    "surcharge_details": null,
    "attempt_count": 1,
    "merchant_decision": null,
    "merchant_connector_id": "mca_FvbbC2wYxwcnbvoXrSFL",
    "incremental_authorization_allowed": false,
    "authorization_count": null,
    "incremental_authorizations": null,
    "external_authentication_details": null,
    "external_3ds_authentication_attempted": false,
    "expires_on": "2025-05-26T13:48:49.037Z",
    "fingerprint": null,
    "browser_info": null,
    "payment_method_id": null,
    "payment_method_status": null,
    "updated": "2025-05-26T13:33:50.999Z",
    "split_payments": null,
    "frm_metadata": null,
    "extended_authorization_applied": null,
    "capture_before": null,
    "merchant_order_reference_id": null,
    "order_tax_amount": null,
    "connector_mandate_id": null,
    "card_discovery": "manual",
    "force_3ds_challenge": false,
    "force_3ds_challenge_trigger": false,
    "issuer_error_code": null,
    "issuer_error_message": null,
    "is_iframe_redirection_enabled": null,
    "whole_connector_response": "{\"messages\":{\"resultCode\":\"Error\",\"message\":[{\"code\":\"E00003\",\"text\":\"The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:transactionKey' element is invalid - The value XXXXXXXXXXXXXXXXXXX is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.\"}]}}"
}
```

2.. Payments - Create (with valid API Keys, `confirm`: `true` and `all_keys_required`: `true`)

Request:

```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_6zQcrKUzlenHXPheZtIUO3WbxTAiPtBxxrLFw1sSRmjRIn0QGPJ1z6NnwlHUKKVa' \
--data-raw '{
    "amount": 35308,
    "currency": "USD",
    "confirm": true,
    "all_keys_required": true,
    "capture_method": "automatic",
    "customer_id": "StripeCustomer",
    "email": "guest@example.com",
    "name": "John Doe",
    "phone": "999999999",
    "phone_country_code": "+1",
    "profile_id": "pro_RdVLVWtGWBgd9sMam8Dg",
    "description": "Its my first payment request",
    "authentication_type": "no_three_ds",
    "return_url": "https://duck.com",
    "payment_method": "card",
    "payment_method_type": "credit",
    "payment_method_data": {
        "card": {
            "card_number": "370000000000002",
            "card_exp_month": "10",
            "card_exp_year": "25",
            "card_holder_name": "joseph Doe",
            "card_cvc": "123"
        }
    },
    "billing": {
        "address": {
            "line1": "1467",
            "line2": "Harrison Street",
            "line3": "Harrison Street",
            "city": "San Fransico",
            "state": "California",
            "zip": "94122",
            "country": "US",
            "first_name": "joseph",
            "last_name": "Doe"
        }
    },
    "shipping": {
        "address": {
            "line1": "1467",
            "line2": "Harrison Street",
            "line3": "Harrison Street",
            "city": "San Fransico",
            "state": "California",
            "zip": "94122",
            "country":"US",
            "first_name": "PiX"
        }
    }  
}'
```

Response:

```
{
    "payment_id": "pay_hxQGHpxW3F5DNxeyiY8z",
    "merchant_id": "merchant_1748267173",
    "status": "succeeded",
    "amount": 35308,
    "net_amount": 35308,
    "shipping_cost": null,
    "amount_capturable": 0,
    "amount_received": 35308,
    "connector": "authorizedotnet",
    "client_secret": "pay_hxQGHpxW3F5DNxeyiY8z_secret_da5n53bB7Kb1exV85EK2",
    "created": "2025-05-26T13:46:40.052Z",
    "currency": "USD",
    "customer_id": "StripeCustomer",
    "customer": {
        "id": "StripeCustomer",
        "name": "John Doe",
        "email": "guest@example.com",
        "phone": "999999999",
        "phone_country_code": "+1"
    },
    "description": "Its my first payment request",
    "refunds": null,
    "disputes": null,
    "mandate_id": null,
    "mandate_data": null,
    "setup_future_usage": null,
    "off_session": null,
    "capture_on": null,
    "capture_method": "automatic",
    "payment_method": "card",
    "payment_method_data": {
        "card": {
            "last4": "0002",
            "card_type": null,
            "card_network": null,
            "card_issuer": null,
            "card_issuing_country": null,
            "card_isin": "370000",
            "card_extended_bin": null,
            "card_exp_month": "10",
            "card_exp_year": "25",
            "card_holder_name": "joseph Doe",
            "payment_checks": null,
            "authentication_data": null
        },
        "billing": null
    },
    "payment_token": null,
    "shipping": {
        "address": {
            "city": "San Fransico",
            "country": "US",
            "line1": "1467",
            "line2": "Harrison Street",
            "line3": "Harrison Street",
            "zip": "94122",
            "state": "California",
            "first_name": "PiX",
            "last_name": null
        },
        "phone": null,
        "email": null
    },
    "billing": {
        "address": {
            "city": "San Fransico",
            "country": "US",
            "line1": "1467",
            "line2": "Harrison Street",
            "line3": "Harrison Street",
            "zip": "94122",
            "state": "California",
            "first_name": "joseph",
            "last_name": "Doe"
        },
        "phone": null,
        "email": null
    },
    "order_details": null,
    "email": "guest@example.com",
    "name": "John Doe",
    "phone": "999999999",
    "return_url": "https://duck.com/",
    "authentication_type": "no_three_ds",
    "statement_descriptor_name": null,
    "statement_descriptor_suffix": null,
    "next_action": null,
    "cancellation_reason": null,
    "error_code": null,
    "error_message": null,
    "unified_code": null,
    "unified_message": null,
    "payment_experience": null,
    "payment_method_type": "credit",
    "connector_label": null,
    "business_country": null,
    "business_label": "default",
    "business_sub_label": null,
    "allowed_payment_method_types": null,
    "ephemeral_key": {
        "customer_id": "StripeCustomer",
        "created_at": 1748267200,
        "expires": 1748270800,
        "secret": "epk_fad60adb28944cf8be7a3d64bbce0672"
    },
    "manual_retry_allowed": false,
    "connector_transaction_id": "120063944184",
    "frm_message": null,
    "metadata": null,
    "connector_metadata": null,
    "feature_metadata": null,
    "reference_id": "120063944184",
    "payment_link": null,
    "profile_id": "pro_zHrEr9z5qskGtTpA1ZPg",
    "surcharge_details": null,
    "attempt_count": 1,
    "merchant_decision": null,
    "merchant_connector_id": "mca_NnVBGa1fNbiNyFfGuadr",
    "incremental_authorization_allowed": null,
    "authorization_count": null,
    "incremental_authorizations": null,
    "external_authentication_details": null,
    "external_3ds_authentication_attempted": false,
    "expires_on": "2025-05-26T14:01:40.052Z",
    "fingerprint": null,
    "browser_info": null,
    "payment_method_id": null,
    "payment_method_status": null,
    "updated": "2025-05-26T13:46:42.017Z",
    "split_payments": null,
    "frm_metadata": null,
    "extended_authorization_applied": null,
    "capture_before": null,
    "merchant_order_reference_id": null,
    "order_tax_amount": null,
    "connector_mandate_id": null,
    "card_discovery": "manual",
    "force_3ds_challenge": false,
    "force_3ds_challenge_trigger": false,
    "issuer_error_code": null,
    "issuer_error_message": null,
    "is_iframe_redirection_enabled": null,
    "whole_connector_response": "{\"transactionResponse\":{\"responseCode\":\"1\",\"authCode\":\"UA8PIX\",\"avsResultCode\":\"Y\",\"cvvResultCode\":\"P\",\"cavvResultCode\":\"2\",\"transId\":\"120063944184\",\"refTransID\":\"\",\"transHash\":\"\",\"testRequest\":\"0\",\"accountNumber\":\"XXXX0002\",\"accountType\":\"AmericanExpress\",\"messages\":[{\"code\":\"1\",\"description\":\"This transaction has been approved.\"}],\"transHashSha2\":\"7028AF831EAF78761E94F39C2F6D1544D0916D8330C75AED524A99A2917BBA17D76305F51183A97E15D9E30A206EC869F0F5D45903F5C7928A454176060439D7\",\"SupplementalDataQualificationIndicator\":0,\"networkTransId\":\"73WA8F79F6PERAJ1F57SWAB\"},\"profileResponse\":{\"messages\":{\"resultCode\":\"Ok\",\"message\":[{\"code\":\"I00001\",\"text\":\"Successful.\"}]},\"customerProfileId\":\"931062475\",\"customerPaymentProfileIdList\":[\"930352630\"],\"customerShippingAddressIdList\":[]},\"refId\":\"\",\"messages\":{\"resultCode\":\"Ok\",\"message\":[{\"code\":\"I00001\",\"text\":\"Successful.\"}]}}"
}
```


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

- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
