Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

refactor(router): centralize payment callback URL handling (#15144)

Hrithikeshca327d06bb72
diff --git a/.github/data/payment_callback_config.sql b/.github/data/payment_callback_config.sql
new file mode 100644
index 0000000000..df0306eb42
--- /dev/null
+++ b/.github/data/payment_callback_config.sql
@@ -0,0 +1,3 @@
+INSERT INTO configs (key, config)
+VALUES ('payment_callback', '{"mode":"enforced"}')
+ON CONFLICT (key) DO UPDATE SET config = EXCLUDED.config;
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.yml
index b0631ade11..065ebdd9cf 100644
--- a/.github/workflows/cypress-tests-runner.yml
+++ b/.github/workflows/cypress-tests-runner.yml
@@ -407,6 +407,11 @@ jobs:
DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db
run: just migrate run --locked-schema
+ - name: Configure enforced payment callbacks
+ if: ${{ env.RUN_TESTS == 'true' }}
+ run: |
+ PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --set=ON_ERROR_STOP=1 --file=.github/data/payment_callback_config.sql
+
- name: Insert card info into the database
if: ${{ env.RUN_TESTS == 'true' }}
run: |
@@ -679,6 +684,10 @@ jobs:
DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db
run: just migrate run --locked-schema
+ - name: Configure enforced payment callbacks
+ run: |
+ PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --set=ON_ERROR_STOP=1 --file=.github/data/payment_callback_config.sql
+
- name: Insert card info into the database
run: |
PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --command "\copy cards_info FROM '.github/data/cards_info.csv' DELIMITER ',' CSV HEADER;"
@@ -966,6 +975,11 @@ jobs:
DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db
run: just migrate run --locked-schema
+ - name: Configure enforced payment callbacks
+ if: ${{ env.RUN_TESTS == 'true' }}
+ run: |
+ PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --set=ON_ERROR_STOP=1 --file=.github/data/payment_callback_config.sql
+
- name: Insert card info into the database
if: ${{ env.RUN_TESTS == 'true' }}
run: |
@@ -1389,6 +1403,10 @@ jobs:
DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db
run: just migrate run --locked-schema
+ - name: Configure enforced payment callbacks
+ run: |
+ PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --set=ON_ERROR_STOP=1 --file=.github/data/payment_callback_config.sql
+
- name: Insert card info into the database
run: |
PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --command "\copy cards_info FROM '.github/data/cards_info.csv' DELIMITER ',' CSV HEADER;"
@@ -1577,6 +1595,11 @@ jobs:
DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db
run: just migrate run --locked-schema
+ - name: Configure enforced payment callbacks
+ if: ${{ env.RUN_TESTS == 'true' }}
+ run: |
+ PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --set=ON_ERROR_STOP=1 --file=.github/data/payment_callback_config.sql
+
- name: Insert card info into the database
if: ${{ env.RUN_TESTS == 'true' }}
run: |
@@ -1845,6 +1868,11 @@ jobs:
DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db
run: just migrate_v2 run --locked-schema
+ - name: Configure enforced payment callbacks
+ if: ${{ env.RUN_TESTS == 'true' }}
+ run: |
+ PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --set=ON_ERROR_STOP=1 --file=.github/data/payment_callback_config.sql
+
- name: Insert card info into the database
if: ${{ env.RUN_TESTS == 'true' }}
run: |
diff --git a/crates/api_models/src/authentication.rs b/crates/api_models/src/authentication.rs
index ac7b1094fb..b539c41276 100644
--- a/crates/api_models/src/authentication.rs
+++ b/crates/api_models/src/authentication.rs
@@ -7,6 +7,7 @@ use common_utils::{
};
#[cfg(feature = "v1")]
use error_stack::ResultExt;
+use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
@@ -42,7 +43,7 @@ pub struct AuthenticationCreateRequest {
/// The URL to which the user should be redirected after authentication.
#[schema(value_type = Option<String>, example = "https://example.com/redirect")]
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
/// Force 3DS challenge.
#[serde(default)]
@@ -95,7 +96,7 @@ pub struct AuthenticationResponse {
/// The client secret for this authentication, to be used for client-side operations.
#[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4_secret_el9ksDkiB8hi6j9N78yo")]
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
/// The amount for the transaction.
#[schema(value_type = MinorUnit, example = 1000)]
@@ -113,7 +114,8 @@ pub struct AuthenticationResponse {
pub force_3ds_challenge: Option<bool>,
/// The URL to which the user should be redirected after authentication, if provided.
- pub return_url: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub return_url: Option<Secret<String>>,
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601::option")]
@@ -221,7 +223,7 @@ pub struct AuthenticationEligibilityRequest {
/// Optional secret value used to identify and authorize the client making the request.
/// This can help ensure that the payment session is secure and valid.
#[schema(value_type = Option<String>)]
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
/// Optional identifier for the business profile associated with the payment.
/// This determines which configurations, rules, and branding are applied to the transaction.
@@ -348,7 +350,7 @@ pub struct AuthenticationEligibilityCheckRequest {
/// Optional secret value used to identify and authorize the client making the request.
/// This can help ensure that the payment session is secure and valid.
#[schema(value_type = Option<String>)]
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
/// The data for this authentication eligibility check.
pub eligibility_check_data: AuthenticationEligibilityCheckData,
}
@@ -527,7 +529,7 @@ pub struct AuthenticationAuthenticateRequest {
pub authentication_id: id_type::AuthenticationId,
/// Client secret for the authentication
#[schema(value_type = String)]
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
/// SDK Information if request is from SDK
pub sdk_information: Option<SdkInformation>,
/// Device Channel indicating whether request is coming from App or Browser
@@ -576,7 +578,7 @@ pub struct AuthenticationAuthenticateResponse {
pub error_code: Option<String>,
/// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.
#[schema(value_type = String)]
- pub authentication_value: Option<hyperswitch_masking::Secret<String>>,
+ pub authentication_value: Option<Secret<String>>,
/// The current status of the authentication (e.g., Started).
#[schema(value_type = AuthenticationStatus)]
@@ -625,7 +627,7 @@ pub struct AuthenticationSyncResponse {
/// The client secret for this authentication.
#[schema(value_type = Option<String>)]
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
/// The amount for the transaction.
#[schema(value_type = MinorUnit, example = 1000)]
@@ -643,7 +645,8 @@ pub struct AuthenticationSyncResponse {
pub force_3ds_challenge: Option<bool>,
/// The URL to which the user should be redirected after authentication.
- pub return_url: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub return_url: Option<Secret<String>>,
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601")]
@@ -795,7 +798,7 @@ pub enum Cryptogram {
Cavv {
/// The authentication cryptogram provided by the issuer or ACS.
#[schema(value_type = Option<String>)]
- authentication_cryptogram: hyperswitch_masking::Secret<String>,
+ authentication_cryptogram: Secret<String>,
},
}
@@ -806,20 +809,20 @@ pub enum AuthenticationPaymentMethodDataResponse {
CardData {
/// card expiry year
#[schema(value_type = Option<String>)]
- card_expiry_year: Option<hyperswitch_masking::Secret<String>>,
+ card_expiry_year: Option<Secret<String>>,
/// card expiry month
#[schema(value_type = Option<String>)]
- card_expiry_month: Option<hyperswitch_masking::Secret<String>>,
+ card_expiry_month: Option<Secret<String>>,
},
NetworkTokenData {
/// network token expiry month
#[schema(value_type = Option<String>)]
- network_token_expiry_month: Option<hyperswitch_masking::Secret<String>>,
+ network_token_expiry_month: Option<Secret<String>>,
/// network token expiry year
#[schema(value_type = Option<String>)]
- network_token_expiry_year: Option<hyperswitch_masking::Secret<String>>,
+ network_token_expiry_year: Option<Secret<String>>,
},
}
@@ -831,43 +834,43 @@ pub enum AuthenticationVaultTokenData {
/// token representing card_number
#[schema(value_type = Option<String>)]
#[serde(rename = "card_number")]
- tokenized_card_number: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_card_number: Option<Secret<String>>,
/// token representing card_expiry_year
#[schema(value_type = Option<String>)]
#[serde(rename = "card_expiry_year")]
- tokenized_card_expiry_year: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_card_expiry_year: Option<Secret<String>>,
/// token representing card_expiry_month
#[schema(value_type = Option<String>)]
#[serde(rename = "card_expiry_month")]
- tokenized_card_expiry_month: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_card_expiry_month: Option<Secret<String>>,
/// token representing card_cvc
#[schema(value_type = Option<String>)]
#[serde(rename = "card_cvc")]
- tokenized_card_cvc: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_card_cvc: Option<Secret<String>>,
},
NetworkTokenData {
/// token representing payment_token
#[schema(value_type = Option<String>)]
#[serde(rename = "network_token")]
- tokenized_network_token: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_network_token: Option<Secret<String>>,
/// token representing token_expiry_year
#[schema(value_type = Option<String>)]
#[serde(rename = "network_token_expiry_year")]
- tokenized_expiry_year: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_expiry_year: Option<Secret<String>>,
/// token representing token_expiry_month
#[schema(value_type = Option<String>)]
#[serde(rename = "network_token_expiry_month")]
- tokenized_expiry_month: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_expiry_month: Option<Secret<String>>,
/// token representing token_cryptogram
#[schema(value_type = Option<String>)]
#[serde(rename = "network_token_cryptogram")]
- tokenized_cryptogram: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_cryptogram: Option<Secret<String>>,
},
}
@@ -884,7 +887,7 @@ impl ApiEventMetric for AuthenticationSyncResponse {
pub struct AuthenticationSyncRequest {
/// The client secret for this authentication.
#[schema(value_type = String)]
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
/// Payment method data for Post Authentication sync
pub payment_method_details: Option<PostAuthenticationRequestPaymentMethodData>,
/// Authentication ID for the authentication
@@ -931,7 +934,7 @@ pub struct ClickToPayDetails {
pub provider: Option<super::enums::CtpServiceProvider>,
/// Encrypted payload
#[schema(value_type = Option<String>)]
- pub encrypted_payload: Option<hyperswitch_masking::Secret<String>>,
+ pub encrypted_payload: Option<Secret<String>>,
}
impl ApiEventMetric for AuthenticationSyncRequest {
@@ -964,7 +967,7 @@ pub struct AuthenticationSessionTokenRequest {
pub authentication_id: id_type::AuthenticationId,
/// Client Secret for the authentication
#[schema(value_type = String)]
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
}
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 29c8b8a95d..bac0d372f3 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1983,81 +1983,6 @@ impl PaymentsRequest {
}
}
-#[cfg(feature = "v1")]
-#[cfg(test)]
-mod payments_request_test {
- use common_utils::generate_customer_id_of_default_length;
-
- use super::*;
-
- #[test]
- fn test_valid_case_where_customer_details_are_passed_only_once() {
- let customer_id = generate_customer_id_of_default_length();
- let payments_request = PaymentsRequest {
- customer_id: Some(customer_id),
- ..Default::default()
- };
-
- assert!(payments_request
- .validate_customer_details_in_request()
- .is_none());
- }
-
- #[test]
- fn test_valid_case_where_customer_id_is_passed_in_both_places() {
- let customer_id = generate_customer_id_of_default_length();
-
- let customer_object = CustomerDetails {
- id: Some(customer_id.clone()),
- name: None,
- email: None,
- phone: None,
- phone_country_code: None,
- tax_registration_id: None,
- document_details: None,
- date_of_birth: None,
- };
-
- let payments_request = PaymentsRequest {
- customer_id: Some(customer_id),
- customer: Some(customer_object),
- ..Default::default()
- };
-
- assert!(payments_request
- .validate_customer_details_in_request()
- .is_none());
- }
-
- #[test]
- fn test_invalid_case_where_customer_id_is_passed_in_both_places() {
- let customer_id = generate_customer_id_of_default_length();
- let another_customer_id = generate_customer_id_of_default_length();
-
- let customer_object = CustomerDetails {
- id: Some(customer_id.clone()),
- name: None,
- email: None,
- phone: None,
- phone_country_code: None,
- tax_registration_id: None,
- document_details: None,
- date_of_birth: None,
- };
-
- let payments_request = PaymentsRequest {
- customer_id: Some(another_customer_id),
- customer: Some(customer_object),
- ..Default::default()
- };
-
- assert_eq!(
- payments_request.validate_customer_details_in_request(),
- Some(vec!["customer_id and customer.id"])
- );
- }
-}
-
/// Details of surcharge applied on this payment, if applicable
#[derive(
Default,
@@ -7126,14 +7051,17 @@ pub enum NextActionData {
#[cfg(feature = "v1")]
RedirectToUrl {
#[smithy(value_type = "String")]
- redirect_to_url: String,
+ #[schema(value_type = String)]
+ redirect_to_url: Secret<String>,
},
#[cfg(feature = "v1")]
RedirectInsidePopup {
#[smithy(value_type = "String")]
- popup_url: String,
+ #[schema(value_type = String)]
+ popup_url: Secret<String>,
#[smithy(value_type = "String")]
- redirect_response_url: String,
+ #[schema(value_type = String)]
+ redirect_response_url: Secret<String>,
},
/// Contains the url for redirection flow
#[cfg(feature = "v2")]
@@ -7282,10 +7210,12 @@ pub struct DDCData {
pub struct ThreeDsData {
/// ThreeDS authentication url - to initiate authentication
#[smithy(value_type = "String")]
- pub three_ds_authentication_url: String,
+ #[schema(value_type = String)]
+ pub three_ds_authentication_url: Secret<String>,
/// ThreeDS authorize url - to complete the payment authorization after authentication
#[smithy(value_type = "String")]
- pub three_ds_authorize_url: String,
+ #[schema(value_type = String)]
+ pub three_ds_authorize_url: Secret<String>,
/// ThreeDS method details
#[smithy(value_type = "ThreeDsMethodData")]
pub three_ds_method_details: ThreeDsMethodData,
@@ -10354,8 +10284,8 @@ pub struct PgRedirectResponse {
#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)]
pub struct RedirectionResponse {
pub return_url: String,
- pub params: Vec<(String, String)>,
- pub return_url_with_query_params: String,
+ pub params: Vec<(String, Secret<String>)>,
+ pub return_url_with_query_params: Secret<String>,
pub http_method: String,
pub headers: Vec<(String, String)>,
}
@@ -10363,7 +10293,7 @@ pub struct RedirectionResponse {
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)]
pub struct RedirectionResponse {
- pub return_url_with_query_params: String,
+ pub return_url_with_query_params: Secret<String>,
}
#[derive(Debug, serde::Deserialize)]
@@ -13801,18 +13731,7 @@ pub mod amount {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_mandate_type() {
- let mandate_type = MandateType::default();
- assert_eq!(
- serde_json::to_string(&mandate_type).unwrap(),
- r#"{"multi_use":null}"#
- )
- }
-}
+mod tests;
#[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)]
pub struct RetrievePaymentLinkRequest {
@@ -14488,328 +14407,6 @@ pub struct AppliedOffer {
pub currency: common_enums::Currency,
}
-#[cfg(feature = "v1")]
-#[cfg(test)]
-mod payments_request_api_contract {
- use std::str::FromStr;
-
- use super::*;
-
- #[test]
- fn test_successful_card_deser() {
- let payments_request = r#"
- {
- "amount": 6540,
- "currency": "USD",
- "payment_method": "card",
- "payment_method_data": {
- "card": {
- "card_number": "4242424242424242",
- "card_exp_month": "10",
- "card_exp_year": "25",
- "card_holder_name": "joseph Doe",
- "card_cvc": "123"
- }
- }
- }
- "#;
-
- let expected_card_number_string = "4242424242424242";
- let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap();
-
- let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request);
- assert!(payments_request.is_ok());
-
- if let Some(PaymentMethodData::Card(card_data)) = payments_request
- .unwrap()
- .payment_method_data
- .unwrap()
- .payment_method_data
- {
- assert_eq!(card_data.card_number, expected_card_number);
- } else {
- panic!("Received unexpected response")
- }
- }
-
- #[test]
- fn test_successful_payment_method_reward() {
- let payments_request = r#"
- {
- "amount": 6540,
- "currency": "USD",
- "payment_method": "reward",
- "payment_method_data": "reward",
- "payment_method_type": "evoucher"
- }
- "#;
-
- let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request);
- assert!(payments_request.is_ok());
- assert_eq!(
- payments_request
- .unwrap()
- .payment_method_data
- .unwrap()
- .payment_method_data,
- Some(PaymentMethodData::Reward)
- );
- }
-
- #[test]
- fn test_payment_method_data_with_payment_method_billing() {
- let payments_request = r#"
- {
- "amount": 6540,
- "currency": "USD",
- "payment_method_data": {
- "billing": {
- "address": {
- "line1": "1467",
- "line2": "Harrison Street",
- "city": "San Fransico",
- "state": "California",
- "zip": "94122",
- "country": "US",
- "first_name": "Narayan",
- "last_name": "Bhat"
- }
- }
- }
- }
- "#;
-
- let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request);
- assert!(payments_request.is_ok());
- assert!(payments_request
- .unwrap()
- .payment_method_data
- .unwrap()
- .billing
- .is_some());
- }
-}
-
-#[cfg(test)]
-mod payments_response_api_contract {
- use super::*;
-
- #[derive(Debug, serde::Serialize)]
- struct TestPaymentsResponse {
- #[serde(serialize_with = "serialize_payment_method_data_response")]
- payment_method_data: Option<PaymentMethodDataResponseWithBilling>,
- }
-
- #[test]
- fn test_reward_payment_response() {
- let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling {
- payment_method_data: Some(PaymentMethodDataResponse::Reward {}),
- billing: None,
- };
-
- let payments_response = TestPaymentsResponse {
- payment_method_data: Some(payment_method_response_with_billing),
- };
-
- let expected_response = r#"{"payment_method_data":"reward"}"#;
-
- let stringified_payments_response = payments_response.encode_to_string_of_json();
- assert_eq!(stringified_payments_response.unwrap(), expected_response);
- }
-
- #[cfg(feature = "v1")]
- #[test]
- fn test_fingerprint_type_serialization() {
- assert_eq!(
- serde_json::to_value(FingerprintType::Dpan).unwrap(),
- serde_json::json!("dpan")
- );
- assert_eq!(
- serde_json::to_value(FingerprintType::Fpan).unwrap(),
- serde_json::json!("fpan")
- );
- }
-}
-
-/// Set of tests to extract billing details from payment method data
-/// These are required for backwards compatibility
-#[cfg(test)]
-mod billing_from_payment_method_data {
- use common_enums::CountryAlpha2;
- use hyperswitch_masking::ExposeOptionInterface;
-
- use super::*;
-
- const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US;
- const TEST_FIRST_NAME: &str = "John";
- const TEST_LAST_NAME: &str = "Wheat Dough";
- const TEST_FULL_NAME: &str = "John Wheat Dough";
- const TEST_FIRST_NAME_SINGLE: &str = "John";
-
- #[test]
- fn test_wallet_payment_method_data_paypal() {
- let test_email: Email = Email::try_from("[email protected]".to_string()).unwrap();
-
- let paypal_wallet_payment_method_data =
- PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection {
- email: Some(test_email.clone()),
- payer_id: None,
- }));
-
- let billing_address = paypal_wallet_payment_method_data
- .get_billing_address()
- .unwrap();
-
- assert_eq!(billing_address.email.unwrap(), test_email);
-
- assert!(billing_address.address.is_none());
- assert!(billing_address.phone.is_none());
- }
-
- #[test]
- fn test_bank_redirect_payment_method_data_eps() {
- let test_email = Email::try_from("[email protected]".to_string()).unwrap();
- let test_first_name = Secret::new(String::from("Chaser"));
-
- let bank_redirect_billing = BankRedirectBilling {
- billing_name: Some(test_first_name.clone()),
- email: Some(test_email.clone()),
- };
-
- let eps_bank_redirect_payment_method_data =
- PaymentMethodData::BankRedirect(BankRedirectData::Eps {
- billing_details: Some(bank_redirect_billing),
- bank_name: None,
- country: Some(TEST_COUNTRY),
- });
-
- let billing_address = eps_bank_redirect_payment_method_data
- .get_billing_address()
- .unwrap();
-
- let address_details = billing_address.address.unwrap();
-
- assert_eq!(billing_address.email.unwrap(), test_email);
- assert_eq!(address_details.country.unwrap(), TEST_COUNTRY);
- assert_eq!(address_details.first_name.unwrap(), test_first_name);
- assert!(billing_address.phone.is_none());
- }
-
- #[test]
- fn test_paylater_payment_method_data_klarna() {
- let test_email: Email = Email::try_from("[email protected]".to_string()).unwrap();
-
- let klarna_paylater_payment_method_data =
- PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {
- billing_email: Some(test_email.clone()),
- billing_country: Some(TEST_COUNTRY),
- });
-
- let billing_address = klarna_paylater_payment_method_data
- .get_billing_address()
- .unwrap();
-
- assert_eq!(billing_address.email.unwrap(), test_email);
- assert_eq!(
- billing_address.address.unwrap().country.unwrap(),
- TEST_COUNTRY
- );
- assert!(billing_address.phone.is_none());
- }
-
- #[test]
- fn test_bank_debit_payment_method_data_ach() {
- let test_email = Email::try_from("[email protected]".to_string()).unwrap();
- let test_first_name = Secret::new(String::from("Chaser"));
-
- let bank_redirect_billing = BankDebitBilling {
- name: Some(test_first_name.clone()),
- address: None,
- email: Some(test_email.clone()),
- };
-
- let ach_bank_debit_payment_method_data =
- PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
- billing_details: Some(bank_redirect_billing),
- account_number: Secret::new("1234".to_string()),
- routing_number: Secret::new("1235".to_string()),
- bank_account_holder_name: None,
- bank_name: None,
- bank_type: None,
- bank_holder_type: None,
- });
-
- let billing_address = ach_bank_debit_payment_method_data
- .get_billing_address()
- .unwrap();
-
- let address_details = billing_address.address.unwrap();
-
- assert_eq!(billing_address.email.unwrap(), test_email);
- assert_eq!(address_details.first_name.unwrap(), test_first_name);
- assert!(billing_address.phone.is_none());
- }
-
- #[test]
- fn test_card_payment_method_data() {
- let card_payment_method_data = PaymentMethodData::Card(Card {
- card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())),
- ..Default::default()
- });
-
- let billing_address = card_payment_method_data.get_billing_address();
-
- let billing_address = billing_address.unwrap();
-
- assert_eq!(
- billing_address.address.unwrap().first_name.expose_option(),
- Some(TEST_FIRST_NAME_SINGLE.into())
- );
- }
-
- #[test]
- fn test_card_payment_method_data_empty() {
- let card_payment_method_data = PaymentMethodData::Card(Card::default());
-
- let billing_address = card_payment_method_data.get_billing_address();
-
- assert!(billing_address.is_none());
- }
-
- #[test]
- fn test_card_payment_method_data_full_name() {
- let card_payment_method_data = PaymentMethodData::Card(Card {
- card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())),
- ..Default::default()
- });
-
- let billing_details = card_payment_method_data.get_billing_address().unwrap();
- let billing_address = billing_details.address.unwrap();
-
- assert_eq!(
- billing_address.first_name.expose_option(),
- Some(TEST_FIRST_NAME.into())
- );
-
- assert_eq!(
- billing_address.last_name.expose_option(),
- Some(TEST_LAST_NAME.into())
- );
- }
-
- #[test]
- fn test_card_payment_method_data_empty_string() {
- let card_payment_method_data = PaymentMethodData::Card(Card {
- card_holder_name: Some(Secret::new("".to_string())),
- ..Default::default()
- });
-
- let billing_details = card_payment_method_data.get_billing_address();
-
- assert!(billing_details.is_none());
- }
-}
-
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct PaymentRevenueRecoveryMetadata {
@@ -15158,20 +14755,6 @@ impl Serialize for NullObject {
}
}
-#[cfg(test)]
-mod null_object_test {
- use serde_json;
-
- use super::*;
-
- #[test]
- fn test_null_object_serialization() {
- let null_object = NullObject;
- let serialized = serde_json::to_string(&null_object).unwrap();
- assert_eq!(serialized, "null");
- }
-}
-
/// Represents external 3DS authentication data used in the payment flow.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ExternalThreeDsData {
diff --git a/crates/api_models/src/payments/tests.rs b/crates/api_models/src/payments/tests.rs
new file mode 100644
index 0000000000..15438ce30e
--- /dev/null
+++ b/crates/api_models/src/payments/tests.rs
@@ -0,0 +1,20 @@
+use super::*;
+
+/// Set of tests to extract billing details from payment method data.
+/// These are required for backwards compatibility.
+mod billing_from_payment_method_data;
+mod null_object;
+#[cfg(feature = "v1")]
+mod request;
+#[cfg(feature = "v1")]
+mod request_api_contract;
+mod response_api_contract;
+
+#[test]
+fn test_mandate_type() {
+ let mandate_type = MandateType::default();
+ assert_eq!(
+ serde_json::to_string(&mandate_type).unwrap(),
+ r#"{"multi_use":null}"#
+ )
+}
diff --git a/crates/api_models/src/payments/tests/billing_from_payment_method_data.rs b/crates/api_models/src/payments/tests/billing_from_payment_method_data.rs
new file mode 100644
index 0000000000..81e0eceada
--- /dev/null
+++ b/crates/api_models/src/payments/tests/billing_from_payment_method_data.rs
@@ -0,0 +1,173 @@
+use common_enums::CountryAlpha2;
+use hyperswitch_masking::ExposeOptionInterface;
+
+use super::super::*;
+
+const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US;
+const TEST_FIRST_NAME: &str = "John";
+const TEST_LAST_NAME: &str = "Wheat Dough";
+const TEST_FULL_NAME: &str = "John Wheat Dough";
+const TEST_FIRST_NAME_SINGLE: &str = "John";
+
+#[test]
+fn test_wallet_payment_method_data_paypal() {
+ let test_email: Email = Email::try_from("[email protected]".to_string()).unwrap();
+
+ let paypal_wallet_payment_method_data =
+ PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection {
+ email: Some(test_email.clone()),
+ payer_id: None,
+ }));
+
+ let billing_address = paypal_wallet_payment_method_data
+ .get_billing_address()
+ .unwrap();
+
+ assert_eq!(billing_address.email.unwrap(), test_email);
+
+ assert!(billing_address.address.is_none());
+ assert!(billing_address.phone.is_none());
+}
+
+#[test]
+fn test_bank_redirect_payment_method_data_eps() {
+ let test_email = Email::try_from("[email protected]".to_string()).unwrap();
+ let test_first_name = Secret::new(String::from("Chaser"));
+
+ let bank_redirect_billing = BankRedirectBilling {
+ billing_name: Some(test_first_name.clone()),
+ email: Some(test_email.clone()),
+ };
+
+ let eps_bank_redirect_payment_method_data =
+ PaymentMethodData::BankRedirect(BankRedirectData::Eps {
+ billing_details: Some(bank_redirect_billing),
+ bank_name: None,
+ country: Some(TEST_COUNTRY),
+ });
+
+ let billing_address = eps_bank_redirect_payment_method_data
+ .get_billing_address()
+ .unwrap();
+
+ let address_details = billing_address.address.unwrap();
+
+ assert_eq!(billing_address.email.unwrap(), test_email);
+ assert_eq!(address_details.country.unwrap(), TEST_COUNTRY);
+ assert_eq!(address_details.first_name.unwrap(), test_first_name);
+ assert!(billing_address.phone.is_none());
+}
+
+#[test]
+fn test_paylater_payment_method_data_klarna() {
+ let test_email: Email = Email::try_from("[email protected]".to_string()).unwrap();
+
+ let klarna_paylater_payment_method_data =
+ PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {
+ billing_email: Some(test_email.clone()),
+ billing_country: Some(TEST_COUNTRY),
+ });
+
+ let billing_address = klarna_paylater_payment_method_data
+ .get_billing_address()
+ .unwrap();
+
+ assert_eq!(billing_address.email.unwrap(), test_email);
+ assert_eq!(
+ billing_address.address.unwrap().country.unwrap(),
+ TEST_COUNTRY
+ );
+ assert!(billing_address.phone.is_none());
+}
+
+#[test]
+fn test_bank_debit_payment_method_data_ach() {
+ let test_email = Email::try_from("[email protected]".to_string()).unwrap();
+ let test_first_name = Secret::new(String::from("Chaser"));
+
+ let bank_redirect_billing = BankDebitBilling {
+ name: Some(test_first_name.clone()),
+ address: None,
+ email: Some(test_email.clone()),
+ };
+
+ let ach_bank_debit_payment_method_data =
+ PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
+ billing_details: Some(bank_redirect_billing),
+ account_number: Secret::new("1234".to_string()),
+ routing_number: Secret::new("1235".to_string()),
+ bank_account_holder_name: None,
+ bank_name: None,
+ bank_type: None,
+ bank_holder_type: None,
+ });
+
+ let billing_address = ach_bank_debit_payment_method_data
+ .get_billing_address()
+ .unwrap();
+
+ let address_details = billing_address.address.unwrap();
+
+ assert_eq!(billing_address.email.unwrap(), test_email);
+ assert_eq!(address_details.first_name.unwrap(), test_first_name);
+ assert!(billing_address.phone.is_none());
+}
+
+#[test]
+fn test_card_payment_method_data() {
+ let card_payment_method_data = PaymentMethodData::Card(Card {
+ card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())),
+ ..Default::default()
+ });
+
+ let billing_address = card_payment_method_data.get_billing_address();
+
+ let billing_address = billing_address.unwrap();
+
+ assert_eq!(
+ billing_address.address.unwrap().first_name.expose_option(),
+ Some(TEST_FIRST_NAME_SINGLE.into())
+ );
+}
+
+#[test]
+fn test_card_payment_method_data_empty() {
+ let card_payment_method_data = PaymentMethodData::Card(Card::default());
+
+ let billing_address = card_payment_method_data.get_billing_address();
+
+ assert!(billing_address.is_none());
+}
+
+#[test]
+fn test_card_payment_method_data_full_name() {
+ let card_payment_method_data = PaymentMethodData::Card(Card {
+ card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())),
+ ..Default::default()
+ });
+
+ let billing_details = card_payment_method_data.get_billing_address().unwrap();
+ let billing_address = billing_details.address.unwrap();
+
+ assert_eq!(
+ billing_address.first_name.expose_option(),
+ Some(TEST_FIRST_NAME.into())
+ );
+
+ assert_eq!(
+ billing_address.last_name.expose_option(),
+ Some(TEST_LAST_NAME.into())
+ );
+}
+
+#[test]
+fn test_card_payment_method_data_empty_string() {
+ let card_payment_method_data = PaymentMethodData::Card(Card {
+ card_holder_name: Some(Secret::new("".to_string())),
+ ..Default::default()
+ });
+
+ let billing_details = card_payment_method_data.get_billing_address();
+
+ assert!(billing_details.is_none());
+}
diff --git a/crates/api_models/src/payments/tests/null_object.rs b/crates/api_models/src/payments/tests/null_object.rs
new file mode 100644
index 0000000000..22f0f37581
--- /dev/null
+++ b/crates/api_models/src/payments/tests/null_object.rs
@@ -0,0 +1,10 @@
+use serde_json;
+
+use super::super::*;
+
+#[test]
+fn test_null_object_serialization() {
+ let null_object = NullObject;
+ let serialized = serde_json::to_string(&null_object).unwrap();
+ assert_eq!(serialized, "null");
+}
diff --git a/crates/api_models/src/payments/tests/request.rs b/crates/api_models/src/payments/tests/request.rs
new file mode 100644
index 0000000000..76852f4f88
--- /dev/null
+++ b/crates/api_models/src/payments/tests/request.rs
@@ -0,0 +1,70 @@
+use common_utils::generate_customer_id_of_default_length;
+
+use super::super::*;
+
+#[test]
+fn test_valid_case_where_customer_details_are_passed_only_once() {
+ let customer_id = generate_customer_id_of_default_length();
+ let payments_request = PaymentsRequest {
+ customer_id: Some(customer_id),
+ ..Default::default()
+ };
+
+ assert!(payments_request
+ .validate_customer_details_in_request()
+ .is_none());
+}
+
+#[test]
+fn test_valid_case_where_customer_id_is_passed_in_both_places() {
+ let customer_id = generate_customer_id_of_default_length();
+
+ let customer_object = CustomerDetails {
+ id: Some(customer_id.clone()),
+ name: None,
+ email: None,
+ phone: None,
+ phone_country_code: None,
+ tax_registration_id: None,
+ document_details: None,
+ date_of_birth: None,
+ };
+
+ let payments_request = PaymentsRequest {
+ customer_id: Some(customer_id),
+ customer: Some(customer_object),
+ ..Default::default()
+ };
+
+ assert!(payments_request
+ .validate_customer_details_in_request()
+ .is_none());
+}
+
+#[test]
+fn test_invalid_case_where_customer_id_is_passed_in_both_places() {
+ let customer_id = generate_customer_id_of_default_length();
+ let another_customer_id = generate_customer_id_of_default_length();
+
+ let customer_object = CustomerDetails {
+ id: Some(customer_id.clone()),
+ name: None,
+ email: None,
+ phone: None,
+ phone_country_code: None,
+ tax_registration_id: None,
+ document_details: None,
+ date_of_birth: None,
+ };
+
+ let payments_request = PaymentsRequest {
+ customer_id: Some(another_customer_id),
+ customer: Some(customer_object),
+ ..Default::default()
+ };
+
+ assert_eq!(
+ payments_request.validate_customer_details_in_request(),
+ Some(vec!["customer_id and customer.id"])
+ );
+}
diff --git a/crates/api_models/src/payments/tests/request_api_contract.rs b/crates/api_models/src/payments/tests/request_api_contract.rs
new file mode 100644
index 0000000000..092fd676fc
--- /dev/null
+++ b/crates/api_models/src/payments/tests/request_api_contract.rs
@@ -0,0 +1,97 @@
+use std::str::FromStr;
+
+use super::super::*;
+
+#[test]
+fn test_successful_card_deser() {
+ let payments_request = r#"
+ {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method": "card",
+ "payment_method_data": {
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "10",
+ "card_exp_year": "25",
+ "card_holder_name": "joseph Doe",
+ "card_cvc": "123"
+ }
+ }
+ }
+ "#;
+
+ let expected_card_number_string = "4242424242424242";
+ let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap();
+
+ let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request);
+ assert!(payments_request.is_ok());
+
+ if let Some(PaymentMethodData::Card(card_data)) = payments_request
+ .unwrap()
+ .payment_method_data
+ .unwrap()
+ .payment_method_data
+ {
+ assert_eq!(card_data.card_number, expected_card_number);
+ } else {
+ panic!("Received unexpected response")
+ }
+}
+
+#[test]
+fn test_successful_payment_method_reward() {
+ let payments_request = r#"
+ {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method": "reward",
+ "payment_method_data": "reward",
+ "payment_method_type": "evoucher"
+ }
+ "#;
+
+ let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request);
+ assert!(payments_request.is_ok());
+ assert_eq!(
+ payments_request
+ .unwrap()
+ .payment_method_data
+ .unwrap()
+ .payment_method_data,
+ Some(PaymentMethodData::Reward)
+ );
+}
+
+#[test]
+fn test_payment_method_data_with_payment_method_billing() {
+ let payments_request = r#"
+ {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method_data": {
+ "billing": {
+ "address": {
+ "line1": "1467",
+ "line2": "Harrison Street",
+ "city": "San Fransico",
+ "state": "California",
+ "zip": "94122",
+ "country": "US",
+ "first_name": "Narayan",
+ "last_name": "Bhat"
+ }
+ }
+ }
+ }
+ "#;
+
+ let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request);
+ assert!(payments_request.is_ok());
+ assert!(payments_request
+ .unwrap()
+ .payment_method_data
+ .unwrap()
+ .billing
+ .is_some());
+}
diff --git a/crates/api_models/src/payments/tests/response_api_contract.rs b/crates/api_models/src/payments/tests/response_api_contract.rs
new file mode 100644
index 0000000000..a0b24d6ef7
--- /dev/null
+++ b/crates/api_models/src/payments/tests/response_api_contract.rs
@@ -0,0 +1,37 @@
+use super::super::*;
+
+#[derive(Debug, serde::Serialize)]
+struct TestPaymentsResponse {
+ #[serde(serialize_with = "serialize_payment_method_data_response")]
+ payment_method_data: Option<PaymentMethodDataResponseWithBilling>,
+}
+
+#[test]
+fn test_reward_payment_response() {
+ let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling {
+ payment_method_data: Some(PaymentMethodDataResponse::Reward {}),
+ billing: None,
+ };
+
+ let payments_response = TestPaymentsResponse {
+ payment_method_data: Some(payment_method_response_with_billing),
+ };
+
+ let expected_response = r#"{"payment_method_data":"reward"}"#;
+
+ let stringified_payments_response = payments_response.encode_to_string_of_json();
+ assert_eq!(stringified_payments_response.unwrap(), expected_response);
+}
+
+#[cfg(feature = "v1")]
+#[test]
+fn test_fingerprint_type_serialization() {
+ assert_eq!(
+ serde_json::to_value(FingerprintType::Dpan).unwrap(),
+ serde_json::json!("dpan")
+ );
+ assert_eq!(
+ serde_json::to_value(FingerprintType::Fpan).unwrap(),
+ serde_json::json!("fpan")
+ );
+}
diff --git a/crates/api_models/tests/callback_url_secrets.rs b/crates/api_models/tests/callback_url_secrets.rs
new file mode 100644
index 0000000000..4ba3e43964
--- /dev/null
+++ b/crates/api_models/tests/callback_url_secrets.rs
@@ -0,0 +1,82 @@
+#![cfg(feature = "v1")]
+
+use api_models::payments::{
+ NextActionData, PollConfigResponse, RedirectionResponse, ThreeDsData, ThreeDsMethodData,
+};
+use hyperswitch_masking::Secret;
+
+const CALLBACK_TOKEN: &str = "d9dc53cc-d1a1-4f57-9077-d20c2d614daa";
+const CALLBACK_URL: &str = "https://router.test/payments/pay/merchant/redirect/token/d9dc53cc-d1a1-4f57-9077-d20c2d614daa/authorize/stripe";
+
+#[cfg(test)]
+fn assert_secret_serialization<T: serde::Serialize + std::fmt::Debug>(
+ response: &T,
+ url_fields: &[&str],
+) {
+ let wire = serde_json::to_value(response).expect("wire response");
+ for field in url_fields {
+ assert_eq!(
+ wire.pointer(field).and_then(serde_json::Value::as_str),
+ Some(CALLBACK_URL)
+ );
+ }
+ let logged = hyperswitch_masking::masked_serialize(response).expect("masked response");
+ assert!(!logged.to_string().contains(CALLBACK_TOKEN));
+ assert!(!format!("{response:?}").contains(CALLBACK_TOKEN));
+}
+
+#[test]
+fn callback_urls_remain_strings_on_the_wire_and_are_masked_in_logs() {
+ let url = || Secret::new(CALLBACK_URL.to_string());
+ assert_secret_serialization(
+ &NextActionData::RedirectToUrl {
+ redirect_to_url: url(),
+ },
+ &["/redirect_to_url"],
+ );
+ assert_secret_serialization(
+ &NextActionData::RedirectInsidePopup {
+ popup_url: url(),
+ redirect_response_url: url(),
+ },
+ &["/popup_url", "/redirect_response_url"],
+ );
+ assert_secret_serialization(
+ &NextActionData::ThreeDsInvoke {
+ three_ds_data: ThreeDsData {
+ three_ds_authentication_url: url(),
+ three_ds_authorize_url: url(),
+ three_ds_method_details: ThreeDsMethodData::AcsThreeDsMethodData {
+ three_ds_method_data_submission: false,
+ three_ds_method_data: None,
+ three_ds_method_url: None,
+ three_ds_method_key: None,
+ consume_post_message_for_three_ds_method_completion: false,
+ },
+ poll_config: PollConfigResponse {
+ poll_id: "poll_test".to_string(),
+ delay_in_secs: 1,
+ frequency: 1,
+ },
+ message_version: None,
+ directory_server_id: None,
+ card_network: None,
+ three_ds_connector: None,
+ },
+ },
+ &[
+ "/three_ds_data/three_ds_authentication_url",
+ "/three_ds_data/three_ds_authorize_url",
+ ],
+ );
+ assert_secret_serialization(
+ &RedirectionResponse {
+ return_url: String::new(),
+ params: vec![("return_url".to_string(), url())],
+ return_url_with_query_params: url(),
+ http_method: "GET".to_string(),
+ headers: vec![],
+ },
+ &["/return_url_with_query_params", "/params/0/1"],
+ );
+}
diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs
index 5e03c33b7e..37b1e49bce 100644
--- a/crates/diesel_models/src/authentication.rs
+++ b/crates/diesel_models/src/authentication.rs
@@ -1,5 +1,6 @@
use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
+use hyperswitch_masking::Secret;
use serde::{self, Deserialize, Serialize};
use crate::schema::authentication;
@@ -52,7 +53,7 @@ pub struct Authentication {
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
pub amount: Option<common_utils::types::MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub billing_address: Option<Encryption>,
@@ -164,7 +165,7 @@ pub struct AuthenticationNew {
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
pub amount: Option<common_utils::types::MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub billing_address: Option<Encryption>,
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 1c1ebf8c2d..5575aaabae 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -4735,12 +4735,12 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub enum RedirectForm {
Form {
- endpoint: String,
+ endpoint: hyperswitch_masking::Secret<String>,
method: common_utils::request::Method,
- form_fields: std::collections::HashMap<String, String>,
+ form_fields: std::collections::HashMap<String, hyperswitch_masking::Secret<String>>,
},
Html {
- html_data: String,
+ html_data: hyperswitch_masking::Secret<String>,
},
BarclaycardAuthSetup {
access_token: String,
@@ -4772,7 +4772,7 @@ pub enum RedirectForm {
client_token: String,
card_token: String,
bin: String,
- acs_url: String,
+ acs_url: hyperswitch_masking::Secret<String>,
},
Nmi {
amount: String,
@@ -4826,97 +4826,4 @@ pub struct PaymentAttemptRecoveryData {
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(PaymentAttemptFeatureMetadata);
-mod tests {
-
- #[test]
- fn test_backwards_compatibility() {
- let serialized_payment_attempt = r#"{
- "payment_id": "PMT123456789",
- "merchant_id": "M123456789",
- "attempt_id": "ATMPT123456789",
- "status": "pending",
- "amount": 10000,
- "currency": "USD",
- "save_to_locker": true,
- "connector": "stripe",
- "error_message": null,
- "offer_amount": 9500,
- "surcharge_amount": 500,
- "tax_amount": 800,
- "payment_method_id": "CRD123456789",
- "payment_method": "card",
- "connector_transaction_id": "CNTR123456789",
- "capture_method": "automatic",
- "capture_on": "2022-09-10T10:11:12Z",
- "confirm": false,
- "authentication_type": "no_three_ds",
- "created_at": "2024-02-26T12:00:00Z",
- "modified_at": "2024-02-26T12:00:00Z",
- "last_synced": null,
- "cancellation_reason": null,
- "amount_to_capture": 10000,
- "mandate_id": null,
- "browser_info": {
- "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
- "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
- "language": "nl-NL",
- "color_depth": 24,
- "screen_height": 723,
- "screen_width": 1536,
- "time_zone": 0,
- "java_enabled": true,
- "java_script_enabled": true,
- "ip_address": "127.0.0.1"
- },
- "error_code": null,
- "payment_token": "TOKEN123456789",
- "connector_metadata": null,
- "payment_experience": "redirect_to_url",
- "payment_method_type": "credit",
- "payment_method_data": {
- "card": {
- "card_number": "4242424242424242",
- "card_exp_month": "10",
- "card_cvc": "123",
- "card_exp_year": "2024",
- "card_holder_name": "John Doe"
- }
- },
- "business_sub_label": "Premium",
- "straight_through_algorithm": null,
- "preprocessing_step_id": null,
- "mandate_details": null,
- "error_reason": null,
- "multiple_capture_count": 0,
- "connector_response_reference_id": null,
- "amount_capturable": 10000,
- "updated_by": "redis_kv",
- "merchant_connector_id": "MCN123456789",
- "authentication_data": null,
- "encoded_data": null,
- "unified_code": null,
- "unified_message": null,
- "net_amount": 10200,
- "mandate_data": {
- "customer_acceptance": {
- "acceptance_type": "offline",
- "accepted_at": "1963-05-03T04:07:52.723Z",
- "online": {
- "ip_address": "127.0.0.1",
- "user_agent": "amet irure esse"
- }
- },
- "single_use": {
- "amount": 6540,
- "currency": "USD"
- }
- }
-},
- "fingerprint_id": null
-}"#;
- let deserialized =
- serde_json::from_str::<super::PaymentAttempt>(serialized_payment_attempt);
-
- assert!(deserialized.is_ok());
- }
-}
+mod tests;
diff --git a/crates/diesel_models/src/payment_attempt/tests.rs b/crates/diesel_models/src/payment_attempt/tests.rs
new file mode 100644
index 0000000000..076e75cf98
--- /dev/null
+++ b/crates/diesel_models/src/payment_attempt/tests.rs
@@ -0,0 +1,90 @@
+#[test]
+fn test_backwards_compatibility() {
+ let serialized_payment_attempt = r#"{
+ "payment_id": "PMT123456789",
+ "merchant_id": "M123456789",
+ "attempt_id": "ATMPT123456789",
+ "status": "pending",
+ "amount": 10000,
+ "currency": "USD",
+ "save_to_locker": true,
+ "connector": "stripe",
+ "error_message": null,
+ "offer_amount": 9500,
+ "surcharge_amount": 500,
+ "tax_amount": 800,
+ "payment_method_id": "CRD123456789",
+ "payment_method": "card",
+ "connector_transaction_id": "CNTR123456789",
+ "capture_method": "automatic",
+ "capture_on": "2022-09-10T10:11:12Z",
+ "confirm": false,
+ "authentication_type": "no_three_ds",
+ "created_at": "2024-02-26T12:00:00Z",
+ "modified_at": "2024-02-26T12:00:00Z",
+ "last_synced": null,
+ "cancellation_reason": null,
+ "amount_to_capture": 10000,
+ "mandate_id": null,
+ "browser_info": {
+ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
+ "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
+ "language": "nl-NL",
+ "color_depth": 24,
+ "screen_height": 723,
+ "screen_width": 1536,
+ "time_zone": 0,
+ "java_enabled": true,
+ "java_script_enabled": true,
+ "ip_address": "127.0.0.1"
+ },
+ "error_code": null,
+ "payment_token": "TOKEN123456789",
+ "connector_metadata": null,
+ "payment_experience": "redirect_to_url",
+ "payment_method_type": "credit",
+ "payment_method_data": {
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "10",
+ "card_cvc": "123",
+ "card_exp_year": "2024",
+ "card_holder_name": "John Doe"
+ }
+ },
+ "business_sub_label": "Premium",
+ "straight_through_algorithm": null,
+ "preprocessing_step_id": null,
+ "mandate_details": null,
+ "error_reason": null,
+ "multiple_capture_count": 0,
+ "connector_response_reference_id": null,
+ "amount_capturable": 10000,
+ "updated_by": "redis_kv",
+ "merchant_connector_id": "MCN123456789",
+ "authentication_data": null,
+ "encoded_data": null,
+ "unified_code": null,
+ "unified_message": null,
+ "net_amount": 10200,
+ "mandate_data": {
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
+ "single_use": {
+ "amount": 6540,
+ "currency": "USD"
+ }
+ }
+},
+ "fingerprint_id": null
+}"#;
+ let deserialized = serde_json::from_str::<super::PaymentAttempt>(serialized_payment_attempt);
+
+ assert!(deserialized.is_ok());
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
index 0dc0621451..8ba82d3fea 100644
--- a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
@@ -126,7 +126,7 @@ pub struct AciPaymentsRequest {
pub payment_method: PaymentDetails,
#[serde(flatten)]
pub instruction: Option<Instruction>,
- pub shopper_result_url: Option<String>,
+ pub shopper_result_url: Option<Secret<String>>,
#[serde(rename = "customParameters[3DS2_enrolled]")]
pub three_ds_two_enrolled: Option<bool>,
pub recurring_type: Option<AciRecurringType>,
@@ -1412,11 +1412,14 @@ where
// If method is Get, parameters are appended to URL
// If method is post, we http Post the method to URL
RedirectForm::Form {
- endpoint: data.url.to_string(),
+ endpoint: data.url.to_string().into(),
// Handles method for Bank redirects currently.
// 3DS response have method within preconditions. That would require replacing below line with a function.
method: data.method.unwrap_or(Method::Post),
- form_fields,
+ form_fields: (form_fields)
+ .into_iter()
+ .map(|(key, value)| (key, value.into()))
+ .collect(),
}
});
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs
index c4af3ce0af..9b4b5a54c8 100644
--- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs
@@ -354,7 +354,7 @@ pub struct AdyenPaymentRequest<'a> {
payment_method: PaymentMethod<'a>,
mpi_data: Option<AdyenMpiData>,
reference: String,
- return_url: String,
+ return_url: Secret<String>,
browser_info: Option<AdyenBrowserInfo>,
shopper_interaction: AdyenShopperInteraction,
recurring_processing_model: Option<AdyenRecurringModel>,
@@ -4641,9 +4641,12 @@ pub fn get_redirection_response(
)
});
RedirectForm::Form {
- endpoint: url.to_string(),
+ endpoint: url.to_string().into(),
method: response.action.method.unwrap_or(Method::Get),
- form_fields,
+ form_fields: (form_fields)
+ .into_iter()
+ .map(|(key, value)| (key, value.into()))
+ .collect(),
}
});
diff --git a/crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs b/crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
index 74a7a9e426..9fd0264ed3 100644
--- a/crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
@@ -85,8 +85,8 @@ impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for AffirmCompleteAuthorizeRe
#[derive(Debug, Serialize)]
pub struct Merchant {
pub public_api_key: Secret<String>,
- pub user_confirmation_url: String,
- pub user_cancel_url: String,
+ pub user_confirmation_url: Secret<String>,
+ pub user_cancel_url: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Shipping {
diff --git a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
index 4198b5ee9d..cd8faad399 100644
--- a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
@@ -187,7 +187,7 @@ pub struct AirwallexPaymentsRequest {
request_id: String,
payment_method: Option<AirwallexPaymentMethod>,
payment_method_options: Option<AirwallexPaymentOptions>,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
device_data: Option<DeviceData>,
payment_consent: Option<PaymentConsentData>,
customer_id: Option<String>,
@@ -1221,7 +1221,7 @@ pub enum AirwallexAuthorizeResponse {
fn get_redirection_form(response_url_data: AirwallexPaymentsNextAction) -> Option<RedirectForm> {
Some(RedirectForm::Form {
- endpoint: response_url_data.url.to_string(),
+ endpoint: response_url_data.url.to_string().into(),
method: response_url_data.method,
form_fields: response_url_data
.data
@@ -1230,22 +1230,25 @@ fn get_redirection_form(response_url_data: AirwallexPaymentsNextAction) -> Optio
//Some form fields might be empty based on the authentication type by the connector
(
"JWT".to_string(),
- data.jwt.map(|jwt| jwt.expose()).unwrap_or_default(),
+ data.jwt.unwrap_or_else(|| Secret::new(String::new())),
),
(
"threeDSMethodData".to_string(),
data.three_ds_method_data
- .map(|three_ds_method_data| three_ds_method_data.expose())
- .unwrap_or_default(),
+ .unwrap_or_else(|| Secret::new(String::new())),
),
(
"token".to_string(),
- data.token
- .map(|token: Secret<String>| token.expose())
- .unwrap_or_default(),
+ data.token.unwrap_or_else(|| Secret::new(String::new())),
+ ),
+ (
+ "provider".to_string(),
+ data.provider.unwrap_or_default().into(),
+ ),
+ (
+ "version".to_string(),
+ data.version.unwrap_or_default().into(),
),
- ("provider".to_string(), data.provider.unwrap_or_default()),
- ("version".to_string(), data.version.unwrap_or_default()),
])
})
.unwrap_or_default(),
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
index f8561f044c..3b6376edcf 100644
--- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
@@ -127,8 +127,8 @@ enum PaymentDetails {
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PayPalDetails {
- pub success_url: Option<String>,
- pub cancel_url: Option<String>,
+ pub success_url: Option<Secret<String>>,
+ pub cancel_url: Option<Secret<String>>,
}
#[derive(Serialize, Debug, Deserialize)]
@@ -2476,7 +2476,7 @@ impl TryFrom<AuthorizedotnetWebhookObjectId> for AuthorizedotnetSyncResponse {
fn get_wallet_data(
wallet_data: &WalletData,
- return_url: &Option<String>,
+ return_url: &Option<Secret<String>>,
) -> CustomResult<PaymentDetails, errors::ConnectorError> {
match wallet_data {
WalletData::GooglePay(_) => Ok(PaymentDetails::OpaqueData(WalletDetails {
diff --git a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
index b805d2e60e..2394c8edc7 100644
--- a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
@@ -85,7 +85,7 @@ pub struct BamboraPaymentsRequest {
amount: FloatMajorUnit,
payment_method: PaymentMethod,
customer_ip: Option<Secret<String, IpAddress>>,
- term_url: Option<String>,
+ term_url: Option<Secret<String>>,
card: BamboraCard,
billing: AddressData,
}
@@ -332,7 +332,7 @@ pub struct BamboraPaymentsResponse {
pub struct Bambora3DsResponse {
#[serde(rename = "3d_session_data")]
three_d_session_data: Secret<String>,
- contents: String,
+ contents: Secret<String>,
}
#[derive(Debug, Serialize, Default, Deserialize)]
@@ -491,10 +491,13 @@ impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, Pa
}),
BamboraResponse::ThreeDsResponse(response) => {
- let value = url::form_urlencoded::parse(response.contents.as_bytes())
- .map(|(key, val)| [key, val].concat())
- .collect();
- let redirection_data = Some(RedirectForm::Html { html_data: value });
+ let value: String =
+ url::form_urlencoded::parse(response.contents.peek().as_bytes())
+ .map(|(key, val)| [key, val].concat())
+ .collect();
+ let redirection_data = Some(RedirectForm::Html {
+ html_data: value.into(),
+ });
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs
index ba0c6200fe..6d8decfb8c 100644
--- a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs
+++ b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs
@@ -29,8 +29,8 @@ use hyperswitch_domain_models::{
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
- SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback, RedirectForm,
+ RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
@@ -1526,6 +1526,22 @@ static BARCLAYCARD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
static BARCLAYCARD_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
+impl api::ConnectorRedirectResponse for Barclaycard {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::BarclaycardAuthSetup { .. })
+ .then_some(RedirectCallback::Complete)
+ }
+
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ _action: enums::PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
+ Ok(enums::CallConnectorAction::Trigger)
+ }
+}
+
impl ConnectorSpecifications for Barclaycard {
fn is_pre_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo) -> bool {
match current_flow {
diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
index d5036b8004..ed763b9039 100644
--- a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
@@ -774,7 +774,7 @@ pub struct BarclaycardRedirectionAuthResponse {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationRequest {
- return_url: String,
+ return_url: Secret<String>,
reference_id: String,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
index 0540b36d25..bedc8d6a28 100644
--- a/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
@@ -46,7 +46,7 @@ pub struct BitpayPaymentsRequest {
price: FloatMajorUnit,
currency: String,
#[serde(rename = "redirectURL")]
- redirect_url: String,
+ redirect_url: Secret<String>,
#[serde(rename = "notificationURL")]
notification_url: String,
transaction_speed: TransactionSpeed,
@@ -129,7 +129,7 @@ pub struct BitpayPaymentResponseData {
pub low_fee_detected: Option<bool>,
pub display_amount_paid: Option<String>,
pub exception_status: ExceptionStatus,
- pub redirect_url: Option<String>,
+ pub redirect_url: Option<Secret<String>>,
pub refund_address_request_pending: Option<bool>,
pub merchant_name: Option<Secret<String>>,
pub token: Option<Secret<String>>,
diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs
index fef8c472cc..e58a30b940 100644
--- a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs
@@ -31,7 +31,7 @@ use hyperswitch_domain_models::{
PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectForm,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback, RedirectForm,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
@@ -1228,6 +1228,10 @@ impl IncomingWebhook for Bluesnap {
}
impl ConnectorRedirectResponse for Bluesnap {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::BlueSnap { .. }).then_some(RedirectCallback::Complete)
+ }
+
fn get_flow_type(
&self,
_query_params: &str,
diff --git a/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs b/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
index 33640bb81e..b3a4432345 100644
--- a/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
@@ -94,7 +94,7 @@ impl fmt::Display for BokuChargeType {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
struct BokuHostedData {
- forward_url: String,
+ forward_url: Secret<String>,
}
impl TryFrom<&BokuRouterData<&types::PaymentsAuthorizeRouterData>> for BokuPaymentsRequest {
diff --git a/crates/hyperswitch_connectors/src/connectors/braintree.rs b/crates/hyperswitch_connectors/src/connectors/braintree.rs
index f763122b12..98d951bbc0 100644
--- a/crates/hyperswitch_connectors/src/connectors/braintree.rs
+++ b/crates/hyperswitch_connectors/src/connectors/braintree.rs
@@ -35,7 +35,8 @@ use hyperswitch_domain_models::{
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData,
- RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ RedirectCallback, RedirectForm, RefundsResponseData, SupportedPaymentMethods,
+ SupportedPaymentMethodsExt,
},
types::{
MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
@@ -1190,6 +1191,10 @@ fn decode_webhook_payload(
}
impl ConnectorRedirectResponse for Braintree {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::Braintree { .. }).then_some(RedirectCallback::Response)
+ }
+
fn get_flow_type(
&self,
_query_params: &str,
diff --git a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
index 297652f927..e80f6eff68 100644
--- a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
@@ -2722,7 +2722,7 @@ fn get_braintree_redirect_form(
client_token_data: ClientTokenResponse,
payment_method_token: PaymentMethodToken,
card_details: PaymentMethodData,
- complete_authorize_url: String,
+ complete_authorize_url: Secret<String>,
) -> Result<RedirectForm, error_stack::Report<errors::ConnectorError>> {
Ok(RedirectForm::Braintree {
client_token: client_token_data
diff --git a/crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs
index f7c391e3df..4a803be1fc 100644
--- a/crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs
@@ -42,8 +42,8 @@ pub struct BreadpayCartRequest {
#[serde(rename_all = "camelCase")]
pub struct BreadpayCartOptions {
order_ref: Option<String>,
- complete_url: String,
- callback_url: String,
+ complete_url: Secret<String>,
+ callback_url: Secret<String>,
// billing_contact: Option<BillingContact>,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/calida/transformers.rs b/crates/hyperswitch_connectors/src/connectors/calida/transformers.rs
index 58a21d3627..be04c18934 100644
--- a/crates/hyperswitch_connectors/src/connectors/calida/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/calida/transformers.rs
@@ -74,8 +74,8 @@ pub struct CalidaPaymentsRequest {
pub billing_address_line1: Secret<String>,
pub billing_address_postal_code: Secret<String>,
pub webhook_url: String,
- pub success_url: String,
- pub failure_url: String,
+ pub success_url: Secret<String>,
+ pub failure_url: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
@@ -234,8 +234,8 @@ pub struct CalidaSyncResponse {
pub billing_address_country: Option<String>,
pub billing_address_country_code_iso: Option<enums::CountryAlpha2>,
pub shipping_address_country_code_iso: Option<enums::CountryAlpha2>,
- pub success_url: Option<String>,
- pub failure_url: Option<String>,
+ pub success_url: Option<Secret<String>>,
+ pub failure_url: Option<Secret<String>>,
pub source: Option<String>,
pub bonus_code: Option<String>,
pub dob: Option<String>,
diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
index 9e0f47f057..cf12419a6d 100644
--- a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
@@ -32,8 +32,8 @@ pub struct CashtocodePaymentsRequest {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
user_alias: Secret<id_type::CustomerId>,
- requested_url: String,
- cancel_url: String,
+ requested_url: Secret<String>,
+ cancel_url: Secret<String>,
email: Option<Email>,
mid: Secret<String>,
}
@@ -64,7 +64,7 @@ impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePayme
) -> Result<Self, Self::Error> {
let customer_id = item.get_customer_id()?;
let url = match env::which() {
- Env::Development => "https://example.com".to_string(),
+ Env::Development => "https://example.com".to_string().into(),
_ => item.request.get_router_return_url()?,
};
let mid = get_mid(
@@ -213,7 +213,7 @@ fn get_redirect_form_data(
match payment_method_type {
enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
- endpoint: response_data.pay_url.to_string(),
+ endpoint: response_data.pay_url.to_string().into(),
method: Method::Post,
form_fields: Default::default(),
}),
diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
index fcb2b09c06..d465c3d959 100644
--- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
@@ -358,8 +358,8 @@ pub struct CheckoutAuthType {
#[derive(Debug, Serialize)]
pub struct ReturnUrl {
- pub success_url: Option<String>,
- pub failure_url: Option<String>,
+ pub success_url: Option<Secret<String>>,
+ pub failure_url: Option<Secret<String>>,
}
#[skip_serializing_none]
@@ -1168,13 +1168,15 @@ impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequ
.request
.router_return_url
.as_ref()
- .map(|return_url| format!("{return_url}?status=success")),
+ .map(|return_url| utils::append_url_query_param(return_url, "status", "success"))
+ .transpose()?,
failure_url: item
.router_data
.request
.router_return_url
.as_ref()
- .map(|return_url| format!("{return_url}?status=failure")),
+ .map(|return_url| utils::append_url_query_param(return_url, "status", "failure"))
+ .transpose()?,
};
let connector_auth = &item.router_data.connector_auth_type;
diff --git a/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
index b7341ed3ee..30424b9a31 100644
--- a/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
@@ -54,8 +54,8 @@ pub struct CoinbasePaymentsRequest {
pub description: Option<String>,
pub pricing_type: String,
pub local_price: LocalPrice,
- pub redirect_url: String,
- pub cancel_url: String,
+ pub redirect_url: Secret<String>,
+ pub cancel_url: Secret<String>,
}
impl TryFrom<&CoinbaseRouterData<&PaymentsAuthorizeRouterData>> for CoinbasePaymentsRequest {
@@ -147,7 +147,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsRe
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
let redirection_data = RedirectForm::Form {
- endpoint: item.response.data.hosted_url.to_string(),
+ endpoint: item.response.data.hosted_url.to_string().into(),
method: Method::Get,
form_fields,
};
@@ -355,7 +355,7 @@ pub enum WebhookEventType {
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Redirects {
- cancel_url: Option<String>,
+ cancel_url: Option<Secret<String>>,
success_url: Option<String>,
will_redirect_after_success: bool,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs
index 2301a16721..e2bdae579f 100644
--- a/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs
@@ -58,8 +58,8 @@ pub struct CoingatePaymentsRequest {
price_currency: Currency,
receive_currency: String,
callback_url: String,
- success_url: Option<String>,
- cancel_url: Option<String>,
+ success_url: Option<Secret<String>>,
+ cancel_url: Option<Secret<String>>,
title: String,
token: Secret<String>,
}
@@ -181,11 +181,12 @@ impl<F, T> TryFrom<ResponseRouterData<F, CoingatePaymentsResponse, T, PaymentsRe
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(Some(RedirectForm::Form {
- endpoint: item.response.payment_url.clone().ok_or(
+ endpoint: (item.response.payment_url.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_url".into(),
},
- )?,
+ )?)
+ .into(),
method: Method::Get,
form_fields: HashMap::new(),
})),
diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
index 4775fa9120..cd0e26db38 100644
--- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
@@ -42,8 +42,8 @@ pub struct CryptopayPaymentsRequest {
pay_currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
network: Option<String>,
- success_redirect_url: Option<String>,
- unsuccess_redirect_url: Option<String>,
+ success_redirect_url: Option<Secret<String>>,
+ unsuccess_redirect_url: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<pii::SecretSerdeValue>,
custom_id: String,
@@ -261,8 +261,8 @@ pub struct CryptopayPaymentResponseData {
pub paid_amount: Option<String>,
pub name: Option<String>,
pub description: Option<String>,
- pub success_redirect_url: Option<String>,
- pub unsuccess_redirect_url: Option<String>,
+ pub success_redirect_url: Option<Secret<String>>,
+ pub unsuccess_redirect_url: Option<Secret<String>>,
pub hosted_page_url: Option<Url>,
pub created_at: Option<String>,
pub expires_at: Option<String>,
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs
index 432d381808..6776574cdd 100644
--- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs
@@ -33,7 +33,8 @@ use hyperswitch_domain_models::{
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData,
- RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ RedirectCallback, RedirectForm, RefundsResponseData, SupportedPaymentMethods,
+ SupportedPaymentMethodsExt,
},
types::{
MandateRevokeRouterData, PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData,
@@ -2366,6 +2367,22 @@ static CYBERSOURCE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
static CYBERSOURCE_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = [];
+impl api::ConnectorRedirectResponse for Cybersource {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::CybersourceAuthSetup { .. })
+ .then_some(RedirectCallback::Complete)
+ }
+
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ _action: enums::PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
+ Ok(enums::CallConnectorAction::Trigger)
+ }
+}
+
impl ConnectorSpecifications for Cybersource {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CYBERSOURCE_CONNECTOR_INFO)
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
index 5d650bafbb..8056227e4f 100644
--- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
@@ -584,7 +584,7 @@ pub struct CybersourceConsumerAuthInformation {
/// The URL to which the cardholder's browser is redirected after the 3DS challenge is completed.
/// Required when requesting Cybersource to perform payer authentication inline (e.g. Google Pay PAN_ONLY with 3DS).
#[serde(skip_serializing_if = "Option::is_none")]
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
/// Reference ID used to correlate the payer authentication request
/// (the Cardinal device-data-collection session id for 3DS).
#[serde(skip_serializing_if = "Option::is_none")]
@@ -3718,7 +3718,7 @@ impl From<&api_models::payments::DeviceChannel> for CybersourceDeviceChannel {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationRequest {
- return_url: String,
+ return_url: Secret<String>,
reference_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
challenge_code: Option<String>,
diff --git a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
index 0af1d787f9..b1d63c4b13 100644
--- a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
@@ -72,9 +72,9 @@ pub struct DataTransCreateAlias {
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RedirectUrls {
- pub success_url: Option<String>,
- pub cancel_url: Option<String>,
- pub error_url: Option<String>,
+ pub success_url: Option<Secret<String>>,
+ pub cancel_url: Option<Secret<String>>,
+ pub error_url: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
@@ -640,7 +640,8 @@ impl<F>
response.transaction_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
- endpoint: format!("{}/{}", redirection_link, response.transaction_id),
+ endpoint: (format!("{}/{}", redirection_link, response.transaction_id))
+ .into(),
method: Method::Get,
form_fields: HashMap::new(),
})),
@@ -720,7 +721,8 @@ impl<F>
response.transaction_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
- endpoint: format!("{}/{}", redirection_link, response.transaction_id),
+ endpoint: (format!("{}/{}", redirection_link, response.transaction_id))
+ .into(),
method: Method::Get,
form_fields: HashMap::new(),
})),
diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
index da25d55673..2c2b95c03d 100644
--- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
@@ -201,8 +201,8 @@ pub struct DeutschebankThreeDSInitializeRequestTds20Data {
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCommunicationData {
- method_notification_url: String,
- cres_notification_url: String,
+ method_notification_url: Secret<String>,
+ cres_notification_url: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -597,10 +597,13 @@ impl
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: item.data.request.get_complete_authorize_url()?,
method: common_utils::request::Method::Get,
- form_fields: HashMap::from([
+ form_fields: (HashMap::from([
("reference".to_string(), reference.clone()),
("signed_on".to_string(), signed_on.clone()),
- ]),
+ ]))
+ .into_iter()
+ .map(|(key, value)| (key, value.into()))
+ .collect(),
})),
mandate_reference: if item.data.request.is_mandate_payment() {
Box::new(Some(MandateReference {
diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
index e6c4070f95..4175f620d2 100644
--- a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
@@ -86,7 +86,7 @@ pub struct DlocalPaymentsRequest {
pub card: Option<Card>,
pub order_id: String,
pub three_dsecure: Option<ThreeDSecureReqData>,
- pub callback_url: Option<String>,
+ pub callback_url: Option<Secret<String>>,
pub description: Option<String>,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs
index b9db3a86a6..01b7191bcf 100644
--- a/crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs
@@ -88,7 +88,7 @@ pub struct DummyConnectorPaymentsRequest<const T: u8> {
amount: MinorUnit,
currency: Currency,
payment_method_data: DummyPaymentMethodData,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
connector: DummyConnectors,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
index 10fdbc908a..9d5a0555fd 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
@@ -110,8 +110,8 @@ pub struct FiservInteractions {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservReturnUrls {
- success_url: String,
- cancel_url: String,
+ success_url: Secret<String>,
+ cancel_url: Secret<String>,
}
#[derive(Debug, Serialize)]
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
index 25f76eeee0..a90527ca9c 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
@@ -330,7 +330,7 @@ pub struct FiuuPaymentRequest {
txn_amount: StringMajorUnit,
signature: Secret<String>,
#[serde(rename = "ReturnURL")]
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
#[serde(rename = "NotificationURL")]
notification_url: Option<Url>,
#[serde(flatten)]
@@ -921,13 +921,16 @@ impl TryFrom<PaymentsResponseRouterData<FiuuPaymentsResponse>> for PaymentsAutho
FiuuPaymentsResponse::PaymentResponse(data) => match data.txn_data.request_data {
RequestData::RedirectData(redirection_data) => {
let redirection_data = Some(RedirectForm::Form {
- endpoint: data.txn_data.request_url.to_string(),
+ endpoint: data.txn_data.request_url.to_string().into(),
method: if data.txn_data.request_method.as_str() == "POST" {
Method::Post
} else {
Method::Get
},
- form_fields: redirection_data.unwrap_or_default(),
+ form_fields: (redirection_data.unwrap_or_default())
+ .into_iter()
+ .map(|(key, value)| (key, value.into()))
+ .collect(),
});
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
index e72fbeeb8b..44decf0a08 100644
--- a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
@@ -315,7 +315,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResp
);
let redirection_data = Some(RedirectForm::Form {
- endpoint: redirect_url,
+ endpoint: redirect_url.into(),
method: Method::Get,
form_fields: Default::default(),
});
diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
index 395629707b..c3df8898c1 100644
--- a/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
+++ b/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
@@ -39,9 +39,9 @@ pub struct GlobalpayRefreshTokenRequest {
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Notifications {
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
pub status_url: Option<String>,
- pub cancel_url: Option<String>,
+ pub cancel_url: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs
index 4dd7db2d05..204d583258 100644
--- a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs
@@ -576,7 +576,7 @@ pub struct GlobalpayErrorResponse {
pub detailed_error_description: String,
}
-fn get_return_url(item: &PaymentsAuthorizeRouterData) -> Option<String> {
+fn get_return_url(item: &PaymentsAuthorizeRouterData) -> Option<Secret<String>> {
match item.request.payment_method_data.clone() {
payment_method_data::PaymentMethodData::Wallet(
payment_method_data::WalletData::PaypalRedirect(_),
diff --git a/crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs b/crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs
index f0638704e8..748f98220e 100644
--- a/crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs
+++ b/crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs
@@ -134,7 +134,7 @@ pub struct GpaymentsAuthenticationRequest {
pub browser_info_collected: BrowserInfoCollected,
pub card_expiry_date: String,
#[serde(rename = "notificationURL")]
- pub notification_url: String,
+ pub notification_url: Secret<String>,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(rename = "threeDSCompInd")]
pub three_ds_comp_ind: ThreeDsCompletionIndicator,
diff --git a/crates/hyperswitch_connectors/src/connectors/hipay.rs b/crates/hyperswitch_connectors/src/connectors/hipay.rs
index c93cc5685d..0ba6d41b25 100644
--- a/crates/hyperswitch_connectors/src/connectors/hipay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/hipay.rs
@@ -2,7 +2,9 @@ pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
-use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType};
+use common_enums::{
+ enums, CallConnectorAction, CaptureMethod, PaymentAction, PaymentMethod, PaymentMethodType,
+};
use common_utils::{
consts::BASE64_ENGINE,
errors::{self as common_errors, CustomResult},
@@ -24,8 +26,8 @@ use hyperswitch_domain_models::{
RefundsData, SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
- SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback,
+ RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
@@ -34,8 +36,8 @@ use hyperswitch_domain_models::{
};
use hyperswitch_interfaces::{
api::{
- self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
- ConnectorValidation,
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
+ ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
@@ -731,6 +733,21 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Hipay {
}
}
+impl ConnectorRedirectResponse for Hipay {
+ fn get_notification_callback(&self) -> Option<RedirectCallback> {
+ Some(RedirectCallback::Response)
+ }
+
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<Value>,
+ _action: PaymentAction,
+ ) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
+ Ok(CallConnectorAction::Trigger)
+ }
+}
+
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Hipay {
fn get_webhook_object_reference_id(
diff --git a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
index dce9202441..be664fac46 100644
--- a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
@@ -83,11 +83,11 @@ pub struct HipayPaymentsRequest {
payment_product: String,
amount: StringMajorUnit,
description: String,
- decline_url: Option<String>,
- pending_url: Option<String>,
- cancel_url: Option<String>,
- accept_url: Option<String>,
- notify_url: Option<String>,
+ decline_url: Option<Secret<String>>,
+ pending_url: Option<Secret<String>>,
+ cancel_url: Option<Secret<String>>,
+ accept_url: Option<Secret<String>>,
+ notify_url: Option<Secret<String>>,
#[serde(flatten)]
#[serde(skip_serializing_if = "Option::is_none")]
three_ds_data: Option<ThreeDSPaymentData>,
@@ -230,7 +230,7 @@ impl TryFrom<&HipayRouterData<&PaymentsAuthorizeRouterData>> for HipayPaymentsRe
pending_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
accept_url: item.router_data.request.router_return_url.clone(),
- notify_url: item.router_data.request.router_return_url.clone(),
+ notify_url: item.router_data.request.router_notification_url.clone(),
three_ds_data: if item.router_data.is_three_ds() {
let billing_address = item.router_data.get_billing_address()?;
Some(ThreeDSPaymentData {
@@ -393,7 +393,7 @@ impl TryFrom<PaymentsResponseRouterData<HipayPaymentsResponse>> for PaymentsAuth
),
redirection_data: match item.data.is_three_ds() {
true => Box::new(Some(RedirectForm::Form {
- endpoint: item.response.forward_url,
+ endpoint: item.response.forward_url.into(),
method: Method::Get,
form_fields: HashMap::new(),
})),
diff --git a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs
index c31249107f..f1960da94c 100644
--- a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs
@@ -89,8 +89,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, IatapayAuthUpdateResponse, T, AccessTok
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectUrls {
- success_url: String,
- failure_url: String,
+ success_url: Secret<String>,
+ failure_url: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -242,7 +242,7 @@ impl
}
}
-fn get_redirect_url(return_url: String) -> RedirectUrls {
+fn get_redirect_url(return_url: Secret<String>) -> RedirectUrls {
RedirectUrls {
success_url: return_url.clone(),
failure_url: return_url,
@@ -389,7 +389,7 @@ fn get_iatpay_response(
false => (
None,
Some(RedirectForm::Form {
- endpoint: checkout_methods.redirect.redirect_url,
+ endpoint: checkout_methods.redirect.redirect_url.into(),
method: Method::Get,
form_fields,
}),
diff --git a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs
index a9fad65c3a..14061a04c1 100644
--- a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs
@@ -42,7 +42,7 @@ pub struct InespayPaymentsRequest {
amount: StringMinorUnit,
reference: String,
debtor_account: Option<Secret<String>>,
- success_link_redirect: Option<String>,
+ success_link_redirect: Option<Secret<String>>,
notif_url: Option<String>,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs b/crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
index 9dd21a346d..2233da7f7b 100644
--- a/crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
@@ -82,9 +82,9 @@ pub enum PaymentMethodSpecifics {
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct MerchantURLs {
- terms: String,
- checkout: String,
- confirmation: String,
+ terms: Secret<String>,
+ checkout: Secret<String>,
+ confirmation: Secret<String>,
push: String,
}
@@ -127,7 +127,7 @@ pub struct PaymentsResponse {
pub struct CheckoutResponse {
order_id: String,
status: KlarnaCheckoutStatus,
- html_snippet: String,
+ html_snippet: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthorizedPaymentMethod {
diff --git a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs
index 4fd93e439e..99d5bfb8b5 100644
--- a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs
@@ -98,8 +98,8 @@ pub struct LoonioCustomerProfile {
#[derive(Debug, Serialize)]
pub struct LoonioRedirectUrl {
- pub success_url: String,
- pub failed_url: String,
+ pub success_url: Secret<String>,
+ pub failed_url: Secret<String>,
}
impl TryFrom<&LoonioRouterData<&PaymentsAuthorizeRouterData>> for LoonioPaymentRequest {
@@ -163,7 +163,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResp
item.data.connector_request_reference_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
- endpoint: item.response.payment_form,
+ endpoint: item.response.payment_form.into(),
method: Method::Get,
form_fields: HashMap::new(),
})),
diff --git a/crates/hyperswitch_connectors/src/connectors/mifinity.rs b/crates/hyperswitch_connectors/src/connectors/mifinity.rs
index 4419e3e91c..23e7589676 100644
--- a/crates/hyperswitch_connectors/src/connectors/mifinity.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mifinity.rs
@@ -22,8 +22,8 @@ use hyperswitch_domain_models::{
RefundsData, SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
- SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback, RedirectForm,
+ RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
@@ -553,6 +553,21 @@ lazy_static! {
}
+impl api::ConnectorRedirectResponse for Mifinity {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::Mifinity { .. }).then_some(RedirectCallback::Response)
+ }
+
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ _action: enums::PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
+ Ok(enums::CallConnectorAction::Trigger)
+ }
+}
+
impl ConnectorSpecifications for Mifinity {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*MIFINITY_CONNECTOR_INFO)
diff --git a/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
index 0b6e9f6de0..be11195c60 100644
--- a/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
@@ -67,7 +67,7 @@ pub struct MifinityPaymentsRequest {
description: String,
destination_account_number: Secret<String>,
brand_id: Secret<String>,
- return_url: String,
+ return_url: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
language_preference: Option<String>,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
index 45e9d338cc..079f3e9fd5 100644
--- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
@@ -57,7 +57,7 @@ impl<T> From<(StringMajorUnit, T)> for MollieRouterData<T> {
pub struct MolliePaymentsRequest {
amount: Amount,
description: String,
- redirect_url: String,
+ redirect_url: Secret<String>,
cancel_url: Option<String>,
webhook_url: String,
locale: Option<String>,
@@ -756,7 +756,7 @@ pub struct MolliePaymentsResponse {
pub status: MolliePaymentStatus,
pub is_cancelable: Option<bool>,
pub sequence_type: Option<SequenceType>,
- pub redirect_url: Option<String>,
+ pub redirect_url: Option<Secret<String>>,
pub webhook_url: Option<String>,
#[serde(rename = "_links")]
pub links: Links,
diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
index 91b1752993..9b24b2796b 100644
--- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
@@ -111,8 +111,8 @@ pub struct Settings {
pub struct PaymentOptions {
pub notification_url: Option<String>,
pub notification_method: Option<String>,
- pub redirect_url: String,
- pub cancel_url: String,
+ pub redirect_url: Secret<String>,
+ pub cancel_url: Secret<String>,
pub close_window: Option<bool>,
pub settings: Option<Settings>,
pub template_id: Option<String>,
diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
index c4dfada640..3432c4a15b 100644
--- a/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
+++ b/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
@@ -8,7 +8,7 @@ use hyperswitch_domain_models::router_request_types::{
authentication::MessageCategory, BrowserInformation,
};
use hyperswitch_interfaces::errors::ConnectorError;
-use hyperswitch_masking::ExposeInterface;
+use hyperswitch_masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use unidecode::unidecode;
@@ -401,7 +401,7 @@ pub struct CardholderAccount {
/// The field has 4 characters in a format YYMM.
///
/// The requirements of the presence of this field are DS specific.
- pub card_expiry_date: Option<hyperswitch_masking::Secret<String>>,
+ pub card_expiry_date: Option<Secret<String>>,
/// This field contains additional information about the Cardholder’s account provided by the 3DS Requestor.
///
/// The field is optional but recommended to include.
@@ -446,7 +446,7 @@ pub struct CardholderAccount {
///
/// This field is required depending on the rules provided by the Directory Server.
/// Available for supporting EMV 3DS 2.3.1 and later versions.
- pub card_security_code: Option<hyperswitch_masking::Secret<String>>,
+ pub card_security_code: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@@ -628,7 +628,7 @@ pub struct Cardholder {
/// This field is limited to a maximum of 50 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
- bill_addr_line1: Option<hyperswitch_masking::Secret<String>>,
+ bill_addr_line1: Option<Secret<String>>,
/// Second line of the street address or equivalent local portion of the Cardholder billing address associated with
/// the card use for this purchase.
@@ -636,7 +636,7 @@ pub struct Cardholder {
/// This field is limited to a maximum of 50 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
- bill_addr_line2: Option<hyperswitch_masking::Secret<String>>,
+ bill_addr_line2: Option<Secret<String>>,
/// Third line of the street address or equivalent local portion of the Cardholder billing address associated with
/// the card use for this purchase.
@@ -644,14 +644,14 @@ pub struct Cardholder {
/// This field is limited to a maximum of 50 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
- bill_addr_line3: Option<hyperswitch_masking::Secret<String>>,
+ bill_addr_line3: Option<Secret<String>>,
/// ZIP or other postal code of the Cardholder billing address associated with the card used for this purchase.
///
/// This field is limited to a maximum of 16 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
- bill_addr_post_code: Option<hyperswitch_masking::Secret<String>>,
+ bill_addr_post_code: Option<Secret<String>>,
/// The state or province of the Cardholder billing address associated with the card used for this purchase.
///
@@ -659,7 +659,7 @@ pub struct Cardholder {
///
/// This field is required unless State is not applicable for this country and unless market or regional mandate
/// restricts sending this information.
- bill_addr_state: Option<hyperswitch_masking::Secret<String>>,
+ bill_addr_state: Option<Secret<String>>,
/// The email address associated with the account that is either entered by the Cardholder, or is on file with
/// the 3DS Requestor.
@@ -699,7 +699,7 @@ pub struct Cardholder {
///
/// Starting from EMV 3DS 2.3.1:
/// This field is limited to 1-45 characters.
- cardholder_name: Option<hyperswitch_masking::Secret<String>>,
+ cardholder_name: Option<Secret<String>>,
/// City portion of the shipping address requested by the Cardholder.
///
@@ -723,7 +723,7 @@ pub struct Cardholder {
///
/// This field is required unless shipping information is the same as billing information, or market or regional
/// mandate restricts sending this information.
- ship_addr_line1: Option<hyperswitch_masking::Secret<String>>,
+ ship_addr_line1: Option<Secret<String>>,
/// Second line of the street address or equivalent local portion of the shipping address associated with
/// the card use for this purchase.
@@ -732,7 +732,7 @@ pub struct Cardholder {
///
/// This field is required unless shipping information is the same as billing information, or market or regional
/// mandate restricts sending this information.
- ship_addr_line2: Option<hyperswitch_masking::Secret<String>>,
+ ship_addr_line2: Option<Secret<String>>,
/// Third line of the street address or equivalent local portion of the shipping address associated with
/// the card use for this purchase.
@@ -741,7 +741,7 @@ pub struct Cardholder {
///
/// This field is required unless shipping information is the same as billing information, or market or regional
/// mandate restricts sending this information.
- ship_addr_line3: Option<hyperswitch_masking::Secret<String>>,
+ ship_addr_line3: Option<Secret<String>>,
/// ZIP or other postal code of the shipping address associated with the card used for this purchase.
///
@@ -749,7 +749,7 @@ pub struct Cardholder {
///
/// This field is required unless shipping information is the same as billing information, or market or regional
/// mandate restricts sending this information.
- ship_addr_post_code: Option<hyperswitch_masking::Secret<String>>,
+ ship_addr_post_code: Option<Secret<String>>,
/// The state or province of the shipping address associated with the card used for this purchase.
///
@@ -757,7 +757,7 @@ pub struct Cardholder {
///
/// This field is required unless shipping information is the same as billing information, or State is not applicable
/// for this country, or market or regional mandate restricts sending this information.
- ship_addr_state: Option<hyperswitch_masking::Secret<String>>,
+ ship_addr_state: Option<Secret<String>>,
/// Tax ID is the Cardholder's tax identification.
///
@@ -834,7 +834,7 @@ impl
cardholder_name: billing_address.address.and_then(|address| {
address
.get_optional_full_name()
- .map(|name| hyperswitch_masking::Secret::new(unidecode(&name.expose())))
+ .map(|name| Secret::new(unidecode(&name.expose())))
}),
ship_addr_city: shipping_address
.as_ref()
@@ -882,7 +882,7 @@ pub struct PhoneNumber {
/// Country Code of the phone, limited to 1-3 characters
#[serde(rename = "cc")]
country_code: Option<String>,
- subscriber: Option<hyperswitch_masking::Secret<String>>,
+ subscriber: Option<Secret<String>>,
}
impl TryFrom<hyperswitch_domain_models::address::PhoneDetails> for PhoneNumber {
@@ -1084,7 +1084,7 @@ pub struct MerchantRiskIndicator {
delivery_timeframe: Option<String>,
/// For electronic delivery, the email address to which the merchandise was delivered.
- delivery_email_address: Option<hyperswitch_masking::Secret<String, EmailStrategy>>,
+ delivery_email_address: Option<Secret<String, EmailStrategy>>,
/// Indicates whether the cardholder is reordering previously purchased merchandise.
///
@@ -1210,7 +1210,7 @@ pub struct MerchantData {
/// If not present in the request it will be filled from the notificationURL configured in the XML or database configuration.
#[serde(rename = "notificationURL")]
#[serde(skip_serializing_if = "Option::is_none")]
- pub notification_url: Option<String>,
+ pub notification_url: Option<Secret<String>>,
/// Each DS provides rules for the 3DS Requestor ID. The 3DS Requestor is responsible for providing the 3DS Requestor ID according to the DS rules.
///
@@ -1327,7 +1327,7 @@ pub struct SellerInfo {
/// Business or contact email address of the Seller. The value length is maximum 254 characters. Accepted values
/// shall meet requirements of Section 3.4 of IETF RFC 5322. This field is optional.
- seller_email: Option<hyperswitch_masking::Secret<String, EmailStrategy>>,
+ seller_email: Option<Secret<String, EmailStrategy>>,
/// Business or contact phone number of the Seller. Country Code and Subscriber sections of the number represented
/// by the following named fields:
@@ -1356,7 +1356,7 @@ pub struct Browser {
///
/// This field is required for requests when deviceChannel = 02 (BRW) where regionally acceptable.
#[serde(rename = "browserIP")]
- browser_ip: Option<hyperswitch_masking::Secret<String, common_utils::pii::IpAddress>>,
+ browser_ip: Option<Secret<String, common_utils::pii::IpAddress>>,
/// Boolean that represents the ability of the cardholder browser to execute Java. Value is returned from the
/// navigator.javaEnabled property.
@@ -1479,9 +1479,7 @@ impl From<BrowserInformation> for Browser {
fn from(value: BrowserInformation) -> Self {
Self {
browser_accept_header: value.accept_header,
- browser_ip: value
- .ip_address
- .map(|ip| hyperswitch_masking::Secret::new(ip.to_string())),
+ browser_ip: value.ip_address.map(|ip| Secret::new(ip.to_string())),
browser_java_enabled: value.java_enabled,
browser_language: value.language,
browser_color_depth: value.color_depth.map(|cd| cd.to_string()),
diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
index 436d0bfbee..73dec0616b 100644
--- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
@@ -127,9 +127,9 @@ pub struct NexinetsBankRedirects {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsAsyncDetails {
- pub success_url: Option<String>,
- pub cancel_url: Option<String>,
- pub failure_url: Option<String>,
+ pub success_url: Option<Secret<String>>,
+ pub cancel_url: Option<Secret<String>>,
+ pub failure_url: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
index e9e0f0e44c..73fb2c0a31 100644
--- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
@@ -509,7 +509,7 @@ pub enum NexixpayPaymentIntent {
pub struct NexixpayRedirectionRequest {
pub three_d_s_auth_url: String,
pub three_ds_request: String,
- pub return_url: String,
+ pub return_url: Secret<String>,
pub transaction_id: String,
}
@@ -1539,13 +1539,16 @@ impl TryFrom<PaymentsPreAuthenticateResponseRouterData<NexixpayPaymentsResponse>
fn nexixpay_threeds_link(
request: NexixpayRedirectionRequest,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
- let mut form_fields = HashMap::<String, String>::new();
- form_fields.insert(String::from("ThreeDsRequest"), request.three_ds_request);
+ let mut form_fields = HashMap::<String, Secret<String>>::new();
+ form_fields.insert(
+ String::from("ThreeDsRequest"),
+ request.three_ds_request.into(),
+ );
form_fields.insert(String::from("ReturnUrl"), request.return_url);
- form_fields.insert(String::from("transactionId"), request.transaction_id);
+ form_fields.insert(String::from("transactionId"), request.transaction_id.into());
Ok(RedirectForm::Form {
- endpoint: request.three_d_s_auth_url,
+ endpoint: request.three_d_s_auth_url.into(),
method: Method::Post,
form_fields,
})
diff --git a/crates/hyperswitch_connectors/src/connectors/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rs
index f080732c06..6ab9a3c3ac 100644
--- a/crates/hyperswitch_connectors/src/connectors/nmi.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs
@@ -24,8 +24,8 @@ use hyperswitch_domain_models::{
SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
- SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback, RedirectForm,
+ RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
@@ -1001,6 +1001,10 @@ impl IncomingWebhook for Nmi {
}
impl ConnectorRedirectResponse for Nmi {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::Nmi { .. }).then_some(RedirectCallback::Complete)
+ }
+
fn get_flow_type(
&self,
_query_params: &str,
diff --git a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
index 737972cc93..39a01ca3fd 100644
--- a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
@@ -194,7 +194,7 @@ pub enum NoonPaymentActions {
pub struct NoonConfiguration {
tokenize_c_c: Option<bool>,
payment_action: NoonPaymentActions,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
@@ -269,7 +269,7 @@ pub struct NoonGooglePay {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPayPal {
- return_url: String,
+ return_url: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -639,7 +639,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsRespon
.result
.checkout_data
.map(|redirection_data| RedirectForm::Form {
- endpoint: redirection_data.post_url.to_string(),
+ endpoint: redirection_data.post_url.to_string().into(),
method: Method::Post,
form_fields: std::collections::HashMap::new(),
});
diff --git a/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs
index a8d81275cd..31528577b7 100644
--- a/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs
@@ -496,7 +496,7 @@ impl
})
.and_then(|link| link.href.clone())
.map(|redirect_url| RedirectForm::Form {
- endpoint: redirect_url,
+ endpoint: redirect_url.into(),
method: Method::Get,
form_fields: HashMap::new(),
});
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
index 4653c1492d..d2b33e8c17 100644
--- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
@@ -183,8 +183,8 @@ pub struct NovalnetPaymentsRequestTransaction {
order_no: String,
payment_data: Option<NovalNetPaymentData>,
hook_url: Option<String>,
- return_url: Option<String>,
- error_return_url: Option<String>,
+ return_url: Option<Secret<String>>,
+ error_return_url: Option<Secret<String>>,
enforce_3d: Option<i8>, //NOTE: Needed for CREDITCARD, GOOGLEPAY
create_token: Option<i8>,
}
@@ -769,7 +769,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsRe
.result
.redirect_url
.map(|url| RedirectForm::Form {
- endpoint: url.expose().to_string(),
+ endpoint: url.expose().to_string().into(),
method: Method::Get,
form_fields: HashMap::new(),
});
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
index 7f0904d804..c4bd443042 100644
--- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
@@ -132,7 +132,7 @@ impl TryFrom<(&types::PaymentsPreAuthenticateRouterData, String)>
.ok_or_else(missing_field_err("browser_info"))?;
let return_url = match env::which() {
- Env::Development => "https://example.com".to_string(),
+ Env::Development => "https://example.com".to_string().into(),
_ => item
.request
.router_return_url
@@ -495,9 +495,9 @@ pub struct ThreeD {
pub method_completion_ind: Option<MethodCompletion>,
pub browser_details: Option<BrowserDetails>,
#[serde(rename = "notificationURL")]
- pub notification_url: Option<String>,
+ pub notification_url: Option<Secret<String>>,
#[serde(rename = "merchantURL")]
- pub merchant_url: Option<String>,
+ pub merchant_url: Option<Secret<String>>,
pub acs_url: Option<String>,
pub c_req: Option<Secret<String>>,
pub external_mpi: Option<ExternalMpi>,
@@ -1139,7 +1139,7 @@ where
let base = NuveiPaymentBaseRequest::try_from((item, session_token))?;
let return_url = match env::which() {
- Env::Development => "https://example.com".to_string(),
+ Env::Development => "https://example.com".to_string().into(),
_ => item.request.get_return_url_required()?,
};
@@ -1732,7 +1732,7 @@ pub struct NuveiPayoutMethodData {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NuveiPayoutUrlDetails {
- pub notification_url: String,
+ pub notification_url: Secret<String>,
}
#[cfg(feature = "payouts")]
@@ -1863,7 +1863,7 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for NuveiPayoutRequest {
let customer_details = item.request.get_customer_details()?;
let url_details = NuveiPayoutUrlDetails {
- notification_url: item.request.get_webhook_url()?,
+ notification_url: item.request.get_webhook_url()?.into(),
};
Ok(Self {
@@ -2422,9 +2422,9 @@ fn process_nuvei_payment_response(
.and_then(|card| card.three_d)
.and_then(|three_ds| three_ds.acs_url.zip(three_ds.c_req))
.map(|(base_url, creq)| RedirectForm::Form {
- endpoint: base_url,
+ endpoint: base_url.into(),
method: Method::Post,
- form_fields: std::collections::HashMap::from([("creq".to_string(), creq.expose())]),
+ form_fields: std::collections::HashMap::from([("creq".to_string(), creq)]),
}),
};
@@ -3958,7 +3958,7 @@ impl From<primitive_wrappers::EnablePartialAuthorizationBool> for PartialApprova
trait NuveiAuthorizePreprocessingCommon {
fn get_browser_info(&self) -> Option<BrowserInformation>;
- fn get_complete_authorize_url(&self) -> Option<String>;
+ fn get_complete_authorize_url(&self) -> Option<Secret<String>>;
fn get_related_transaction_id(&self) -> Option<String> {
None
}
@@ -3987,7 +3987,7 @@ trait NuveiAuthorizePreprocessingCommon {
}
fn get_return_url_required(
&self,
- ) -> Result<String, error_stack::Report<errors::ConnectorError>>;
+ ) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>>;
fn get_capture_method(&self) -> Option<CaptureMethod>;
fn get_minor_amount_required(&self) -> MinorUnit;
fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>>;
@@ -4035,7 +4035,7 @@ impl NuveiAuthorizePreprocessingCommon for CompleteAuthorizeData {
}
fn get_return_url_required(
&self,
- ) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ ) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>> {
self.get_router_return_url()
}
@@ -4067,7 +4067,7 @@ impl NuveiAuthorizePreprocessingCommon for CompleteAuthorizeData {
self.browser_info.clone()
}
- fn get_complete_authorize_url(&self) -> Option<String> {
+ fn get_complete_authorize_url(&self) -> Option<Secret<String>> {
self.complete_authorize_url.clone()
}
@@ -4092,7 +4092,7 @@ impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData {
_ => None,
}
}
- fn get_complete_authorize_url(&self) -> Option<String> {
+ fn get_complete_authorize_url(&self) -> Option<Secret<String>> {
self.complete_authorize_url.clone()
}
@@ -4111,7 +4111,7 @@ impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData {
fn get_return_url_required(
&self,
- ) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ ) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>> {
self.get_router_return_url()
}
@@ -4181,7 +4181,7 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData {
fn get_return_url_required(
&self,
- ) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ ) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>> {
self.get_router_return_url()
}
@@ -4189,7 +4189,7 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData {
self.capture_method
}
- fn get_complete_authorize_url(&self) -> Option<String> {
+ fn get_complete_authorize_url(&self) -> Option<Secret<String>> {
self.complete_authorize_url.clone()
}
@@ -4304,9 +4304,9 @@ pub struct NuveiAmountDetails {
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UrlDetails {
- pub success_url: String,
- pub failure_url: String,
- pub pending_url: String,
+ pub success_url: Secret<String>,
+ pub failure_url: Secret<String>,
+ pub pending_url: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
diff --git a/crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
index b32cf00064..c6580f9381 100644
--- a/crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
@@ -42,7 +42,7 @@ pub struct OpennodePaymentsRequest {
currency: String,
description: String,
auto_settle: bool,
- success_url: String,
+ success_url: Secret<String>,
callback_url: String,
order_id: String,
}
@@ -124,7 +124,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsRe
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
let redirection_data = RedirectForm::Form {
- endpoint: item.response.data.hosted_checkout_url.to_string(),
+ endpoint: item.response.data.hosted_checkout_url.to_string().into(),
method: Method::Get,
form_fields,
};
@@ -269,7 +269,7 @@ fn get_crypto_specific_payment_data(
pub struct OpennodeWebhookDetails {
pub id: String,
pub callback_url: String,
- pub success_url: String,
+ pub success_url: Secret<String>,
pub status: OpennodePaymentStatus,
pub payment_method: String,
pub missing_amt: String,
diff --git a/crates/hyperswitch_connectors/src/connectors/paybox.rs b/crates/hyperswitch_connectors/src/connectors/paybox.rs
index 9fb6cb7073..9479a4f5b5 100644
--- a/crates/hyperswitch_connectors/src/connectors/paybox.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paybox.rs
@@ -24,8 +24,8 @@ use hyperswitch_domain_models::{
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
- SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback,
+ RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
@@ -680,6 +680,10 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp
}
}
impl ConnectorRedirectResponse for Paybox {
+ fn get_notification_callback(&self) -> Option<RedirectCallback> {
+ Some(RedirectCallback::Complete)
+ }
+
fn get_flow_type(
&self,
_query_params: &str,
diff --git a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
index 32f4fc3f60..76dc177de4 100644
--- a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
@@ -132,9 +132,9 @@ pub struct ThreeDSPaymentsRequest {
#[serde(rename = "CVVCode")]
cvv_code: Secret<String>,
#[serde(rename = "URLRetour")]
- url_retour: String,
+ url_retour: Secret<String>,
#[serde(rename = "URLHttpDirect")]
- url_http_direct: String,
+ url_http_direct: Secret<String>,
email_porteur: common_utils::pii::Email,
first_name: Secret<String>,
last_name: Secret<String>,
@@ -399,6 +399,12 @@ impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxP
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if item.router_data.is_three_ds() {
let address = item.router_data.get_billing_address()?;
+ let notification_url = item
+ .router_data
+ .request
+ .router_notification_url
+ .clone()
+ .ok_or_else(utils::missing_field_err("router_notification_url"))?;
Ok(Self::CardThreeDs(ThreeDSPaymentsRequest {
id_merchant: auth_data.merchant_id,
id_session: item.router_data.connector_request_reference_id.clone(),
@@ -408,7 +414,7 @@ impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxP
cc_exp_date: expiration_date,
cvv_code: req_card.card_cvc,
url_retour: item.router_data.request.get_complete_authorize_url()?,
- url_http_direct: item.router_data.request.get_complete_authorize_url()?,
+ url_http_direct: notification_url,
email_porteur: item.router_data.request.get_email()?,
first_name: address.get_first_name()?.clone(),
last_name: address.get_last_name()?.clone(),
@@ -759,9 +765,7 @@ impl<F> TryFrom<ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, Pay
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
- redirection_data: Box::new(Some(RedirectForm::Html {
- html_data: data.peek().to_string(),
- })),
+ redirection_data: Box::new(Some(RedirectForm::Html { html_data: data })),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/payjustnow/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payjustnow/transformers.rs
index 79f9f56527..d8c81905f6 100644
--- a/crates/hyperswitch_connectors/src/connectors/payjustnow/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payjustnow/transformers.rs
@@ -59,8 +59,8 @@ pub struct PayjustnowRequest {
billing_address: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
shipping_address: Option<Address>,
- confirm_redirect_url: String,
- cancel_redirect_url: String,
+ confirm_redirect_url: Secret<String>,
+ cancel_redirect_url: Secret<String>,
}
#[derive(Debug, Serialize)]
diff --git a/crates/hyperswitch_connectors/src/connectors/payme.rs b/crates/hyperswitch_connectors/src/connectors/payme.rs
index fea682dfec..e234048868 100644
--- a/crates/hyperswitch_connectors/src/connectors/payme.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payme.rs
@@ -30,8 +30,8 @@ use hyperswitch_domain_models::{
SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
- SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback, RedirectForm,
+ RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
CreateOrderRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
@@ -412,6 +412,10 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons
}
impl ConnectorRedirectResponse for Payme {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::Payme).then_some(RedirectCallback::Complete)
+ }
+
fn get_flow_type(
&self,
_query_params: &str,
diff --git a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
index fbbc3d66a5..96a8fb9227 100644
--- a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
@@ -72,7 +72,7 @@ pub struct MandateRequest {
sale_price: MinorUnit,
transaction_id: String,
product_name: String,
- sale_return_url: String,
+ sale_return_url: Secret<String>,
seller_payme_id: Secret<String>,
sale_callback_url: String,
buyer_key: Secret<String>,
@@ -133,7 +133,7 @@ pub struct GenerateSaleRequest {
sale_price: MinorUnit,
transaction_id: String,
product_name: String,
- sale_return_url: String,
+ sale_return_url: Secret<String>,
seller_payme_id: Secret<String>,
sale_callback_url: String,
sale_payment_method: SalePaymentMethod,
@@ -246,9 +246,12 @@ impl TryFrom<&PaymePaySaleResponse> for PaymentsResponseData {
fn try_from(value: &PaymePaySaleResponse) -> Result<Self, Self::Error> {
let redirection_data = match value.sale_3ds {
Some(true) => value.redirect_url.clone().map(|url| RedirectForm::Form {
- endpoint: url.to_string(),
+ endpoint: url.to_string().into(),
method: common_utils::request::Method::Get,
- form_fields: HashMap::<String, String>::new(),
+ form_fields: (HashMap::<String, String>::new())
+ .into_iter()
+ .map(|(key, value)| (key, value.into()))
+ .collect(),
}),
_ => None,
};
diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
index b322f56296..383855cfd5 100644
--- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
@@ -579,8 +579,8 @@ pub struct RedirectRequest {
#[derive(Debug, Serialize, Deserialize)]
pub struct ContextStruct {
- return_url: Option<String>,
- cancel_url: Option<String>,
+ return_url: Option<Secret<String>>,
+ cancel_url: Option<Secret<String>>,
user_action: Option<UserAction>,
shipping_preference: ShippingPreference,
}
@@ -3139,7 +3139,7 @@ impl TryFrom<PaymentsResponseRouterData<PaypalThreeDsResponse>> for PaymentsAuth
}
fn paypal_threeds_link(
- (redirect_url, complete_auth_url): (Option<Url>, Option<String>),
+ (redirect_url, complete_auth_url): (Option<Url>, Option<Secret<String>>),
) -> CustomResult<RedirectForm, errors::ConnectorError> {
let mut redirect_url =
redirect_url.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -3150,7 +3150,7 @@ fn paypal_threeds_link(
let mut form_fields = std::collections::HashMap::from_iter(
redirect_url
.query_pairs()
- .map(|(key, value)| (key.to_string(), value.to_string())),
+ .map(|(key, value)| (key.to_string(), value.to_string().into())),
);
// paypal requires return url to be passed as a field along with payer_action_url
@@ -3160,7 +3160,7 @@ fn paypal_threeds_link(
redirect_url.set_query(None);
Ok(RedirectForm::Form {
- endpoint: redirect_url.to_string(),
+ endpoint: redirect_url.to_string().into(),
method: Method::Get,
form_fields,
})
diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
index ec380a1ced..6df62386a6 100644
--- a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
@@ -144,7 +144,7 @@ pub struct PaysafeCustomerDetails {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDs {
- pub merchant_url: String,
+ pub merchant_url: Secret<String>,
pub device_channel: DeviceChannel,
pub message_category: ThreeDsMessageCategory,
pub authentication_purpose: ThreeDsAuthenticationPurpose,
@@ -382,7 +382,7 @@ pub struct PaysafeGiftCard {
#[derive(Debug, Serialize)]
pub struct ReturnLink {
pub rel: LinkType,
- pub href: String,
+ pub href: Secret<String>,
pub method: String,
}
@@ -738,7 +738,7 @@ pub struct PaysafePaymentHandleResponse {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentLink {
pub rel: String,
- pub href: String,
+ pub href: Secret<String>,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
index 393d39f600..380a657028 100644
--- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
@@ -9,7 +9,7 @@ use hyperswitch_domain_models::{
types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{consts, errors};
-use hyperswitch_masking::{ExposeInterface, Secret};
+use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
@@ -54,7 +54,7 @@ pub struct PowertranzPaymentsRequest {
#[serde(rename_all = "PascalCase")]
pub struct ExtendedData {
three_d_secure: ThreeDSecure,
- merchant_response_url: String,
+ merchant_response_url: Secret<String>,
browser_info: BrowserInfo,
}
@@ -347,7 +347,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResp
.unwrap_or(item.response.transaction_identifier.clone());
let redirection_data = item.response.redirect_data.map(|redirect_data| {
hyperswitch_domain_models::router_response_types::RedirectForm::Html {
- html_data: redirect_data.expose(),
+ html_data: redirect_data,
}
});
let response = error_response.map_or(
diff --git a/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
index 5911729cf0..c74f2d6161 100644
--- a/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
@@ -216,9 +216,9 @@ impl TryFrom<PaymentsResponseRouterData<ProphetpayTokenResponse>>
fn get_redirect_url_form(
mut redirect_url: Url,
- complete_auth_url: Option<String>,
+ complete_auth_url: Option<Secret<String>>,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
- let mut form_fields = HashMap::<String, String>::new();
+ let mut form_fields = HashMap::<String, Secret<String>>::new();
form_fields.insert(
String::from("redirectUrl"),
@@ -231,7 +231,7 @@ fn get_redirect_url_form(
redirect_url.set_query(None);
Ok(RedirectForm::Form {
- endpoint: redirect_url.to_string(),
+ endpoint: redirect_url.to_string().into(),
method: Method::Get,
form_fields,
})
diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs b/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
index 568d7ae5cb..0944c646cc 100644
--- a/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
@@ -48,8 +48,8 @@ pub struct RapydPaymentsRequest {
pub merchant_reference_id: Option<String>,
pub capture: Option<bool>,
pub description: Option<String>,
- pub complete_payment_url: Option<String>,
- pub error_payment_url: Option<String>,
+ pub complete_payment_url: Option<Secret<String>>,
+ pub error_payment_url: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize)]
diff --git a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
index f9dea159de..2a6ee8becd 100644
--- a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
@@ -117,7 +117,7 @@ pub struct EmvThreedsData {
#[serde(skip_serializing_if = "Option::is_none")]
cres: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
- notification_u_r_l: Option<String>,
+ notification_u_r_l: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
protocol_version: Option<String>,
#[serde(flatten, skip_serializing_if = "Option::is_none")]
@@ -218,7 +218,7 @@ impl EmvThreedsData {
self
}
- pub fn set_notification_u_r_l(mut self, notification_u_r_l: String) -> Self {
+ pub fn set_notification_u_r_l(mut self, notification_u_r_l: Secret<String>) -> Self {
self.notification_u_r_l = Some(notification_u_r_l);
self
}
@@ -1264,9 +1264,12 @@ fn build_threeds_form(ds_emv3ds: &RedsysEmv3DSData) -> Result<RedirectForm, Erro
form_fields.insert("creq".to_string(), creq);
Ok(RedirectForm::Form {
- endpoint,
+ endpoint: endpoint.into(),
method: common_utils::request::Method::Post,
- form_fields,
+ form_fields: (form_fields)
+ .into_iter()
+ .map(|(key, value)| (key, value.into()))
+ .collect(),
})
}
diff --git a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
index 106fb2d157..da0dbed6e0 100644
--- a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
@@ -39,9 +39,9 @@ type Error = error_stack::Report<errors::ConnectorError>;
trait Shift4AuthorizePreprocessingCommon {
fn is_automatic_capture(&self) -> Result<bool, Error>;
- fn get_router_return_url(&self) -> Option<String>;
+ fn get_router_return_url(&self) -> Option<Secret<String>>;
fn get_email_optional(&self) -> Option<pii::Email>;
- fn get_complete_authorize_url(&self) -> Option<String>;
+ fn get_complete_authorize_url(&self) -> Option<Secret<String>>;
fn get_currency_required(&self) -> Result<enums::Currency, Error>;
fn get_metadata(&self) -> Result<Option<serde_json::Value>, Error>;
fn get_payment_method_data_required(&self) -> Result<PaymentMethodData, Error>;
@@ -67,7 +67,7 @@ impl Shift4AuthorizePreprocessingCommon for PaymentsAuthorizeData {
self.email.clone()
}
- fn get_complete_authorize_url(&self) -> Option<String> {
+ fn get_complete_authorize_url(&self) -> Option<Secret<String>> {
self.complete_authorize_url.clone()
}
@@ -86,7 +86,7 @@ impl Shift4AuthorizePreprocessingCommon for PaymentsAuthorizeData {
self.is_auto_capture()
}
- fn get_router_return_url(&self) -> Option<String> {
+ fn get_router_return_url(&self) -> Option<Secret<String>> {
self.router_return_url.clone()
}
@@ -102,7 +102,7 @@ impl Shift4AuthorizePreprocessingCommon for PaymentsPreAuthenticateData {
self.email.clone()
}
- fn get_complete_authorize_url(&self) -> Option<String> {
+ fn get_complete_authorize_url(&self) -> Option<Secret<String>> {
self.complete_authorize_url.clone()
}
@@ -126,7 +126,7 @@ impl Shift4AuthorizePreprocessingCommon for PaymentsPreAuthenticateData {
self.is_auto_capture()
}
- fn get_router_return_url(&self) -> Option<String> {
+ fn get_router_return_url(&self) -> Option<Secret<String>> {
self.router_return_url.clone()
}
@@ -203,7 +203,7 @@ pub struct Cards3DSRequest {
pub card_exp_month: Secret<String>,
#[serde(rename = "card[expYear]")]
pub card_exp_year: Secret<String>,
- return_url: String,
+ return_url: Secret<String>,
}
#[serde_with::skip_serializing_none]
@@ -217,7 +217,7 @@ pub struct CardsNon3DSRequest {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Flow {
- pub return_url: String,
+ pub return_url: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -755,9 +755,9 @@ impl TryFrom<&BankRedirectData> for PaymentMethodType {
}
}
-impl TryFrom<Option<String>> for Flow {
+impl TryFrom<Option<Secret<String>>> for Flow {
type Error = Error;
- fn try_from(router_return_url: Option<String>) -> Result<Self, Self::Error> {
+ fn try_from(router_return_url: Option<Secret<String>>) -> Result<Self, Self::Error> {
Ok(Self {
return_url: router_return_url.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
})
diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
index 577d2b90e6..533269a56d 100644
--- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
@@ -261,7 +261,7 @@ pub struct PaymentIntentRequest {
pub statement_descriptor: Option<String>,
#[serde(flatten)]
pub meta_data: HashMap<String, String>,
- pub return_url: String,
+ pub return_url: Secret<String>,
pub confirm: bool,
pub payment_method: Option<Secret<String>>,
pub customer: Option<Secret<String>>,
@@ -330,7 +330,7 @@ pub struct SetupIntentRequest {
pub usage: Option<enums::FutureUsage>,
pub customer: Option<Secret<String>>,
pub off_session: Option<bool>,
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
#[serde(flatten)]
pub payment_data: StripePaymentMethodData,
pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated
@@ -2831,7 +2831,7 @@ impl TryFrom<(&PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentRequest
.request
.router_return_url
.clone()
- .unwrap_or_else(|| "https://juspay.in/".to_string()),
+ .unwrap_or_else(|| "https://juspay.in/".to_string().into()),
confirm: true, // Stripe requires confirm to be true if return URL is present
description: item.description.clone(),
shipping: shipping_address,
@@ -4341,7 +4341,7 @@ impl Serialize for StripeNextActionResponse {
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeRedirectToUrlResponse {
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
url: Url,
}
@@ -5805,164 +5805,4 @@ where
}
#[cfg(test)]
-mod test_validate_shipping_address_against_payment_method {
- use std::borrow::Cow;
-
- use common_enums::CountryAlpha2;
- use hyperswitch_interfaces::errors::ConnectorError;
- use hyperswitch_masking::Secret;
-
- use crate::connectors::stripe::transformers::{
- validate_shipping_address_against_payment_method, StripePaymentMethodType,
- StripeShippingAddress,
- };
-
- #[test]
- fn should_return_ok() {
- // Arrange
- let stripe_shipping_address = create_stripe_shipping_address(
- "name".to_string(),
- Some("line1".to_string()),
- Some(CountryAlpha2::AD),
- Some("zip".to_string()),
- );
-
- let payment_method = &StripePaymentMethodType::AfterpayClearpay;
-
- //Act
- let result = validate_shipping_address_against_payment_method(
- &Some(stripe_shipping_address),
- Some(payment_method),
- );
-
- // Assert
- assert!(result.is_ok());
- }
-
- #[test]
- fn should_return_err_for_empty_line1() {
- // Arrange
- let stripe_shipping_address = create_stripe_shipping_address(
- "name".to_string(),
- None,
- Some(CountryAlpha2::AD),
- Some("zip".to_string()),
- );
-
- let payment_method = &StripePaymentMethodType::AfterpayClearpay;
-
- //Act
- let result = validate_shipping_address_against_payment_method(
- &Some(stripe_shipping_address),
- Some(payment_method),
- );
-
- // Assert
- assert!(result.is_err());
- let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
- assert_eq!(missing_fields.len(), 1);
- assert_eq!(*missing_fields.first().unwrap(), "shipping.address.line1");
- }
-
- #[test]
- fn should_return_err_for_empty_country() {
- // Arrange
- let stripe_shipping_address = create_stripe_shipping_address(
- "name".to_string(),
- Some("line1".to_string()),
- None,
- Some("zip".to_string()),
- );
-
- let payment_method = &StripePaymentMethodType::AfterpayClearpay;
-
- //Act
- let result = validate_shipping_address_against_payment_method(
- &Some(stripe_shipping_address),
- Some(payment_method),
- );
-
- // Assert
- assert!(result.is_err());
- let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
- assert_eq!(missing_fields.len(), 1);
- assert_eq!(*missing_fields.first().unwrap(), "shipping.address.country");
- }
-
- #[test]
- fn should_return_err_for_empty_zip() {
- // Arrange
- let stripe_shipping_address = create_stripe_shipping_address(
- "name".to_string(),
- Some("line1".to_string()),
- Some(CountryAlpha2::AD),
- None,
- );
- let payment_method = &StripePaymentMethodType::AfterpayClearpay;
-
- //Act
- let result = validate_shipping_address_against_payment_method(
- &Some(stripe_shipping_address),
- Some(payment_method),
- );
-
- // Assert
- assert!(result.is_err());
- let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
- assert_eq!(missing_fields.len(), 1);
- assert_eq!(*missing_fields.first().unwrap(), "shipping.address.zip");
- }
-
- #[test]
- fn should_return_error_when_missing_multiple_fields() {
- // Arrange
- let expected_missing_field_names: Vec<&str> =
- vec!["shipping.address.zip", "shipping.address.country"];
- let stripe_shipping_address = create_stripe_shipping_address(
- "name".to_string(),
- Some("line1".to_string()),
- None,
- None,
- );
- let payment_method = &StripePaymentMethodType::AfterpayClearpay;
-
- //Act
- let result = validate_shipping_address_against_payment_method(
- &Some(stripe_shipping_address),
- Some(payment_method),
- );
-
- // Assert
- assert!(result.is_err());
- let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
- for field in missing_fields {
- assert!(expected_missing_field_names.contains(&field.as_ref()));
- }
- }
-
- fn get_missing_fields(connector_error: &ConnectorError) -> Vec<Cow<'static, str>> {
- if let ConnectorError::MissingRequiredFields { field_names } = connector_error {
- return field_names.to_vec();
- }
-
- vec![]
- }
-
- fn create_stripe_shipping_address(
- name: String,
- line1: Option<String>,
- country: Option<CountryAlpha2>,
- zip: Option<String>,
- ) -> StripeShippingAddress {
- StripeShippingAddress {
- name: Some(Secret::new(name)),
- line1: line1.map(Secret::new),
- country,
- zip: zip.map(Secret::new),
- city: Some(String::from("city")),
- line2: Some(Secret::new(String::from("line2"))),
- state: Some(Secret::new(String::from("state"))),
- phone: Some(Secret::new(String::from("pbone number"))),
- }
- }
-}
+mod tests;
diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers/tests.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers/tests.rs
new file mode 100644
index 0000000000..eb4ca57982
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers/tests.rs
@@ -0,0 +1,155 @@
+use std::borrow::Cow;
+
+use common_enums::CountryAlpha2;
+use hyperswitch_interfaces::errors::ConnectorError;
+use hyperswitch_masking::Secret;
+
+use crate::connectors::stripe::transformers::{
+ validate_shipping_address_against_payment_method, StripePaymentMethodType,
+ StripeShippingAddress,
+};
+
+#[test]
+fn should_return_ok() {
+ // Arrange
+ let stripe_shipping_address = create_stripe_shipping_address(
+ "name".to_string(),
+ Some("line1".to_string()),
+ Some(CountryAlpha2::AD),
+ Some("zip".to_string()),
+ );
+
+ let payment_method = &StripePaymentMethodType::AfterpayClearpay;
+
+ //Act
+ let result = validate_shipping_address_against_payment_method(
+ &Some(stripe_shipping_address),
+ Some(payment_method),
+ );
+
+ // Assert
+ assert!(result.is_ok());
+}
+
+#[test]
+fn should_return_err_for_empty_line1() {
+ // Arrange
+ let stripe_shipping_address = create_stripe_shipping_address(
+ "name".to_string(),
+ None,
+ Some(CountryAlpha2::AD),
+ Some("zip".to_string()),
+ );
+
+ let payment_method = &StripePaymentMethodType::AfterpayClearpay;
+
+ //Act
+ let result = validate_shipping_address_against_payment_method(
+ &Some(stripe_shipping_address),
+ Some(payment_method),
+ );
+
+ // Assert
+ assert!(result.is_err());
+ let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
+ assert_eq!(missing_fields.len(), 1);
+ assert_eq!(*missing_fields.first().unwrap(), "shipping.address.line1");
+}
+
+#[test]
+fn should_return_err_for_empty_country() {
+ // Arrange
+ let stripe_shipping_address = create_stripe_shipping_address(
+ "name".to_string(),
+ Some("line1".to_string()),
+ None,
+ Some("zip".to_string()),
+ );
+
+ let payment_method = &StripePaymentMethodType::AfterpayClearpay;
+
+ //Act
+ let result = validate_shipping_address_against_payment_method(
+ &Some(stripe_shipping_address),
+ Some(payment_method),
+ );
+
+ // Assert
+ assert!(result.is_err());
+ let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
+ assert_eq!(missing_fields.len(), 1);
+ assert_eq!(*missing_fields.first().unwrap(), "shipping.address.country");
+}
+
+#[test]
+fn should_return_err_for_empty_zip() {
+ // Arrange
+ let stripe_shipping_address = create_stripe_shipping_address(
+ "name".to_string(),
+ Some("line1".to_string()),
+ Some(CountryAlpha2::AD),
+ None,
+ );
+ let payment_method = &StripePaymentMethodType::AfterpayClearpay;
+
+ //Act
+ let result = validate_shipping_address_against_payment_method(
+ &Some(stripe_shipping_address),
+ Some(payment_method),
+ );
+
+ // Assert
+ assert!(result.is_err());
+ let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
+ assert_eq!(missing_fields.len(), 1);
+ assert_eq!(*missing_fields.first().unwrap(), "shipping.address.zip");
+}
+
+#[test]
+fn should_return_error_when_missing_multiple_fields() {
+ // Arrange
+ let expected_missing_field_names: Vec<&str> =
+ vec!["shipping.address.zip", "shipping.address.country"];
+ let stripe_shipping_address =
+ create_stripe_shipping_address("name".to_string(), Some("line1".to_string()), None, None);
+ let payment_method = &StripePaymentMethodType::AfterpayClearpay;
+
+ //Act
+ let result = validate_shipping_address_against_payment_method(
+ &Some(stripe_shipping_address),
+ Some(payment_method),
+ );
+
+ // Assert
+ assert!(result.is_err());
+ let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
+ for field in missing_fields {
+ assert!(expected_missing_field_names.contains(&field.as_ref()));
+ }
+}
+
+fn get_missing_fields(connector_error: &ConnectorError) -> Vec<Cow<'static, str>> {
+ if let ConnectorError::MissingRequiredFields { field_names } = connector_error {
+ return field_names.to_vec();
+ }
+
+ vec![]
+}
+
+fn create_stripe_shipping_address(
+ name: String,
+ line1: Option<String>,
+ country: Option<CountryAlpha2>,
+ zip: Option<String>,
+) -> StripeShippingAddress {
+ StripeShippingAddress {
+ name: Some(Secret::new(name)),
+ line1: line1.map(Secret::new),
+ country,
+ zip: zip.map(Secret::new),
+ city: Some(String::from("city")),
+ line2: Some(Secret::new(String::from("line2"))),
+ state: Some(Secret::new(String::from("state"))),
+ phone: Some(Secret::new(String::from("pbone number"))),
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs
index 348e77adf2..92b7763db5 100644
--- a/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs
@@ -530,7 +530,7 @@ pub struct ThreedsecureioAuthenticationRequest {
pub acs_end_protocol_version: String,
pub three_dsserver_trans_id: String,
pub acct_number: cards::CardNumber,
- pub notification_url: String,
+ pub notification_url: Secret<String>,
pub three_dscomp_ind: ThreeDSecureIoThreeDsCompletionIndicator,
pub three_dsrequestor_url: String,
pub acquirer_bin: String,
diff --git a/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
index 8d8f9a8365..585293e1ad 100644
--- a/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
@@ -51,7 +51,7 @@ pub struct PaymentInitiation {
pub amount: Amount,
pub local_instrument: LocalInstrument,
pub creditor: Creditor,
- pub callback_url: Option<String>,
+ pub callback_url: Option<Secret<String>>,
pub flow_type: FlowType,
}
@@ -458,7 +458,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsRes
match auth {
Authentication::RedirectUrl { redirect_url } => {
RedirectForm::Form {
- endpoint: redirect_url.to_string(),
+ endpoint: redirect_url.to_string().into(),
method: Method::Get,
form_fields: HashMap::new(),
}
diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
index 7b4a1f0006..11fe75a686 100644
--- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
@@ -163,9 +163,9 @@ pub struct BankPaymentInformationResponse {
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct CallbackURLs {
- pub success: String,
- pub cancel: String,
- pub error: String,
+ pub success: Secret<String>,
+ pub cancel: Secret<String>,
+ pub error: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
@@ -179,7 +179,7 @@ pub struct PaymentRequestCards {
pub cardholder: Secret<String>,
pub reference: String,
#[serde(rename = "redirectUrl")]
- pub redirect_url: String,
+ pub redirect_url: Secret<String>,
#[serde(rename = "billing[city]")]
pub billing_city: String,
#[serde(rename = "billing[country]")]
@@ -245,7 +245,7 @@ pub struct PaymentRequestNetworkToken {
#[serde(rename = "exp")]
pub expiry_date: Secret<String>,
#[serde(rename = "RedirectUrl")]
- pub redirect_url: String,
+ pub redirect_url: Secret<String>,
#[serde(rename = "threeDSecureEnrollmentStatus")]
pub enrollment_status: char,
#[serde(rename = "threeDSecureEci")]
@@ -344,7 +344,7 @@ fn get_card_request_data(
params: TrustpayMandatoryParams,
amount: StringMajorUnit,
ccard: &Card,
- return_url: String,
+ return_url: Secret<String>,
) -> Result<TrustpayPaymentsRequest, Error> {
let email = item.request.get_email()?;
let customer_ip_address = browser_info.get_ip_address()?;
@@ -470,7 +470,7 @@ fn get_bank_redirection_request_data(
debtor: get_debtor_info(item, pm, params)?,
},
callback_urls: CallbackURLs {
- success: format!("{return_url}?status=SuccessOk"),
+ success: utils::append_url_query_param(&return_url, "status", "SuccessOk")?,
cancel: return_url.clone(),
error: return_url,
},
@@ -504,7 +504,7 @@ fn get_bank_transfer_request_data(
debtor: get_bank_transfer_debtor_info(item, pm, params)?,
},
callback_urls: CallbackURLs {
- success: format!("{return_url}?status=SuccessOk"),
+ success: utils::append_url_query_param(&return_url, "status", "SuccessOk")?,
cancel: return_url.clone(),
error: return_url,
},
@@ -900,9 +900,12 @@ fn handle_cards_response(
let form_fields = response.redirect_params.unwrap_or_default();
let redirection_data = response.redirect_url.map(|url| RedirectForm::Form {
- endpoint: url.to_string(),
+ endpoint: url.to_string().into(),
method: Method::Post,
- form_fields,
+ form_fields: (form_fields)
+ .into_iter()
+ .map(|(key, value)| (key, value.into()))
+ .collect(),
});
let error = if msg.is_some() {
Some(ErrorResponse {
diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
index 7bac061fd1..d5bf7f4e9c 100644
--- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
@@ -201,7 +201,7 @@ pub struct MerchantDetails {
pub three_ds_requestor_id: Option<String>,
pub three_ds_requestor_name: Option<String>,
pub merchant_country_code: Option<MerchantCountryCode>,
- pub notification_url: Option<url::Url>,
+ pub notification_url: Option<Secret<url::Url>>,
pub webhook_url: Option<url::Url>,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
index 37a599f00e..4c18d33704 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
@@ -114,7 +114,7 @@ pub struct ReturnUrls {
#[derive(Debug, Serialize)]
pub struct Link {
- link: Option<String>,
+ link: Option<Secret<String>>,
}
impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPaymentsRequest {
@@ -401,7 +401,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsRespon
.clone()
.expose();
let redirection_data = Some(RedirectForm::Form {
- endpoint: url.to_string(),
+ endpoint: url.to_string().into(),
method: Method::Get,
form_fields: Default::default(),
});
diff --git a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
index e2d4649471..0cb0aa2f74 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
@@ -126,7 +126,7 @@ pub struct RedirectPaymentMethod {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectionData {
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs
index 8137766ba7..57fc93e328 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs
@@ -34,8 +34,8 @@ use hyperswitch_domain_models::{
PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
- SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback, RedirectForm,
+ RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
@@ -1425,6 +1425,10 @@ impl IncomingWebhook for Worldpay {
}
impl ConnectorRedirectResponse for Worldpay {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::WorldpayDDCForm { .. }).then_some(RedirectCallback::Complete)
+ }
+
fn get_flow_type(
&self,
_query_params: &str,
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
index 976d00ed67..a50dc386e1 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
@@ -309,7 +309,7 @@ pub enum ThreeDSRequestChannel {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSRequestChallenge {
- pub return_url: String,
+ pub return_url: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub preference: Option<ThreeDsPreference>,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
index b6b8894add..5300c7dcfa 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
@@ -253,7 +253,8 @@ impl TryFrom<(enums::PaymentMethod, Option<enums::PaymentMethodType>)> for Payme
// Trait to abstract common functionality between Authorize and SetupMandate
trait WorldpayPaymentsRequestData {
- fn get_return_url(&self) -> Result<String, error_stack::Report<errors::ConnectorError>>;
+ fn get_return_url(&self)
+ -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>>;
fn get_auth_type(&self) -> &enums::AuthenticationType;
fn get_browser_info(&self) -> Option<&BrowserInformation>;
fn get_payment_method_data(&self) -> &PaymentMethodData;
@@ -279,7 +280,9 @@ trait WorldpayPaymentsRequestData {
impl WorldpayPaymentsRequestData
for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
- fn get_return_url(&self) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ fn get_return_url(
+ &self,
+ ) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>> {
self.request.get_complete_authorize_url()
}
@@ -363,7 +366,9 @@ impl WorldpayPaymentsRequestData
impl WorldpayPaymentsRequestData
for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
- fn get_return_url(&self) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ fn get_return_url(
+ &self,
+ ) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>> {
self.request.get_complete_authorize_url()
}
@@ -880,11 +885,11 @@ impl<F, T>
WorldpayPaymentResponseFields::ThreeDsChallenged(res) => (
None,
Some(RedirectForm::Form {
- endpoint: res.challenge.url.to_string(),
+ endpoint: res.challenge.url.to_string().into(),
method: common_utils::request::Method::Post,
form_fields: HashMap::from([(
"JWT".to_string(),
- res.challenge.jwt.clone().expose(),
+ res.challenge.jwt.clone(),
)]),
}),
None,
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs b/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
index 0ae798a38f..2d97a27505 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
@@ -3,6 +3,7 @@ pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
+use common_enums::{CallConnectorAction, PaymentAction};
use common_types::payments::GpayTokenizationData;
use common_utils::{
errors::CustomResult,
@@ -30,8 +31,8 @@ use hyperswitch_domain_models::{
SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
- SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectCallback, RedirectForm,
+ RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
@@ -1572,6 +1573,22 @@ static WORLDPAYXML_SUPPORTED_WEBHOOK_FLOWS: &[common_enums::EventClass] = &[
common_enums::EventClass::Payouts,
];
+impl api::ConnectorRedirectResponse for Worldpayxml {
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ matches!(form, RedirectForm::WorldpayxmlDDCForm { .. })
+ .then_some(RedirectCallback::Complete)
+ }
+
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ _action: PaymentAction,
+ ) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
+ Ok(CallConnectorAction::Trigger)
+ }
+}
+
impl ConnectorSpecifications for Worldpayxml {
fn is_webhook_mtls_required(&self) -> bool {
true
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs
index 4a0a760b1a..a434ff64dc 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs
@@ -2623,7 +2623,7 @@ struct ChallengeJwt {
#[serde(rename = "OrgUnitId")]
org_unit_id: Secret<String>,
#[serde(rename = "ReturnUrl")]
- return_url: String,
+ return_url: Secret<String>,
#[serde(rename = "Payload")]
payload: Payload,
#[serde(rename = "ObjectifyPayload")]
@@ -2726,7 +2726,7 @@ fn generate_challenge_jwt(
acs_url: String,
payload: String,
transaction_id: String,
- return_url: String,
+ return_url: Secret<String>,
metadata_for_jwt: WorldpayxmlConnectorMetadataObject,
) -> Result<String, errors::ConnectorError> {
let iat: u64 = common_utils::date_time::now_unix_timestamp()
diff --git a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
index c49869add0..a676455805 100644
--- a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
@@ -51,8 +51,8 @@ pub enum PaymentMethodType {
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChannelProperties {
- pub success_return_url: String,
- pub failure_return_url: String,
+ pub success_return_url: Secret<String>,
+ pub failure_return_url: Secret<String>,
pub skip_three_d_secure: bool,
}
#[derive(Serialize, Deserialize, Debug)]
@@ -486,7 +486,7 @@ impl TryFrom<PaymentsResponseRouterData<XenditPaymentResponse>> for PaymentsAuth
Some(actions) if !actions.is_empty() => {
actions.first().map_or(Box::new(None), |single_action| {
Box::new(Some(RedirectForm::Form {
- endpoint: single_action.url.clone(),
+ endpoint: single_action.url.clone().into(),
method: match single_action.method {
MethodType::Get => Method::Get,
MethodType::Post => Method::Post,
diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
index 62f1544756..4ff0bba173 100644
--- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
@@ -104,7 +104,7 @@ pub struct CheckoutRequest {
signature: Option<Secret<String>>,
specified_payment_channel: ZenPaymentChannels,
terminal_uuid: Secret<String>,
- url_redirect: String,
+ url_redirect: Secret<String>,
}
#[derive(Clone, Debug, Display, Serialize)]
@@ -149,7 +149,7 @@ pub struct ZenPaymentData {
#[serde(skip_serializing_if = "Option::is_none")]
card: Option<ZenCardDetails>,
descriptor: String,
- return_verify_url: Option<String>,
+ return_verify_url: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
@@ -157,7 +157,7 @@ pub struct ZenPaymentData {
pub struct ZenGeneralPaymentData {
#[serde(rename = "type")]
payment_type: ZenPaymentTypes,
- return_url: String,
+ return_url: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -613,7 +613,10 @@ fn get_signature_data(
"terminaluuid={}",
checkout_request.terminal_uuid.peek()
));
- signature_data.push(format!("urlredirect={}", checkout_request.url_redirect));
+ signature_data.push(format!(
+ "urlredirect={}",
+ checkout_request.url_redirect.peek()
+ ));
let signature = signature_data.join("&");
Ok(signature.to_lowercase())
}
diff --git a/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs
index 4e02ab45bb..26362c9c9d 100644
--- a/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs
@@ -77,8 +77,8 @@ pub struct ZslPaymentsRequest {
mer_txn_date: String,
mer_id: Secret<String>,
lang: String,
- success_url: String,
- failure_url: String,
+ success_url: Secret<String>,
+ failure_url: Secret<String>,
success_s2s_url: String,
failure_s2s_url: String,
enctype: EncodingType,
@@ -340,7 +340,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsRespons
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Form {
- endpoint: redirect_url,
+ endpoint: redirect_url.into(),
method: Method::Get,
form_fields: HashMap::new(),
})),
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index a43fa7319b..1d422b5be1 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -2755,7 +2755,6 @@ default_imp_for_connector_redirect_response!(
connectors::Calida,
connectors::Bamboraapac,
connectors::Bankofamerica,
- connectors::Barclaycard,
connectors::Boku,
connectors::Cashtocode,
connectors::Celero,
@@ -2765,7 +2764,6 @@ default_imp_for_connector_redirect_response!(
connectors::Coingate,
connectors::Cryptopay,
connectors::Custombilling,
- connectors::Cybersource,
connectors::Cybersourcedecisionmanager,
connectors::D24,
connectors::Datatrans,
@@ -2794,7 +2792,6 @@ default_imp_for_connector_redirect_response!(
connectors::Gocardless,
connectors::GotymeSanlam,
connectors::Gpayments,
- connectors::Hipay,
connectors::Hyperpg,
connectors::Helcim,
connectors::HyperswitchVault,
@@ -2812,7 +2809,6 @@ default_imp_for_connector_redirect_response!(
connectors::Klarna,
connectors::Loonio,
connectors::Merchante,
- connectors::Mifinity,
connectors::Moneris,
connectors::Mpgs,
connectors::Multisafepay,
@@ -2876,7 +2872,6 @@ default_imp_for_connector_redirect_response!(
connectors::Wellsfargopayout,
connectors::Worldline,
connectors::Worldpayvantiv,
- connectors::Worldpayxml,
connectors::Volt,
connectors::Zsl,
connectors::CtpMastercard
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index b4e4321e06..d4df56b64b 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -2490,14 +2490,14 @@ pub trait PaymentsAuthorizeRequestData {
fn is_customer_initiated_mandate_payment(&self) -> bool;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_optional_webhook_url(&self) -> Option<String>;
- fn get_router_return_url(&self) -> Result<String, Error>;
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error>;
fn is_wallet(&self) -> bool;
fn is_card(&self) -> bool;
fn is_mit_payment(&self) -> bool;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_connector_mandate_id(&self) -> Result<String, Error>;
fn get_connector_mandate_data(&self) -> Option<mandates::ConnectorMandateReferenceId>;
- fn get_complete_authorize_url(&self) -> Result<String, Error>;
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error>;
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>;
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>;
fn get_optional_user_agent(&self) -> Option<String>;
@@ -2565,7 +2565,7 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData {
}
}
- fn get_complete_authorize_url(&self) -> Result<String, Error> {
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
@@ -2601,7 +2601,7 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData {
fn get_optional_webhook_url(&self) -> Option<String> {
self.webhook_url.clone()
}
- fn get_router_return_url(&self) -> Result<String, Error> {
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
@@ -3054,12 +3054,12 @@ impl RefundsRequestData for RefundsData {
pub trait PaymentsSetupMandateRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_email(&self) -> Result<Email, Error>;
- fn get_router_return_url(&self) -> Result<String, Error>;
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error>;
fn is_card(&self) -> bool;
- fn get_return_url(&self) -> Result<String, Error>;
+ fn get_return_url(&self) -> Result<Secret<String>, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_optional_language_from_browser_info(&self) -> Option<String>;
- fn get_complete_authorize_url(&self) -> Result<String, Error>;
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn is_customer_initiated_mandate_payment(&self) -> bool;
}
@@ -3073,7 +3073,7 @@ impl PaymentsSetupMandateRequestData for SetupMandateRequestData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
- fn get_router_return_url(&self) -> Result<String, Error> {
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("router_return_url"))
@@ -3081,7 +3081,7 @@ impl PaymentsSetupMandateRequestData for SetupMandateRequestData {
fn is_card(&self) -> bool {
matches!(self.payment_method_data, PaymentMethodData::Card(_))
}
- fn get_return_url(&self) -> Result<String, Error> {
+ fn get_return_url(&self) -> Result<Secret<String>, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
@@ -3096,7 +3096,7 @@ impl PaymentsSetupMandateRequestData for SetupMandateRequestData {
.clone()
.and_then(|browser_info| browser_info.language)
}
- fn get_complete_authorize_url(&self) -> Result<String, Error> {
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
@@ -3120,7 +3120,7 @@ pub trait PaymentMethodTokenizationRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_optional_ip_address(&self) -> Option<Secret<String, IpAddress>>;
fn get_optional_user_agent(&self) -> Option<String>;
- fn get_router_return_url(&self) -> Result<String, Error>;
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error>;
fn is_mandate_payment(&self) -> bool;
fn is_customer_initiated_mandate_payment(&self) -> bool;
fn is_stripe_split_payment(&self) -> bool;
@@ -3146,7 +3146,7 @@ impl PaymentMethodTokenizationRequestData for PaymentMethodTokenizationData {
.and_then(|browser_info| browser_info.user_agent.clone())
}
- fn get_router_return_url(&self) -> Result<String, Error> {
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("router_return_url"))
@@ -3176,14 +3176,14 @@ pub trait PaymentsCompleteAuthorizeRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
- fn get_complete_authorize_url(&self) -> Result<String, Error>;
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error>;
fn is_mandate_payment(&self) -> bool;
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>;
fn is_cit_mandate_payment(&self) -> bool;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_threeds_method_comp_ind(&self) -> Result<payments::ThreeDsCompletionIndicator, Error>;
fn get_connector_mandate_id(&self) -> Option<String>;
- fn get_router_return_url(&self) -> Result<String, Error>;
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error>;
}
impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData {
@@ -3196,7 +3196,7 @@ impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData {
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
- fn get_router_return_url(&self) -> Result<String, Error> {
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("router_return_url"))
@@ -3215,7 +3215,7 @@ impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData {
.into(),
)
}
- fn get_complete_authorize_url(&self) -> Result<String, Error> {
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
@@ -3350,7 +3350,7 @@ impl PaymentsPreAuthenticateRequestData for PaymentsPreAuthenticateData {
pub trait PaymentsAuthenticateRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_payment_method_data(&self) -> Result<PaymentMethodData, Error>;
- fn get_complete_authorize_url(&self) -> Result<String, Error>;
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
}
@@ -3373,7 +3373,7 @@ impl PaymentsAuthenticateRequestData for PaymentsAuthenticateData {
.ok_or_else(missing_field_err("payment_method_data"))
}
- fn get_complete_authorize_url(&self) -> Result<String, Error> {
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
@@ -6743,14 +6743,7 @@ impl QrImage {
}
#[cfg(test)]
-mod tests {
- use crate::utils;
- #[test]
- fn test_image_data_source_url() {
- let qr_image_data_source_url = utils::QrImage::new_from_data("Hyperswitch".to_string());
- assert!(qr_image_data_source_url.is_ok());
- }
-}
+mod tests;
pub fn get_mandate_details(
setup_mandate_details: Option<mandates::MandateData>,
@@ -7718,6 +7711,7 @@ pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data(
setup_future_usage: data.request.setup_future_usage,
off_session: data.request.off_session,
setup_mandate_details: data.request.setup_mandate_details.clone(),
+ router_notification_url: None,
router_return_url: data.request.router_return_url.clone(),
email: data.request.email.clone(),
customer_name: data.request.customer_name.clone(),
@@ -8441,3 +8435,15 @@ impl ExtendedAuthorizationData for PaymentsCancelData {
None
}
}
+
+/// Append a connector query parameter without replacing callback credentials.
+pub fn append_url_query_param(
+ value: &Secret<String>,
+ key: &str,
+ parameter: &str,
+) -> CustomResult<Secret<String>, errors::ConnectorError> {
+ let mut url = url::Url::parse(value.peek())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ url.query_pairs_mut().append_pair(key, parameter);
+ Ok(Secret::new(url.to_string()))
+}
diff --git a/crates/hyperswitch_connectors/src/utils/tests.rs b/crates/hyperswitch_connectors/src/utils/tests.rs
new file mode 100644
index 0000000000..3acfee46de
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/utils/tests.rs
@@ -0,0 +1,42 @@
+use hyperswitch_masking::{PeekInterface, Secret};
+
+use super::append_url_query_param;
+use crate::utils;
+
+#[test]
+fn appended_status_preserves_callback_token_and_fragment() {
+ let token = "d9dc53cc-d1a1-4f57-9077-d20c2d614daa";
+ let base = Secret::new(format!(
+ "https://router.test/payments/pay/merchant/redirect/token/{token}/response/connector?result=ok#result"
+ ));
+ let result = append_url_query_param(&base, "status", "success").expect("URL");
+ let parsed = url::Url::parse(result.peek()).expect("URL");
+ let pairs = parsed.query_pairs().collect::<Vec<_>>();
+ assert!(pairs
+ .iter()
+ .any(|(key, value)| key == "result" && value == "ok"));
+ assert!(pairs
+ .iter()
+ .any(|(key, value)| key == "status" && value == "success"));
+ assert_eq!(
+ parsed.path(),
+ format!("/payments/pay/merchant/redirect/token/{token}/response/connector")
+ );
+ assert_eq!(parsed.fragment(), Some("result"));
+ assert_eq!(
+ append_url_query_param(
+ &Secret::new("https://router.test/payments/path".to_string()),
+ "status",
+ "failure"
+ )
+ .expect("URL")
+ .peek(),
+ "https://router.test/payments/path?status=failure"
+ );
+}
+
+#[test]
+fn test_image_data_source_url() {
+ let qr_image_data_source_url = utils::QrImage::new_from_data("Hyperswitch".to_string());
+ assert!(qr_image_data_source_url.is_ok());
+}
diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs
index 13301c7b5c..21f504e507 100644
--- a/crates/hyperswitch_domain_models/src/api.rs
+++ b/crates/hyperswitch_domain_models/src/api.rs
@@ -96,6 +96,7 @@ impl_api_event_type!(Miscellaneous, (GenericLinkFormData));
#[derive(Debug, PartialEq)]
pub struct RedirectionFormData {
pub redirect_form: crate::router_response_types::RedirectForm,
+ pub callback_url: Option<hyperswitch_masking::Secret<String>>,
pub payment_method_data: Option<PaymentMethodData>,
pub amount: String,
pub currency: String,
diff --git a/crates/hyperswitch_domain_models/src/authentication.rs b/crates/hyperswitch_domain_models/src/authentication.rs
index 9b375216d9..dbfa6a2c89 100644
--- a/crates/hyperswitch_domain_models/src/authentication.rs
+++ b/crates/hyperswitch_domain_models/src/authentication.rs
@@ -85,7 +85,7 @@ pub struct Authentication {
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
#[encrypt(ty = Value)]
pub billing_address: Option<Encryptable<Secret<Value>>>,
#[encrypt(ty = Value)]
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 2edc9716a1..66d1439348 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -111,9 +111,11 @@ pub struct PaymentsAuthorizeData {
pub currency: storage_enums::Currency,
pub confirm: bool,
pub capture_method: Option<storage_enums::CaptureMethod>,
- pub router_return_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
+ /// Router callback for connector notifications, with a token independent of browser callbacks.
+ pub router_notification_url: Option<Secret<String>>,
pub webhook_url: Option<String>,
- pub complete_authorize_url: Option<String>,
+ pub complete_authorize_url: Option<Secret<String>>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<mandates::MandateIds>,
@@ -212,9 +214,9 @@ pub struct ExternalVaultProxyPaymentsData {
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
- pub router_return_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
pub webhook_url: Option<String>,
- pub complete_authorize_url: Option<String>,
+ pub complete_authorize_url: Option<Secret<String>>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<mandates::MandateIds>,
@@ -307,7 +309,7 @@ pub struct PaymentsPostSessionTokensData {
pub merchant_order_reference_id: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
- pub router_return_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
@@ -580,7 +582,7 @@ pub struct PaymentMethodTokenizationData {
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub mandate_id: Option<mandates::MandateIds>,
- pub router_return_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
pub capture_method: Option<storage_enums::CaptureMethod>,
}
@@ -697,7 +699,7 @@ pub struct CreateOrderRequestData {
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub webhook_url: Option<String>,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
- pub router_return_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub capture_method: Option<storage_enums::CaptureMethod>,
}
@@ -808,8 +810,8 @@ pub struct PaymentsPreAuthenticateData {
pub capture_method: Option<storage_enums::CaptureMethod>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
- pub router_return_url: Option<String>,
- pub complete_authorize_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
+ pub complete_authorize_url: Option<Secret<String>>,
pub browser_info: Option<BrowserInformation>,
pub enrolled_for_3ds: bool,
pub customer_name: Option<Secret<String>>,
@@ -905,7 +907,7 @@ pub struct PaymentsAuthenticateData {
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
- pub complete_authorize_url: Option<String>,
+ pub complete_authorize_url: Option<Secret<String>>,
pub browser_info: Option<BrowserInformation>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub minor_amount: Option<MinorUnit>,
@@ -916,7 +918,7 @@ pub struct PaymentsAuthenticateData {
pub webhook_url: Option<String>,
pub force_3ds_challenge: Option<bool>,
/// Merchant return URL, forwarded to the authentication leg.
- pub router_return_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
}
impl TryFrom<CompleteAuthorizeData> for PaymentsAuthenticateData {
@@ -961,7 +963,7 @@ pub struct PaymentsPostAuthenticateData {
// New amount for amount frame work
pub minor_amount: Option<MinorUnit>,
pub metadata: Option<pii::SecretSerdeValue>,
- pub complete_authorize_url: Option<String>,
+ pub complete_authorize_url: Option<Secret<String>>,
pub order_id: Option<String>,
}
@@ -1043,7 +1045,7 @@ pub struct CompleteAuthorizeData {
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub connector_meta: Option<serde_json::Value>,
- pub complete_authorize_url: Option<String>,
+ pub complete_authorize_url: Option<Secret<String>>,
pub metadata: Option<serde_json::Value>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub request_incremental_authorization: bool,
@@ -1056,7 +1058,7 @@ pub struct CompleteAuthorizeData {
pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>,
pub is_stored_credential: Option<bool>,
pub tokenization: Option<common_enums::Tokenization>,
- pub router_return_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
pub merchant_order_reference_id: Option<String>,
pub is_account_funded_transaction: Option<bool>,
pub recipient_details: Option<api_models::payments::RecipientDetails>,
@@ -1927,7 +1929,7 @@ pub struct SetupMandateRequestData {
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub setup_mandate_details: Option<mandates::MandateData>,
- pub router_return_url: Option<String>,
+ pub router_return_url: Option<Secret<String>>,
pub webhook_url: Option<String>,
pub feature_metadata: Option<api_models::payments::FeatureMetadata>,
pub browser_info: Option<BrowserInformation>,
@@ -1937,7 +1939,7 @@ pub struct SetupMandateRequestData {
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub request_incremental_authorization: bool,
pub metadata: Option<pii::SecretSerdeValue>,
- pub complete_authorize_url: Option<String>,
+ pub complete_authorize_url: Option<Secret<String>>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub enrolled_for_3ds: bool,
pub related_transaction_id: Option<String>,
diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
index 8a50f2c090..7c2987f076 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
@@ -1,5 +1,6 @@
use common_utils::{ext_traits::OptionExt, pii::Email};
use error_stack::{Report, ResultExt};
+use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
@@ -103,7 +104,7 @@ pub struct ConnectorAuthenticationRequestData {
pub message_category: MessageCategory,
pub device_channel: api_models::payments::DeviceChannel,
pub pre_authentication_data: PreAuthenticationData,
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
pub sdk_information: Option<api_models::payments::SdkInformation>,
pub email: Option<Email>,
pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
@@ -181,7 +182,7 @@ pub struct ExternalThreeDSConnectorMetadata {
#[derive(Clone, Debug)]
pub struct AuthenticationStore {
- pub cavv: Option<hyperswitch_masking::Secret<String>>,
+ pub cavv: Option<Secret<String>>,
pub authentication: authentication::Authentication,
}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs b/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
index 5c849722f4..c792db4403 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
@@ -29,7 +29,7 @@ pub struct MerchantDetails {
pub three_ds_requestor_url: Option<String>,
pub three_ds_requestor_id: Option<String>,
pub three_ds_requestor_name: Option<String>,
- pub notification_url: Option<url::Url>,
+ pub notification_url: Option<Secret<url::Url>>,
pub webhook_url: Option<url::Url>,
}
@@ -49,7 +49,7 @@ pub struct UasAuthenticationRequestData {
pub browser_details: Option<super::BrowserInformation>,
pub transaction_details: TransactionDetails,
pub pre_authentication_data: super::authentication::PreAuthenticationData,
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
pub sdk_information: Option<api_models::payments::SdkInformation>,
pub email: Option<common_utils::pii::Email>,
pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index bef7253888..1c33774db8 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -12,6 +12,7 @@ pub use disputes::{
SubmitEvidenceResponse,
};
use error_stack::ResultExt;
+use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
@@ -219,16 +220,14 @@ impl CaptureSyncResponse {
}
}
impl PaymentsResponseData {
- pub fn get_connector_metadata(&self) -> Option<hyperswitch_masking::Secret<serde_json::Value>> {
+ pub fn get_connector_metadata(&self) -> Option<Secret<serde_json::Value>> {
match self {
Self::TransactionResponse {
connector_metadata, ..
}
| Self::PreProcessingResponse {
connector_metadata, ..
- } => connector_metadata
- .clone()
- .map(hyperswitch_masking::Secret::new),
+ } => connector_metadata.clone().map(Secret::new),
_ => None,
}
}
@@ -399,15 +398,24 @@ impl PreprocessingResponseId {
}
}
+/// Callback endpoint used by a connector's browser redirect form.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RedirectCallback {
+ /// Process a connector redirect response.
+ Response,
+ /// Complete authorization after a browser interaction.
+ Complete,
+}
+
#[derive(Debug, Eq, PartialEq, Clone, Serialize, serde::Deserialize)]
pub enum RedirectForm {
Form {
- endpoint: String,
+ endpoint: Secret<String>,
method: Method,
- form_fields: HashMap<String, String>,
+ form_fields: HashMap<String, Secret<String>>,
},
Html {
- html_data: String,
+ html_data: Secret<String>,
},
BarclaycardAuthSetup {
access_token: String,
@@ -439,12 +447,12 @@ pub enum RedirectForm {
client_token: String,
card_token: String,
bin: String,
- acs_url: String,
+ acs_url: Secret<String>,
},
Nmi {
amount: String,
currency: common_enums::Currency,
- public_key: hyperswitch_masking::Secret<String>,
+ public_key: Secret<String>,
customer_vault_id: String,
order_id: String,
},
@@ -471,14 +479,14 @@ impl From<(url::Url, Method)> for RedirectForm {
let form_fields = HashMap::from_iter(
redirect_url
.query_pairs()
- .map(|(key, value)| (key.to_string(), value.to_string())),
+ .map(|(key, value)| (key.to_string(), value.to_string().into())),
);
// Do not include query params in the endpoint
redirect_url.set_query(None);
Self::Form {
- endpoint: redirect_url.to_string(),
+ endpoint: redirect_url.to_string().into(),
method,
form_fields,
}
@@ -753,7 +761,7 @@ pub enum AuthenticationResponseData {
},
AuthNResponse {
authn_flow_type: AuthNFlowType,
- authentication_value: Option<hyperswitch_masking::Secret<String>>,
+ authentication_value: Option<Secret<String>>,
trans_status: common_enums::TransactionStatus,
connector_metadata: Option<serde_json::Value>,
ds_trans_id: Option<String>,
@@ -765,7 +773,7 @@ pub enum AuthenticationResponseData {
},
PostAuthNResponse {
trans_status: common_enums::TransactionStatus,
- authentication_value: Option<hyperswitch_masking::Secret<String>>,
+ authentication_value: Option<Secret<String>>,
eci: Option<String>,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
@@ -856,8 +864,8 @@ impl PaymentMethodDetails {
#[derive(Debug, Clone)]
pub enum VaultResponseData {
ExternalVaultCreateResponse {
- session_id: hyperswitch_masking::Secret<String>,
- client_secret: hyperswitch_masking::Secret<String>,
+ session_id: Secret<String>,
+ client_secret: Secret<String>,
},
ExternalVaultInsertResponse {
connector_vault_id: VaultIdType,
@@ -880,16 +888,16 @@ pub enum VaultIdType {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MultiVaultIdType {
Card {
- tokenized_card_number: Option<hyperswitch_masking::Secret<String>>,
- tokenized_card_expiry_year: Option<hyperswitch_masking::Secret<String>>,
- tokenized_card_expiry_month: Option<hyperswitch_masking::Secret<String>>,
- tokenized_card_cvc: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_card_number: Option<Secret<String>>,
+ tokenized_card_expiry_year: Option<Secret<String>>,
+ tokenized_card_expiry_month: Option<Secret<String>>,
+ tokenized_card_cvc: Option<Secret<String>>,
},
NetworkToken {
- tokenized_network_token: Option<hyperswitch_masking::Secret<String>>,
- tokenized_network_token_exp_year: Option<hyperswitch_masking::Secret<String>>,
- tokenized_network_token_exp_month: Option<hyperswitch_masking::Secret<String>>,
- tokenized_cryptogram: Option<hyperswitch_masking::Secret<String>>,
+ tokenized_network_token: Option<Secret<String>>,
+ tokenized_network_token_exp_year: Option<Secret<String>>,
+ tokenized_network_token_exp_month: Option<Secret<String>>,
+ tokenized_cryptogram: Option<Secret<String>>,
},
}
@@ -956,34 +964,4 @@ impl Default for VaultResponseData {
}
#[cfg(test)]
-mod pii_masking_tests {
- use super::ConnectorCustomerResponseData;
-
- /// Connectors parse the customer email into a masked `Email`; this domain
- /// type used to strip it back to a plain `String`, so the address reached
- /// any log that serializes the struct via `masked_serialize`.
- #[test]
- fn connector_customer_email_is_masked_for_logging() {
- let email = common_utils::pii::Email::try_from("[email protected]".to_string())
- .expect("valid email");
- let data = ConnectorCustomerResponseData::new(
- "cus_1".to_string(),
- Some("Jane Doe".to_string()),
- Some(email),
- None,
- );
-
- let masked = hyperswitch_masking::masked_serialize(&data)
- .expect("masked serialization")
- .to_string();
-
- assert!(
- !masked.contains("[email protected]"),
- "email leaked into the log view: {masked}"
- );
- assert!(
- masked.contains("@example.com"),
- "EmailStrategy should retain the domain, got: {masked}"
- );
- }
-}
+mod tests;
diff --git a/crates/hyperswitch_domain_models/src/router_response_types/tests.rs b/crates/hyperswitch_domain_models/src/router_response_types/tests.rs
new file mode 100644
index 0000000000..bd9812d9e2
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/router_response_types/tests.rs
@@ -0,0 +1,29 @@
+use super::ConnectorCustomerResponseData;
+
+/// Connectors parse the customer email into a masked `Email`; this domain
+/// type used to strip it back to a plain `String`, so the address reached
+/// any log that serializes the struct via `masked_serialize`.
+#[test]
+fn connector_customer_email_is_masked_for_logging() {
+ let email = common_utils::pii::Email::try_from("[email protected]".to_string())
+ .expect("valid email");
+ let data = ConnectorCustomerResponseData::new(
+ "cus_1".to_string(),
+ Some("Jane Doe".to_string()),
+ Some(email),
+ None,
+ );
+
+ let masked = hyperswitch_masking::masked_serialize(&data)
+ .expect("masked serialization")
+ .to_string();
+
+ assert!(
+ !masked.contains("[email protected]"),
+ "email leaked into the log view: {masked}"
+ );
+ assert!(
+ masked.contains("@example.com"),
+ "EmailStrategy should retain the domain, got: {masked}"
+ );
+}
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index efb0a23f82..28a6a6a767 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -87,8 +87,8 @@ use hyperswitch_domain_models::{
merchant_connector_webhook_management::{
ConnectorWebhookGenerateSecretResponse, ConnectorWebhookRegisterResponse,
},
- ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, SupportedPaymentMethods,
- VerifyWebhookSourceResponseData,
+ ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, RedirectCallback,
+ RedirectForm, SupportedPaymentMethods, VerifyWebhookSourceResponseData,
},
};
use hyperswitch_masking::Maskable;
@@ -1049,6 +1049,16 @@ pub trait ConnectorValidation: ConnectorCommon + ConnectorSpecifications {
/// trait ConnectorRedirectResponse
pub trait ConnectorRedirectResponse {
+ /// Callback endpoint required by this connector's browser redirect form.
+ fn get_redirect_callback(&self, _form: &RedirectForm) -> Option<RedirectCallback> {
+ None
+ }
+
+ /// Callback endpoint for connector notifications, separate from browser callbacks.
+ fn get_notification_callback(&self) -> Option<RedirectCallback> {
+ None
+ }
+
/// fn get_flow_type
fn get_flow_type(
&self,
diff --git a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
index f14a19e24c..6be1225cfd 100644
--- a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
+++ b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
@@ -11,7 +11,9 @@ use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_data_v2::RouterDataV2,
router_request_types::CurrentFlowInfo,
- router_response_types::{ConnectorInfo, SupportedPaymentMethods},
+ router_response_types::{
+ ConnectorInfo, RedirectCallback, RedirectForm, SupportedPaymentMethods,
+ },
};
use crate::{
@@ -489,6 +491,20 @@ impl IncomingWebhook for ConnectorEnum {
}
impl ConnectorRedirectResponse for ConnectorEnum {
+ fn get_notification_callback(&self) -> Option<RedirectCallback> {
+ match self {
+ Self::Old(connector) => connector.get_notification_callback(),
+ Self::New(connector) => connector.get_notification_callback(),
+ }
+ }
+
+ fn get_redirect_callback(&self, form: &RedirectForm) -> Option<RedirectCallback> {
+ match self {
+ Self::Old(connector) => connector.get_redirect_callback(form),
+ Self::New(connector) => connector.get_redirect_callback(form),
+ }
+ }
+
fn get_flow_type(
&self,
query_params: &str,
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index f898d5d194..59305b783d 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -2031,12 +2031,17 @@ impl ForeignTryFrom<payments_grpc::RedirectForm> for RedirectForm {
fn foreign_try_from(value: payments_grpc::RedirectForm) -> Result<Self, Self::Error> {
match value.form_type {
Some(payments_grpc::redirect_form::FormType::Form(form)) => Ok(Self::Form {
- endpoint: form.clone().endpoint,
+ endpoint: form.clone().endpoint.into(),
method: Method::foreign_try_from(form.clone().method())?,
- form_fields: form.clone().form_fields,
+ form_fields: form
+ .clone()
+ .form_fields
+ .into_iter()
+ .map(|(key, value)| (key, value.into()))
+ .collect(),
}),
Some(payments_grpc::redirect_form::FormType::Html(html)) => Ok(Self::Html {
- html_data: html.html_data,
+ html_data: html.html_data.into(),
}),
Some(payments_grpc::redirect_form::FormType::Uri(_)) => Err(
UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
@@ -2055,7 +2060,7 @@ impl ForeignTryFrom<payments_grpc::RedirectForm> for RedirectForm {
client_token: braintree.client_token,
card_token: braintree.card_token,
bin: braintree.bin,
- acs_url: braintree.acs_url,
+ acs_url: braintree.acs_url.into(),
})
}
Some(payments_grpc::redirect_form::FormType::Mifinity(mifinity)) => {
@@ -2803,67 +2808,4 @@ impl UnifiedConnectorServiceError {
}
#[cfg(test)]
-mod ucs_kill_switch_reason_tests {
- use super::*;
-
- fn tonic_status(code: tonic::Code) -> UnifiedConnectorServiceError {
- UnifiedConnectorServiceError::TonicStatus {
- code,
- message: "from ucs".to_string(),
- transport: None,
- }
- }
-
- #[test]
- fn ucs_wide_grpc_codes_still_qualify() {
- // While UCS is unwell the payment has no fallback and fails outright, so these qualify
- // like any other. They share a label so a run of them reads as one UCS-wide event.
- for code in [
- tonic::Code::Unavailable,
- tonic::Code::DeadlineExceeded,
- tonic::Code::ResourceExhausted,
- tonic::Code::Aborted,
- tonic::Code::Cancelled,
- ] {
- assert_eq!(
- tonic_status(code).ucs_kill_switch_reason(),
- Some(UcsKillSwitchReason::UcsUnreachable),
- "{code:?}"
- );
- }
- }
-
- #[test]
- fn ucs_side_grpc_codes_are_kill_switch_worthy() {
- // `from_grpc_error` extracts connector errors and timeouts before producing TonicStatus,
- // so what reaches here is UCS-side and repeats identically for this scope.
- let cases = [
- (
- tonic::Code::InvalidArgument,
- UcsKillSwitchReason::UcsRejectedRequest,
- ),
- (
- tonic::Code::FailedPrecondition,
- UcsKillSwitchReason::UcsRejectedRequest,
- ),
- (
- tonic::Code::Unauthenticated,
- UcsKillSwitchReason::UcsRejectedRequest,
- ),
- (
- tonic::Code::Unimplemented,
- UcsKillSwitchReason::UcsFlowUnsupported,
- ),
- (tonic::Code::Internal, UcsKillSwitchReason::UcsInternalError),
- (tonic::Code::Unknown, UcsKillSwitchReason::UcsInternalError),
- ];
-
- for (code, expected) in cases {
- assert_eq!(
- tonic_status(code).ucs_kill_switch_reason(),
- Some(expected),
- "{code:?}"
- );
- }
- }
-}
+mod tests;
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers/tests.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers/tests.rs
new file mode 100644
index 0000000000..80379306f4
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers/tests.rs
@@ -0,0 +1,62 @@
+use super::*;
+
+fn tonic_status(code: tonic::Code) -> UnifiedConnectorServiceError {
+ UnifiedConnectorServiceError::TonicStatus {
+ code,
+ message: "from ucs".to_string(),
+ transport: None,
+ }
+}
+
+#[test]
+fn ucs_wide_grpc_codes_still_qualify() {
+ // While UCS is unwell the payment has no fallback and fails outright, so these qualify
+ // like any other. They share a label so a run of them reads as one UCS-wide event.
+ for code in [
+ tonic::Code::Unavailable,
+ tonic::Code::DeadlineExceeded,
+ tonic::Code::ResourceExhausted,
+ tonic::Code::Aborted,
+ tonic::Code::Cancelled,
+ ] {
+ assert_eq!(
+ tonic_status(code).ucs_kill_switch_reason(),
+ Some(UcsKillSwitchReason::UcsUnreachable),
+ "{code:?}"
+ );
+ }
+}
+
+#[test]
+fn ucs_side_grpc_codes_are_kill_switch_worthy() {
+ // `from_grpc_error` extracts connector errors and timeouts before producing TonicStatus,
+ // so what reaches here is UCS-side and repeats identically for this scope.
+ let cases = [
+ (
+ tonic::Code::InvalidArgument,
+ UcsKillSwitchReason::UcsRejectedRequest,
+ ),
+ (
+ tonic::Code::FailedPrecondition,
+ UcsKillSwitchReason::UcsRejectedRequest,
+ ),
+ (
+ tonic::Code::Unauthenticated,
+ UcsKillSwitchReason::UcsRejectedRequest,
+ ),
+ (
+ tonic::Code::Unimplemented,
+ UcsKillSwitchReason::UcsFlowUnsupported,
+ ),
+ (tonic::Code::Internal, UcsKillSwitchReason::UcsInternalError),
+ (tonic::Code::Unknown, UcsKillSwitchReason::UcsInternalError),
+ ];
+
+ for (code, expected) in cases {
+ assert_eq!(
+ tonic_status(code).ucs_kill_switch_reason(),
+ Some(expected),
+ "{code:?}"
+ );
+ }
+}
diff --git a/crates/redis_interface/src/metrics.rs b/crates/redis_interface/src/metrics.rs
index d4bec1fe1b..318a3663df 100644
--- a/crates/redis_interface/src/metrics.rs
+++ b/crates/redis_interface/src/metrics.rs
@@ -36,6 +36,7 @@ pub(crate) enum RedisOperation {
IncrementKeyWithExpiry,
DecrementKeyWithExpiry,
GetKey,
+ ConsumeKey,
GetMultipleKeys,
Exists,
DeleteKey,
diff --git a/crates/redis_interface/src/module/fred/commands.rs b/crates/redis_interface/src/module/fred/commands.rs
index be96d5949a..ae6f39772c 100644
--- a/crates/redis_interface/src/module/fred/commands.rs
+++ b/crates/redis_interface/src/module/fred/commands.rs
@@ -2329,6 +2329,39 @@ impl super::RedisConnectionWithContext {
Ok(del_result)
}
+ /// Atomically read and delete a string using MULTI/GET/DEL/EXEC.
+ /// Missing keys are never created. A successful return requires both a value
+ /// and confirmation that this transaction deleted exactly one key.
+ #[instrument(level = "DEBUG", skip_all)]
+ pub async fn consume_key(
+ &self,
+ key: &RedisKey,
+ ) -> CustomResult<Option<String>, errors::RedisError> {
+ let redis_key = key.tenant_aware_key(&self.redis_conn);
+ let transaction = self.get_transaction();
+ transaction
+ .get::<(), _>(&redis_key)
+ .await
+ .change_context(errors::RedisError::GetFailed)?;
+ transaction
+ .del::<(), _>(&redis_key)
+ .await
+ .change_context(errors::RedisError::DeleteFailed)?;
+ let result: (Option<String>, i64) = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
+ RedisOperation::ConsumeKey,
+ transaction.exec(true),
+ )
+ .await
+ .change_context(errors::RedisError::DeleteFailed)?;
+ match result {
+ (Some(value), 1) => Ok(Some(value)),
+ (None, 0) => Ok(None),
+ _ => Err(report!(errors::RedisError::UnknownResult)),
+ }
+ }
+
/// Sets a value in Redis if not already present, and returns the value (either existing or newly set).
/// This operation is atomic using Redis transactions.
#[instrument(level = "DEBUG", skip(self))]
diff --git a/crates/redis_interface/src/module/redis_rs/commands.rs b/crates/redis_interface/src/module/redis_rs/commands.rs
index 26fc2fc4ef..fa7d3783ae 100644
--- a/crates/redis_interface/src/module/redis_rs/commands.rs
+++ b/crates/redis_interface/src/module/redis_rs/commands.rs
@@ -1734,6 +1734,37 @@ impl super::RedisConnectionWithContext {
Ok(del_result)
}
+ /// Atomically read and delete a string using MULTI/GET/DEL/EXEC.
+ /// Missing keys are never created. A successful return requires both a value
+ /// and confirmation that this transaction deleted exactly one key.
+ #[instrument(level = "DEBUG", skip_all)]
+ pub async fn consume_key(
+ &self,
+ key: &RedisKey,
+ ) -> CustomResult<Option<String>, errors::RedisError> {
+ let redis_key = key.tenant_aware_key(&self.redis_conn);
+ let mut conn = self.redis_conn.pool.clone();
+ let result: (Option<String>, i64) = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
+ RedisOperation::ConsumeKey,
+ redis::pipe()
+ .atomic()
+ .cmd("GET")
+ .arg(&redis_key)
+ .cmd("DEL")
+ .arg(&redis_key)
+ .query_async(&mut conn),
+ )
+ .await
+ .change_context(errors::RedisError::DeleteFailed)?;
+ match result {
+ (Some(value), 1) => Ok(Some(value)),
+ (None, 0) => Ok(None),
+ _ => Err(report!(errors::RedisError::UnknownResult)),
+ }
+ }
+
/// Sets a value in Redis if not already present, and returns the value (either existing or newly set).
/// This operation is atomic using Redis transactions (MULTI/EXEC pipeline).
#[instrument(level = "DEBUG", skip(self))]
diff --git a/crates/redis_interface/src/test.rs b/crates/redis_interface/src/test.rs
index 4b44441b86..065a5e16c8 100644
--- a/crates/redis_interface/src/test.rs
+++ b/crates/redis_interface/src/test.rs
@@ -2743,3 +2743,71 @@ async fn test_cluster_pubsub() {
assert!(is_success);
}
+
+#[tokio::test]
+async fn test_consume_key_single_winner_and_replay() {
+ tokio::task::spawn_blocking(|| {
+ futures::executor::block_on(async {
+ let connection = test_connection(&RedisSettings::default())
+ .await
+ .expect("Redis connection");
+ let key: RedisKey = format!("test_consume_concurrent_{}", unique_test_id()).into();
+ connection
+ .set_key_with_expiry(&key, "unused", 60)
+ .await
+ .expect("seed token");
+ let results =
+ futures::future::join_all((0..32).map(|_| connection.consume_key(&key))).await;
+ let values = results
+ .into_iter()
+ .map(|result| result.expect("consume transaction"))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ values
+ .iter()
+ .filter(|value| value.as_deref() == Some("unused"))
+ .count(),
+ 1
+ );
+ assert_eq!(values.iter().filter(|value| value.is_none()).count(), 31);
+ assert_eq!(connection.consume_key(&key).await.expect("replay"), None);
+ assert!(!connection.exists::<()>(&key).await.expect("key absent"));
+ })
+ })
+ .await
+ .expect("test task");
+}
+
+#[tokio::test]
+async fn test_consume_key_missing_and_expired_are_not_created() {
+ tokio::task::spawn_blocking(|| {
+ futures::executor::block_on(async {
+ let connection = test_connection(&RedisSettings::default())
+ .await
+ .expect("Redis connection");
+ let key: RedisKey = format!("test_consume_expired_{}", unique_test_id()).into();
+ for _ in 0..2 {
+ assert_eq!(
+ connection.consume_key(&key).await.expect("unknown token"),
+ None
+ );
+ }
+ assert!(!connection.exists::<()>(&key).await.expect("missing key"));
+ connection
+ .set_key_with_expiry(&key, "unused", 60)
+ .await
+ .expect("seed token");
+ connection
+ .set_expire_at(&key, 1)
+ .await
+ .expect("expire token");
+ assert_eq!(
+ connection.consume_key(&key).await.expect("expired token"),
+ None
+ );
+ assert!(!connection.exists::<()>(&key).await.expect("expired key"));
+ })
+ })
+ .await
+ .expect("test task");
+}
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index 3ec63ac337..7c3635fb77 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -10,6 +10,7 @@ use common_utils::{
types::MinorUnit,
};
use error_stack::ResultExt;
+use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -30,7 +31,7 @@ pub struct StripeBillingDetails {
pub address: Option<AddressDetails>,
pub email: Option<Email>,
pub name: Option<String>,
- pub phone: Option<hyperswitch_masking::Secret<String>>,
+ pub phone: Option<Secret<String>>,
}
impl From<StripeBillingDetails> for payments::Address {
@@ -62,10 +63,10 @@ impl From<StripeBillingDetails> for payments::Address {
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct StripeCard {
pub number: cards::CardNumber,
- pub exp_month: hyperswitch_masking::Secret<String>,
- pub exp_year: hyperswitch_masking::Secret<String>,
- pub cvc: hyperswitch_masking::Secret<String>,
- pub holder_name: Option<hyperswitch_masking::Secret<String>>,
+ pub exp_month: Secret<String>,
+ pub exp_year: Secret<String>,
+ pub cvc: Secret<String>,
+ pub holder_name: Option<Secret<String>>,
}
// ApplePay wallet param is not available in stripe Docs
@@ -77,7 +78,7 @@ pub enum StripeWallet {
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct StripeUpi {
- pub vpa_id: hyperswitch_masking::Secret<String, UpiVpaMaskingStrategy>,
+ pub vpa_id: Secret<String, UpiVpaMaskingStrategy>,
}
#[derive(Debug, Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
@@ -175,20 +176,20 @@ impl From<StripePaymentMethodDetails> for payments::PaymentMethodData {
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct Shipping {
pub address: AddressDetails,
- pub name: Option<hyperswitch_masking::Secret<String>>,
+ pub name: Option<Secret<String>>,
pub carrier: Option<String>,
- pub phone: Option<hyperswitch_masking::Secret<String>>,
- pub tracking_number: Option<hyperswitch_masking::Secret<String>>,
+ pub phone: Option<Secret<String>>,
+ pub tracking_number: Option<Secret<String>>,
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct AddressDetails {
pub city: Option<String>,
pub country: Option<api_enums::CountryAlpha2>,
- pub line1: Option<hyperswitch_masking::Secret<String>>,
- pub line2: Option<hyperswitch_masking::Secret<String>>,
- pub postal_code: Option<hyperswitch_masking::Secret<String>>,
- pub state: Option<hyperswitch_masking::Secret<String>>,
+ pub line1: Option<Secret<String>>,
+ pub line2: Option<Secret<String>>,
+ pub postal_code: Option<Secret<String>>,
+ pub state: Option<Secret<String>>,
}
impl From<Shipping> for payments::Address {
@@ -245,7 +246,7 @@ pub enum AcceptanceType {
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct OnlineMandate {
- pub ip_address: hyperswitch_masking::Secret<String, IpAddress>,
+ pub ip_address: Secret<String, IpAddress>,
pub user_agent: String,
}
@@ -269,7 +270,7 @@ pub struct StripePaymentIntentRequest {
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub metadata: Option<serde_json::Value>,
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
pub payment_method_options: Option<StripePaymentMethodOptions>,
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
pub mandate: Option<String>,
@@ -481,7 +482,7 @@ pub struct StripePaymentIntentResponse {
pub amount_capturable: i64,
pub currency: String,
pub status: StripePaymentStatus,
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
pub created: Option<i64>,
pub customer: Option<id_type::CustomerId>,
pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>,
@@ -504,11 +505,11 @@ pub struct StripePaymentIntentResponse {
pub capture_on: Option<PrimitiveDateTime>,
pub payment_token: Option<String>,
pub email: Option<Email>,
- pub phone: Option<hyperswitch_masking::Secret<String>>,
+ pub phone: Option<Secret<String>>,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor_name: Option<String>,
pub capture_method: Option<api_models::enums::CaptureMethod>,
- pub name: Option<hyperswitch_masking::Secret<String>>,
+ pub name: Option<Secret<String>>,
pub last_payment_error: Option<LastPaymentError>,
pub connector_transaction_id: Option<String>,
}
@@ -719,7 +720,7 @@ pub struct MandateOption {
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub accepted_at: Option<PrimitiveDateTime>,
pub user_agent: Option<String>,
- pub ip_address: Option<hyperswitch_masking::Secret<String, IpAddress>>,
+ pub ip_address: Option<Secret<String, IpAddress>>,
pub mandate_type: Option<StripeMandateType>,
pub amount: Option<i64>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
@@ -815,7 +816,7 @@ impl ForeignFrom<Option<Request3DS>> for api_models::enums::AuthenticationType {
#[derive(Default, Eq, PartialEq, Serialize, Debug)]
pub struct RedirectUrl {
pub return_url: Option<String>,
- pub url: Option<String>,
+ pub url: Option<Secret<String>>,
}
#[derive(PartialEq, serde::Serialize, Debug)]
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index e99c29dd8d..8e23505fa4 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -3,6 +3,7 @@ use std::str::FromStr;
use api_models::payments;
use common_utils::{date_time, ext_traits::StringExt, id_type, pii as secret};
use error_stack::ResultExt;
+use hyperswitch_masking::Secret;
use router_env::logger;
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -26,7 +27,7 @@ pub struct StripeBillingDetails {
pub address: Option<payments::AddressDetails>,
pub email: Option<pii::Email>,
pub name: Option<String>,
- pub phone: Option<pii::Secret<String>>,
+ pub phone: Option<Secret<String>>,
}
impl From<StripeBillingDetails> for payments::Address {
@@ -45,9 +46,9 @@ impl From<StripeBillingDetails> for payments::Address {
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct StripeCard {
pub number: cards::CardNumber,
- pub exp_month: pii::Secret<String>,
- pub exp_year: pii::Secret<String>,
- pub cvc: pii::Secret<String>,
+ pub exp_month: Secret<String>,
+ pub exp_year: Secret<String>,
+ pub cvc: Secret<String>,
}
// ApplePay wallet param is not available in stripe Docs
@@ -96,7 +97,7 @@ impl From<StripeCard> for payments::Card {
card_number: card.number,
card_exp_month: card.exp_month,
card_exp_year: card.exp_year,
- card_holder_name: Some(hyperswitch_masking::Secret::new("stripe_cust".to_owned())),
+ card_holder_name: Some(Secret::new("stripe_cust".to_owned())),
card_cvc: card.cvc,
card_issuer: None,
card_network: None,
@@ -136,8 +137,8 @@ pub struct Shipping {
pub address: Option<payments::AddressDetails>,
pub name: Option<String>,
pub carrier: Option<String>,
- pub phone: Option<pii::Secret<String>>,
- pub tracking_number: Option<pii::Secret<String>>,
+ pub phone: Option<Secret<String>>,
+ pub tracking_number: Option<Secret<String>>,
}
impl From<Shipping> for payments::Address {
@@ -169,7 +170,7 @@ pub struct StripeSetupIntentRequest {
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub metadata: Option<secret::SecretSerdeValue>,
- pub client_secret: Option<pii::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
pub payment_method_options: Option<payment_intent::StripePaymentMethodOptions>,
pub payment_method: Option<String>,
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
@@ -231,11 +232,10 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest {
field_name: "currency".into(),
})?,
email: item.receipt_email,
- name: item.billing_details.as_ref().and_then(|b| {
- b.name
- .as_ref()
- .map(|x| hyperswitch_masking::Secret::new(x.to_owned()))
- }),
+ name: item
+ .billing_details
+ .as_ref()
+ .and_then(|b| b.name.as_ref().map(|x| Secret::new(x.to_owned()))),
phone: item.shipping.as_ref().and_then(|s| s.phone.clone()),
description: item.description,
return_url: item.return_url,
@@ -365,7 +365,7 @@ impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest {
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct RedirectUrl {
pub return_url: Option<String>,
- pub url: Option<String>,
+ pub url: Option<Secret<String>>,
}
#[derive(PartialEq, serde::Serialize)]
@@ -513,7 +513,7 @@ pub struct StripeSetupIntentResponse {
pub id: id_type::PaymentId,
pub object: String,
pub status: StripeSetupStatus,
- pub client_secret: Option<hyperswitch_masking::Secret<String>>,
+ pub client_secret: Option<Secret<String>>,
pub metadata: Option<Value>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created: Option<time::PrimitiveDateTime>,
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs
index a411e86000..637367d96a 100644
--- a/crates/router/src/compatibility/wrap.rs
+++ b/crates/router/src/compatibility/wrap.rs
@@ -134,6 +134,7 @@ where
let config = state.conf();
api::build_redirection_form(
&redirection_data.redirect_form,
+ redirection_data.callback_url.as_ref(),
redirection_data.payment_method_data,
redirection_data.amount,
redirection_data.currency,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index ec1e715dd7..f34ffd90dc 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -836,12 +836,12 @@ pub trait PaymentsAuthorizeRequestData {
fn is_cit_mandate_payment(&self) -> bool;
fn is_customer_initiated_mandate_payment(&self) -> bool;
fn get_webhook_url(&self) -> Result<String, Error>;
- fn get_router_return_url(&self) -> Result<String, Error>;
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error>;
fn is_wallet(&self) -> bool;
fn is_card(&self) -> bool;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_connector_mandate_id(&self) -> Result<String, Error>;
- fn get_complete_authorize_url(&self) -> Result<String, Error>;
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error>;
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>;
fn get_original_amount(&self) -> i64;
fn get_surcharge_amount(&self) -> Option<i64>;
@@ -898,7 +898,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
}
}
- fn get_complete_authorize_url(&self) -> Result<String, Error> {
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
@@ -952,7 +952,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
- fn get_router_return_url(&self) -> Result<String, Error> {
+ fn get_router_return_url(&self) -> Result<Secret<String>, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
@@ -1124,7 +1124,7 @@ pub trait PaymentsCompleteAuthorizeRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
- fn get_complete_authorize_url(&self) -> Result<String, Error>;
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error>;
fn is_mandate_payment(&self) -> bool;
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>;
fn is_cit_mandate_payment(&self) -> bool;
@@ -1154,7 +1154,7 @@ impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData {
.into(),
)
}
- fn get_complete_authorize_url(&self) -> Result<String, Error> {
+ fn get_complete_authorize_url(&self) -> Result<Secret<String>, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
@@ -2296,83 +2296,7 @@ pub fn get_card_details(
}
#[cfg(test)]
-mod error_code_error_message_tests {
- use super::*;
-
- struct TestConnector;
-
- impl ConnectorErrorTypeMapping for TestConnector {
- fn get_connector_error_type(
- &self,
- error_code: String,
- error_message: String,
- ) -> ConnectorErrorType {
- match (error_code.as_str(), error_message.as_str()) {
- ("01", "INVALID_MERCHANT") => ConnectorErrorType::BusinessError,
- ("03", "INVALID_CVV") => ConnectorErrorType::UserError,
- ("04", "04") => ConnectorErrorType::TechnicalError,
- _ => ConnectorErrorType::UnknownError,
- }
- }
- }
-
- #[test]
- fn test_get_error_code_error_message_based_on_priority() {
- let error_code_message_list_unknown = vec![
- ErrorCodeAndMessage {
- error_code: "01".to_string(),
- error_message: "INVALID_MERCHANT".to_string(),
- },
- ErrorCodeAndMessage {
- error_code: "05".to_string(),
- error_message: "05".to_string(),
- },
- ErrorCodeAndMessage {
- error_code: "03".to_string(),
- error_message: "INVALID_CVV".to_string(),
- },
- ErrorCodeAndMessage {
- error_code: "04".to_string(),
- error_message: "04".to_string(),
- },
- ];
- let error_code_message_list_user = vec![
- ErrorCodeAndMessage {
- error_code: "01".to_string(),
- error_message: "INVALID_MERCHANT".to_string(),
- },
- ErrorCodeAndMessage {
- error_code: "03".to_string(),
- error_message: "INVALID_CVV".to_string(),
- },
- ];
- let error_code_error_message_unknown = get_error_code_error_message_based_on_priority(
- TestConnector,
- error_code_message_list_unknown,
- );
- let error_code_error_message_user = get_error_code_error_message_based_on_priority(
- TestConnector,
- error_code_message_list_user,
- );
- let error_code_error_message_none =
- get_error_code_error_message_based_on_priority(TestConnector, vec![]);
- assert_eq!(
- error_code_error_message_unknown,
- Some(ErrorCodeAndMessage {
- error_code: "05".to_string(),
- error_message: "05".to_string(),
- })
- );
- assert_eq!(
- error_code_error_message_user,
- Some(ErrorCodeAndMessage {
- error_code: "03".to_string(),
- error_message: "INVALID_CVV".to_string(),
- })
- );
- assert_eq!(error_code_error_message_none, None);
- }
-}
+mod tests;
#[derive(Debug, strum::Display, Eq, PartialEq, Hash)]
pub enum PaymentMethodDataType {
diff --git a/crates/router/src/connector/utils/tests.rs b/crates/router/src/connector/utils/tests.rs
new file mode 100644
index 0000000000..85e69e49f6
--- /dev/null
+++ b/crates/router/src/connector/utils/tests.rs
@@ -0,0 +1,73 @@
+use super::*;
+
+struct TestConnector;
+
+impl ConnectorErrorTypeMapping for TestConnector {
+ fn get_connector_error_type(
+ &self,
+ error_code: String,
+ error_message: String,
+ ) -> ConnectorErrorType {
+ match (error_code.as_str(), error_message.as_str()) {
+ ("01", "INVALID_MERCHANT") => ConnectorErrorType::BusinessError,
+ ("03", "INVALID_CVV") => ConnectorErrorType::UserError,
+ ("04", "04") => ConnectorErrorType::TechnicalError,
+ _ => ConnectorErrorType::UnknownError,
+ }
+ }
+}
+
+#[test]
+fn test_get_error_code_error_message_based_on_priority() {
+ let error_code_message_list_unknown = vec![
+ ErrorCodeAndMessage {
+ error_code: "01".to_string(),
+ error_message: "INVALID_MERCHANT".to_string(),
+ },
+ ErrorCodeAndMessage {
+ error_code: "05".to_string(),
+ error_message: "05".to_string(),
+ },
+ ErrorCodeAndMessage {
+ error_code: "03".to_string(),
+ error_message: "INVALID_CVV".to_string(),
+ },
+ ErrorCodeAndMessage {
+ error_code: "04".to_string(),
+ error_message: "04".to_string(),
+ },
+ ];
+ let error_code_message_list_user = vec![
+ ErrorCodeAndMessage {
+ error_code: "01".to_string(),
+ error_message: "INVALID_MERCHANT".to_string(),
+ },
+ ErrorCodeAndMessage {
+ error_code: "03".to_string(),
+ error_message: "INVALID_CVV".to_string(),
+ },
+ ];
+ let error_code_error_message_unknown = get_error_code_error_message_based_on_priority(
+ TestConnector,
+ error_code_message_list_unknown,
+ );
+ let error_code_error_message_user =
+ get_error_code_error_message_based_on_priority(TestConnector, error_code_message_list_user);
+ let error_code_error_message_none =
+ get_error_code_error_message_based_on_priority(TestConnector, vec![]);
+ assert_eq!(
+ error_code_error_message_unknown,
+ Some(ErrorCodeAndMessage {
+ error_code: "05".to_string(),
+ error_message: "05".to_string(),
+ })
+ );
+ assert_eq!(
+ error_code_error_message_user,
+ Some(ErrorCodeAndMessage {
+ error_code: "03".to_string(),
+ error_message: "INVALID_CVV".to_string(),
+ })
+ );
+ assert_eq!(error_code_error_message_none, None);
+}
diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs
index 9f2493fa86..0891dc14f3 100644
--- a/crates/router/src/core/authentication.rs
+++ b/crates/router/src/core/authentication.rs
@@ -8,7 +8,7 @@ use common_enums::Currency;
use common_utils::{errors::CustomResult, ext_traits::ValueExt};
use error_stack::ResultExt;
use hyperswitch_domain_models::authentication;
-use hyperswitch_masking::ExposeInterface;
+use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use super::errors::StorageErrorExt;
use crate::{
@@ -17,7 +17,10 @@ use crate::{
errors::ApiErrorResponse, payment_methods::vault, payments as payments_core,
unified_connector_service,
},
- routes::SessionState,
+ routes::{
+ payments::callback_routes::{ConnectorCallbackPath, PaymentCallbackRoute},
+ SessionState,
+ },
types::{
self as core_types, api,
domain::{self},
@@ -43,7 +46,7 @@ pub async fn perform_authentication(
message_category: api::authentication::MessageCategory,
device_channel: payments::DeviceChannel,
authentication_data: authentication::Authentication,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
@@ -218,7 +221,7 @@ pub async fn perform_post_authentication(
let authentication_store =
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
- cavv: tokenized_data.map(|data| hyperswitch_masking::Secret::new(data.value1)),
+ cavv: tokenized_data.map(|data| Secret::new(data.value1)),
authentication: authentication_update,
};
@@ -574,8 +577,8 @@ async fn call_ucs_pre_authenticate_proxy(
connector_authentication_id: threeds_server_transaction_id.clone(),
threeds_server_transaction_id,
maximum_supported_3ds_version: message_version.clone(),
- three_ds_method_data,
- three_ds_method_url,
+ three_ds_method_data: three_ds_method_data.map(ExposeInterface::expose),
+ three_ds_method_url: three_ds_method_url.map(ExposeInterface::expose),
message_version,
connector_metadata: None,
directory_server_id,
@@ -645,7 +648,11 @@ pub async fn perform_pre_authentication_proxy<F: Clone>(
capture_method: payment_data.payment_attempt.get_effective_capture_method(),
currency: payment_data.payment_intent.currency,
payment_method_type: payment_data.payment_attempt.payment_method_type,
- router_return_url: payment_data.payment_intent.return_url.clone(),
+ router_return_url: payment_data
+ .payment_intent
+ .return_url
+ .clone()
+ .map(Into::into),
complete_authorize_url: None,
browser_info: None,
enrolled_for_3ds: true,
@@ -894,7 +901,7 @@ async fn call_ucs_post_authenticate_proxy<F: Clone>(
.clone()
.map(|tds| {
hyperswitch_domain_models::router_request_types::CompleteAuthorizeRedirectResponse {
- params: Some(hyperswitch_masking::Secret::new(tds)),
+ params: Some(Secret::new(tds)),
payload: None,
}
}),
@@ -1172,7 +1179,7 @@ pub async fn perform_post_authentication_proxy<F: Clone>(
Ok(
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
- cavv: tokenized_data.map(|data| hyperswitch_masking::Secret::new(data.value1)),
+ cavv: tokenized_data.map(|data| Secret::new(data.value1)),
authentication,
},
)
@@ -1422,14 +1429,21 @@ async fn call_ucs_authenticate_proxy(
business_profile.get_id().clone(),
);
- let notification_url = Some(common_utils::types::Url::wrap(
- url::Url::parse(&payments_core::helpers::create_authorize_url(
- &state.base_url,
- payment_attempt,
- &psp_connector_name,
- ))
- .change_context(ApiErrorResponse::InternalServerError)?,
- ));
+ let notification_url = PaymentCallbackRoute::authorize_url(
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_attempt.payment_id.clone(),
+ merchant_id: payment_attempt.processor_merchant_id.clone(),
+ connector: psp_connector_name.to_string(),
+ },
+ )
+ .persist(state)
+ .await?;
+ let notification_url = Some(Secret::new(common_utils::types::Url::wrap(
+ url::Url::parse(notification_url.peek())
+ .change_context(ApiErrorResponse::InternalServerError)?,
+ )));
// Prefer acquirer details set directly on the PSP connector's own metadata; fall back to the
// profile's card-network-keyed acquirer config the same way
@@ -1598,7 +1612,7 @@ fn parse_ucs_authenticate_response(
let authentication_type = common_enums::DecoupledAuthenticationType::from(trans_status.clone());
let acs_url = acs_url
- .map(|url| url::Url::parse(&url))
+ .map(|url| url::Url::parse(url.peek()))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("acs_url returned by UCS authenticate is not a valid URL")?;
@@ -1608,7 +1622,7 @@ fn parse_ucs_authenticate_response(
hyperswitch_domain_models::router_request_types::authentication::AuthNFlowType::Challenge(Box::new(
hyperswitch_domain_models::router_request_types::authentication::ChallengeParams {
acs_url: acs_url.clone(),
- challenge_request: challenge_request.clone(),
+ challenge_request: challenge_request.clone().map(ExposeInterface::expose),
challenge_request_key: None,
acs_reference_number: acs_reference_number.clone(),
acs_trans_id: acs_trans_id.clone(),
@@ -1649,7 +1663,7 @@ fn parse_ucs_authenticate_response(
authentication_type,
trans_status,
acs_url,
- challenge_request,
+ challenge_request: challenge_request.map(ExposeInterface::expose),
acs_reference_number,
acs_trans_id,
three_ds_server_transaction_id,
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 4a2c18affc..6dd3aec4f1 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -5,7 +5,7 @@ use common_enums::PaymentMethod;
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use hyperswitch_domain_models::authentication;
-use hyperswitch_masking::ExposeInterface;
+use hyperswitch_masking::{ExposeInterface, Secret};
use crate::{
core::{
@@ -41,7 +41,7 @@ pub fn construct_authentication_router_data(
device_channel: payments::DeviceChannel,
merchant_connector_account: payments_helpers::MerchantConnectorAccountType,
authentication_data: authentication::Authentication,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
diff --git a/crates/router/src/core/configs.rs b/crates/router/src/core/configs.rs
index 67bf038a3a..e47fbc7c48 100644
--- a/crates/router/src/core/configs.rs
+++ b/crates/router/src/core/configs.rs
@@ -1,5 +1,6 @@
pub mod dimension_config;
pub mod dimension_state;
+pub mod payment_callback;
use common_utils::errors::CustomResult;
pub use dimension_config::{
BlockImplicitCustomerCreation, EnableExtendedCardBin, ImplicitCustomerUpdate,
diff --git a/crates/router/src/core/configs/payment_callback.rs b/crates/router/src/core/configs/payment_callback.rs
new file mode 100644
index 0000000000..b4ae405bfe
--- /dev/null
+++ b/crates/router/src/core/configs/payment_callback.rs
@@ -0,0 +1,92 @@
+//! Payment callback policy stored as JSON under the `payment_callback` configs key.
+//!
+//! Example value: `{"mode":"migration"}`.
+//! Use the configs API to update this entry so cached values are invalidated.
+//! For a staged rollout, explicitly select legacy mode, then switch to migration
+//! after all replicas support tokenized paths and enforce once older flows drain.
+//! Every tenant must have a valid entry before the HTTP server starts. Tokens expire after
+//! `common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME` seconds.
+
+use error_stack::ResultExt;
+use hyperswitch_domain_models::configs::ConfigInterface;
+use serde::Deserialize;
+use storage_impl::errors::StorageError;
+
+use crate::{
+ core::errors::{self, RouterResult},
+ routes::{AppState, SessionState},
+};
+
+/// Runtime rollout policy for single-use payment callback URLs.
+#[derive(Debug, Deserialize, Clone)]
+pub struct PaymentCallbackConfig {
+ pub mode: PaymentCallbackMode,
+}
+
+#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum PaymentCallbackMode {
+ /// Preserve original URLs until all replicas support tokenized paths.
+ Legacy,
+ /// Issue tokenized paths while accepting callbacks from older payment flows.
+ Migration,
+ /// Require a token on every protected payment callback.
+ Enforced,
+}
+
+impl PaymentCallbackMode {
+ pub const fn issues_tokens(self) -> bool {
+ !matches!(self, Self::Legacy)
+ }
+
+ pub const fn allows_legacy(self) -> bool {
+ !matches!(self, Self::Enforced)
+ }
+}
+
+impl PaymentCallbackConfig {
+ pub const KEY: &'static str = "payment_callback";
+
+ pub(crate) async fn validate_at_startup(state: &AppState) -> RouterResult<()> {
+ for (tenant_id, store) in &state.stores {
+ Self::load_from_store(store.as_ref())
+ .await
+ .attach_printable_lazy(|| {
+ format!(
+ "Invalid or missing payment_callback config for tenant {}",
+ tenant_id.get_string_repr()
+ )
+ })?;
+ }
+ Ok(())
+ }
+
+ pub(crate) async fn load(state: &SessionState) -> RouterResult<Self> {
+ Self::load_from_store(state.store.as_ref()).await
+ }
+
+ async fn load_from_store(
+ store: &(impl ConfigInterface<Error = StorageError> + ?Sized),
+ ) -> RouterResult<Self> {
+ let config = store
+ .find_config_by_key_optional(Self::KEY)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch payment_callback config")?;
+ Self::parse(config.as_ref().map(|config| config.config.as_str()))
+ }
+
+ fn parse(value: Option<&str>) -> RouterResult<Self> {
+ let value = value
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Required config payment_callback is missing")?;
+ serde_json::from_str(value)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Invalid payment_callback config: mode must be legacy, migration, or enforced",
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/router/src/core/configs/payment_callback/tests.rs b/crates/router/src/core/configs/payment_callback/tests.rs
new file mode 100644
index 0000000000..15e0a4ba6d
--- /dev/null
+++ b/crates/router/src/core/configs/payment_callback/tests.rs
@@ -0,0 +1,40 @@
+use super::*;
+
+#[test]
+fn missing_callback_config_is_rejected() {
+ let error = PaymentCallbackConfig::parse(None).expect_err("missing config");
+ assert!(format!("{error:?}").contains("Required config payment_callback is missing"));
+}
+
+#[test]
+fn callback_config_supports_each_rollout_mode() {
+ for (value, mode) in [
+ ("legacy", PaymentCallbackMode::Legacy),
+ ("migration", PaymentCallbackMode::Migration),
+ ("enforced", PaymentCallbackMode::Enforced),
+ ] {
+ let value = serde_json::json!({"mode": value});
+ let config =
+ PaymentCallbackConfig::parse(Some(&value.to_string())).expect("valid callback config");
+ assert_eq!(config.mode, mode);
+ }
+}
+
+#[test]
+fn invalid_callback_config_is_rejected() {
+ for value in [
+ "",
+ "invalid JSON",
+ "null",
+ "{}",
+ r#"{"unrelated":"migration"}"#,
+ r#"{"mode":"unknown"}"#,
+ r#"{"mode":null}"#,
+ r#"{"mode":1}"#,
+ ] {
+ assert!(
+ PaymentCallbackConfig::parse(Some(value)).is_err(),
+ "{value}"
+ );
+ }
+}
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 2e30d846c4..24574b9ffa 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -137,7 +137,7 @@ where
.clone_from(&payment_data.get_payment_attempt().connector_transaction_id);
let mut router_data = frm_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
&frm_data.connector_details.connector_name,
platform.get_processor(),
@@ -398,7 +398,7 @@ pub async fn pre_payouts_frm_core(
)?;
let mut router_data: hyperswitch_connectors::types::PoFrmRouterData = frm_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
&applicability.frm_routing_algorithm.data,
platform.get_processor(),
diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
index 740630ddab..9991de1996 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -11,7 +11,10 @@ use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::types::FrmData,
- payments::{self, gateway::context::RouterGatewayContext, helpers},
+ payments::{
+ self, callback_urls::ConnectorCallbackUrls, gateway::context::RouterGatewayContext,
+ helpers,
+ },
utils::get_gateway_frm_metadata,
},
errors, services,
@@ -39,6 +42,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
todo!()
@@ -56,6 +60,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
use crate::connector::utils::PaymentsAttemptData;
diff --git a/crates/router/src/core/fraud_check/flows/po_frm_flow.rs b/crates/router/src/core/fraud_check/flows/po_frm_flow.rs
index aaf63fce77..3f7794b134 100644
--- a/crates/router/src/core/fraud_check/flows/po_frm_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/po_frm_flow.rs
@@ -8,7 +8,7 @@ use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::types::PayoutFrmData,
- payments::{self, helpers},
+ payments::{self, callback_urls::ConnectorCallbackUrls, helpers},
utils::get_payout_gateway_frm_metadata,
},
errors, services,
@@ -37,6 +37,7 @@ impl ConstructFlowSpecificData<frm_api::PoFrm, FraudCheckPayoutData, FraudCheckR
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<RouterData<frm_api::PoFrm, FraudCheckPayoutData, FraudCheckResponseData>>
{
let connector_auth_type: ConnectorAuthType = merchant_connector_account
diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs
index 2a40933571..dbeddc7d07 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -7,7 +7,9 @@ use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FraudCheckConnectorData, FrmData},
- payments::{self, flows::ConstructFlowSpecificData, helpers},
+ payments::{
+ self, callback_urls::ConnectorCallbackUrls, flows::ConstructFlowSpecificData, helpers,
+ },
},
errors, services,
types::{
@@ -36,6 +38,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
todo!()
@@ -53,6 +56,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
let status = storage_enums::AttemptStatus::Pending;
diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs
index ff18d19b25..0a65f1e54f 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -8,7 +8,9 @@ use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FraudCheckConnectorData, FrmData},
- payments::{self, flows::ConstructFlowSpecificData, helpers},
+ payments::{
+ self, callback_urls::ConnectorCallbackUrls, flows::ConstructFlowSpecificData, helpers,
+ },
},
errors, services,
types::{
@@ -35,6 +37,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
todo!()
}
@@ -51,6 +54,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
let status = storage_enums::AttemptStatus::Pending;
diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
index 8528189919..4ad13846af 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -6,7 +6,9 @@ use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FrmData},
- payments::{self, flows::ConstructFlowSpecificData, helpers},
+ payments::{
+ self, callback_urls::ConnectorCallbackUrls, flows::ConstructFlowSpecificData, helpers,
+ },
},
errors, services,
types::{
@@ -39,6 +41,7 @@ impl
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
@@ -57,6 +60,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 4451eccf2e..a7b76299e0 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1,5 +1,6 @@
use hyperswitch_domain_models::mandates;
pub mod access_token;
+pub mod callback_urls;
pub mod conditional_configs;
pub mod customers;
#[cfg(feature = "olap")]
@@ -157,7 +158,13 @@ use crate::{
},
db::StorageInterface,
logger,
- routes::{app::ReqState, metrics, payment_methods::ParentPaymentMethodToken, SessionState},
+ routes::{
+ app::ReqState,
+ metrics,
+ payment_methods::ParentPaymentMethodToken,
+ payments::callback_routes::{ConnectorCallbackPath, PaymentCallbackRoute},
+ SessionState,
+ },
services::{self, api::Authenticate, ConnectorRedirectResponse},
types::{
self as router_types,
@@ -3214,17 +3221,17 @@ where
)
.await?;
- Res::generate_response(
+ Res::generate_response_with_callbacks(
+ &state,
payment_data,
auth_flow,
- &state.base_url,
operation,
- &state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&platform,
)
+ .await
}
#[cfg(feature = "v1")]
@@ -3278,17 +3285,17 @@ where
)
.await?;
- Res::generate_response(
+ Res::generate_response_with_callbacks(
+ &state,
payment_data,
auth_flow,
- &state.base_url,
operation,
- &state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&platform,
)
+ .await
}
#[cfg(feature = "v1")]
@@ -3772,7 +3779,7 @@ where
));
let router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
platform.get_processor(),
@@ -4023,17 +4030,17 @@ where
)
.await?;
- Res::generate_response(
+ Res::generate_response_with_callbacks(
+ &state,
payment_data,
auth_flow,
- &state.base_url,
operation,
- &state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&platform,
)
+ .await
}
/// Whether the profile that ran the network token arm has clear-PAN retries enabled. An
@@ -4612,17 +4619,17 @@ where
)
.await?;
- Res::generate_response(
+ Res::generate_response_with_callbacks(
+ &state,
payment_data,
customer,
- &state.base_url,
operation,
- &state.conf.connector_request_reference_id_config,
None,
None,
header_payload.x_hs_latency,
&platform,
)
+ .await
}
#[cfg(feature = "v2")]
@@ -4656,17 +4663,17 @@ where
)
.await?;
- Res::generate_response(
+ Res::generate_response_with_callbacks(
+ &state,
payment_data,
customer,
- &state.base_url,
operation,
- &state.conf.connector_request_reference_id_config,
None,
None,
header_payload.x_hs_latency,
&platform,
)
+ .await
}
#[cfg(all(feature = "v2", feature = "olap"))]
@@ -4815,21 +4822,21 @@ pub async fn payments_get_intent_using_merchant_reference(
))
.await?;
- transformers::ToResponse::<
+ <api::PaymentsIntentResponse as transformers::ToResponse<
api::PaymentGetIntent,
PaymentIntentData<api::PaymentGetIntent>,
operations::PaymentGetIntent,
- >::generate_response(
+ >>::generate_response_with_callbacks(
+ &state,
payment_data,
customer,
- &state.base_url,
operations::PaymentGetIntent,
- &state.conf.connector_request_reference_id_config,
None,
None,
header_payload.x_hs_latency,
&platform,
)
+ .await
}
#[cfg(feature = "v2")]
@@ -5493,6 +5500,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
)?;
return Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
+ callback_url: None,
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
@@ -5511,6 +5519,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
)?;
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
+ callback_url: None,
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
@@ -5639,6 +5648,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync {
)?;
return Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
+ callback_url: None,
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
@@ -5657,6 +5667,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync {
)?;
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
+ callback_url: None,
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
@@ -5828,7 +5839,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync {
Ok(services::ApplicationResponse::JsonForRedirection(
api::RedirectionResponse {
- return_url_with_query_params: return_url_str,
+ return_url_with_query_params: return_url_str.into(),
},
))
}
@@ -6207,6 +6218,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
)?;
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
+ callback_url: None,
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
@@ -7007,7 +7019,7 @@ where
.await?;
let router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
platform.get_processor(),
@@ -7435,7 +7447,7 @@ where
.await?;
let router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
platform.get_processor(),
@@ -7600,7 +7612,7 @@ where
.await?;
let router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
platform.get_processor(),
@@ -7644,7 +7656,7 @@ where
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let mut router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
platform.get_processor(),
@@ -7993,7 +8005,7 @@ where
let merchant_recipient_data = None;
let mut router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
platform.get_processor(),
@@ -8201,7 +8213,7 @@ where
.await?;
let mut router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
platform.get_processor(),
@@ -8876,7 +8888,7 @@ where
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>,
- RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req>,
+ RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
// To construct connector flow specific api
dyn api::Connector:
@@ -8900,7 +8912,7 @@ where
let connector_id = session_connector_data.connector.connector.id();
let router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector_id,
processor,
@@ -9030,7 +9042,7 @@ where
));
let router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector_id,
processor,
@@ -9430,7 +9442,7 @@ where
customers::ConnectorCustomerAction::CreateCustomer => {
// Create customer at connector and update the customer table to store this data
let mut customer_router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
processor,
@@ -9545,7 +9557,7 @@ where
if should_call_connector {
// Create customer at connector and update the customer table to store this data
let router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
processor,
@@ -9675,7 +9687,7 @@ where
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
{
let mut router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
processor,
@@ -14161,11 +14173,19 @@ pub async fn payment_external_authentication<F: Clone + Sync>(
.as_ref()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing connector in payment_attempt")?;
- let return_url = Some(helpers::create_authorize_url(
- &state.base_url,
- &payment_attempt.clone(),
- payment_connector_name,
- ));
+ let return_url = Some(
+ PaymentCallbackRoute::authorize_url(
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_attempt.payment_id.clone(),
+ merchant_id: payment_attempt.processor_merchant_id.clone(),
+ connector: payment_connector_name.to_string(),
+ },
+ )
+ .persist(&state)
+ .await?,
+ );
let mca_id_option = merchant_connector_account.get_mca_id(); // Bind temporary value
let merchant_connector_account_id_or_connector_name = mca_id_option
.as_ref()
@@ -14454,8 +14474,30 @@ pub async fn payment_start_redirection(
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing authentication_data in payment_attempt")?;
+ let mut sdk_callback_urls = callback_urls::SdkCallbackUrls::default();
+ let connector_name = payment_attempt
+ .connector
+ .as_deref()
+ .get_required_value("connector")?;
+ let connector = api::ConnectorData::convert_connector(connector_name)?;
+ let callback_url = sdk_callback_urls
+ .redirection_form_callback_url(
+ connector.get_redirect_callback(&redirection_data),
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_attempt.payment_id.clone(),
+ merchant_id: payment_attempt.processor_merchant_id.clone(),
+ connector: connector.id().to_string(),
+ },
+ None,
+ )
+ .cloned();
+ sdk_callback_urls.persist(&state).await?;
+
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
+ callback_url,
redirect_form: redirection_data,
payment_method_data: None,
amount: payment_attempt.amount_details.get_net_amount().to_string(),
diff --git a/crates/router/src/core/payments/callback_urls.rs b/crates/router/src/core/payments/callback_urls.rs
new file mode 100644
index 0000000000..15215c575e
--- /dev/null
+++ b/crates/router/src/core/payments/callback_urls.rs
@@ -0,0 +1,328 @@
+//! Collection and persistence of payment callback URLs for connectors and the SDK.
+
+use hyperswitch_domain_models::router_response_types::RedirectCallback;
+use hyperswitch_masking::Secret;
+
+use crate::{
+ core::{configs::payment_callback::PaymentCallbackMode, errors::RouterResult},
+ routes::{
+ payments::{
+ callback_routes::{
+ CallbackPaymentId, ConnectorCallbackPath, ConnectorCallbackWithCredentialsPath,
+ PaymentCallbackRoute, StartCallbackPath,
+ },
+ callback_tokens::PaymentCallbackUrl,
+ },
+ SessionState,
+ },
+};
+
+/// Connector URLs created during router-data construction, pending token registration.
+#[derive(Clone, Default)]
+pub struct ConnectorCallbackUrls {
+ pub redirect_response: Option<PaymentCallbackUrl>,
+ pub redirect_complete: Option<PaymentCallbackUrl>,
+ pub notification: Option<PaymentCallbackUrl>,
+}
+
+/// SDK URLs returned by response generation, pending token registration.
+#[derive(Clone, Default)]
+pub struct SdkCallbackUrls {
+ pub start: Option<PaymentCallbackUrl>,
+ pub authorize: Option<PaymentCallbackUrl>,
+ pub redirect_response: Option<PaymentCallbackUrl>,
+ pub redirect_complete: Option<PaymentCallbackUrl>,
+}
+
+impl SdkCallbackUrls {
+ pub fn redirection_form_callback_url(
+ &mut self,
+ callback: Option<RedirectCallback>,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ path: &ConnectorCallbackPath,
+ creds_identifier: Option<&str>,
+ ) -> Option<&Secret<String>> {
+ Some(match callback? {
+ RedirectCallback::Response => self.redirect_response_url(
+ base_url,
+ callback_mode,
+ &path.payment_id,
+ &path.merchant_id,
+ &path.connector,
+ None,
+ ),
+ RedirectCallback::Complete => self.redirect_complete_url(
+ base_url,
+ callback_mode,
+ &path.payment_id,
+ &path.merchant_id,
+ &path.connector,
+ creds_identifier,
+ ),
+ })
+ }
+
+ pub fn start_url(
+ &mut self,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ payment_id: &CallbackPaymentId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ attempt_id: &str,
+ ) -> &Secret<String> {
+ self.start
+ .get_or_insert_with(|| {
+ PaymentCallbackRoute::start_url(
+ base_url,
+ callback_mode,
+ &StartCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ attempt_id: attempt_id.to_string(),
+ },
+ )
+ })
+ .url()
+ }
+
+ pub fn authorize_url(
+ &mut self,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ payment_id: &CallbackPaymentId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector: &str,
+ ) -> &Secret<String> {
+ self.authorize
+ .get_or_insert_with(|| {
+ PaymentCallbackRoute::authorize_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ },
+ )
+ })
+ .url()
+ }
+
+ pub fn redirect_response_url(
+ &mut self,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ payment_id: &CallbackPaymentId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector: &str,
+ creds_identifier: Option<&str>,
+ ) -> &Secret<String> {
+ self.redirect_response
+ .get_or_insert_with(|| match creds_identifier {
+ Some(creds) => PaymentCallbackRoute::redirect_response_with_credentials_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackWithCredentialsPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ creds_identifier: creds.to_string(),
+ },
+ ),
+ None => PaymentCallbackRoute::redirect_response_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ },
+ ),
+ })
+ .url()
+ }
+
+ pub fn redirect_complete_url(
+ &mut self,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ payment_id: &CallbackPaymentId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector: &str,
+ creds_identifier: Option<&str>,
+ ) -> &Secret<String> {
+ self.redirect_complete
+ .get_or_insert_with(|| match creds_identifier {
+ Some(creds) => PaymentCallbackRoute::redirect_complete_with_credentials_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackWithCredentialsPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ creds_identifier: creds.to_string(),
+ },
+ ),
+ None => PaymentCallbackRoute::redirect_complete_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ },
+ ),
+ })
+ .url()
+ }
+
+ pub async fn persist(self, state: &SessionState) -> RouterResult<()> {
+ let Self {
+ start,
+ authorize,
+ redirect_response,
+ redirect_complete,
+ } = self;
+
+ futures::future::try_join_all(
+ [start, authorize, redirect_response, redirect_complete]
+ .into_iter()
+ .flatten()
+ .map(|callback_url| callback_url.persist(state)),
+ )
+ .await?;
+ Ok(())
+ }
+}
+
+impl ConnectorCallbackUrls {
+ /// Notifications must not consume the token used by the customer's browser.
+ pub fn notification_url(
+ &mut self,
+ callback: Option<RedirectCallback>,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ path: &ConnectorCallbackPath,
+ creds_identifier: Option<&str>,
+ ) -> Option<Secret<String>> {
+ let callback = callback?;
+ let notification = self.notification.get_or_insert_with(|| {
+ let credentials_path =
+ creds_identifier.map(|creds| ConnectorCallbackWithCredentialsPath {
+ payment_id: path.payment_id.clone(),
+ merchant_id: path.merchant_id.clone(),
+ connector: path.connector.clone(),
+ creds_identifier: creds.to_string(),
+ });
+ match (callback, credentials_path.as_ref()) {
+ (RedirectCallback::Response, None) => {
+ PaymentCallbackRoute::redirect_response_url(base_url, callback_mode, path)
+ }
+ (RedirectCallback::Complete, None) => {
+ PaymentCallbackRoute::redirect_complete_url(base_url, callback_mode, path)
+ }
+ (RedirectCallback::Response, Some(path)) => {
+ PaymentCallbackRoute::redirect_response_with_credentials_url(
+ base_url,
+ callback_mode,
+ path,
+ )
+ }
+ (RedirectCallback::Complete, Some(path)) => {
+ PaymentCallbackRoute::redirect_complete_with_credentials_url(
+ base_url,
+ callback_mode,
+ path,
+ )
+ }
+ }
+ });
+ Some(notification.url().clone())
+ }
+
+ pub fn redirect_response_url(
+ &mut self,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ payment_id: &CallbackPaymentId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector: &str,
+ creds_identifier: Option<&str>,
+ ) -> &Secret<String> {
+ self.redirect_response
+ .get_or_insert_with(|| match creds_identifier {
+ Some(creds) => PaymentCallbackRoute::redirect_response_with_credentials_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackWithCredentialsPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ creds_identifier: creds.to_string(),
+ },
+ ),
+ None => PaymentCallbackRoute::redirect_response_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ },
+ ),
+ })
+ .url()
+ }
+
+ pub fn redirect_complete_url(
+ &mut self,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ payment_id: &CallbackPaymentId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector: &str,
+ creds_identifier: Option<&str>,
+ ) -> &Secret<String> {
+ self.redirect_complete
+ .get_or_insert_with(|| match creds_identifier {
+ Some(creds) => PaymentCallbackRoute::redirect_complete_with_credentials_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackWithCredentialsPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ creds_identifier: creds.to_string(),
+ },
+ ),
+ None => PaymentCallbackRoute::redirect_complete_url(
+ base_url,
+ callback_mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ },
+ ),
+ })
+ .url()
+ }
+
+ pub async fn persist(self, state: &SessionState) -> RouterResult<()> {
+ let Self {
+ redirect_response,
+ redirect_complete,
+ notification,
+ } = self;
+
+ futures::future::try_join_all(
+ [redirect_response, redirect_complete, notification]
+ .into_iter()
+ .flatten()
+ .map(|callback_url| callback_url.persist(state)),
+ )
+ .await?;
+ Ok(())
+ }
+}
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 1ce2ea684b..5beaa44a8d 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -32,6 +32,7 @@ use hyperswitch_domain_models::{
};
use payment_methods::single_use_token;
+use super::callback_urls::ConnectorCallbackUrls;
use crate::{
core::{
errors::{ApiErrorResponse, RouterResult},
@@ -46,6 +47,72 @@ use crate::{
#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait ConstructFlowSpecificData<F, Req, Res> {
+ #[cfg(feature = "v1")]
+ async fn construct_router_data_with_callbacks<'a>(
+ &self,
+ state: &SessionState,
+ connector_id: &str,
+ processor: &domain::Processor,
+ business_profile: &domain::Profile,
+ merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<domain_payments::HeaderPayload>,
+ payment_method: Option<common_enums::PaymentMethod>,
+ payment_method_type: Option<common_enums::PaymentMethodType>,
+ ) -> RouterResult<types::RouterData<F, Req, Res>>
+ where
+ types::RouterData<F, Req, Res>: Send,
+ {
+ let mut connector_callback_urls = ConnectorCallbackUrls::default();
+ let router_data = self
+ .construct_router_data(
+ state,
+ connector_id,
+ processor,
+ business_profile,
+ merchant_connector_account,
+ merchant_recipient_data,
+ header_payload,
+ payment_method,
+ payment_method_type,
+ &mut connector_callback_urls,
+ )
+ .await?;
+ connector_callback_urls.persist(state).await?;
+ Ok(router_data)
+ }
+
+ #[cfg(feature = "v2")]
+ async fn construct_router_data_with_callbacks<'a>(
+ &self,
+ state: &SessionState,
+ connector_id: &str,
+ processor: &domain::Processor,
+ customer: &Option<domain::Customer>,
+ merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<domain_payments::HeaderPayload>,
+ ) -> RouterResult<types::RouterData<F, Req, Res>>
+ where
+ types::RouterData<F, Req, Res>: Send,
+ {
+ let mut connector_callback_urls = ConnectorCallbackUrls::default();
+ let router_data = self
+ .construct_router_data(
+ state,
+ connector_id,
+ processor,
+ customer,
+ merchant_connector_account,
+ merchant_recipient_data,
+ header_payload,
+ &mut connector_callback_urls,
+ )
+ .await?;
+ connector_callback_urls.persist(state).await?;
+ Ok(router_data)
+ }
+
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
@@ -58,6 +125,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> {
header_payload: Option<domain_payments::HeaderPayload>,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::RouterData<F, Req, Res>>;
#[cfg(feature = "v2")]
@@ -70,6 +138,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> {
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<domain_payments::HeaderPayload>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::RouterData<F, Req, Res>>;
async fn get_merchant_recipient_data<'a>(
diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs
index 4234b52dd5..9326504b51 100644
--- a/crates/router/src/core/payments/flows/approve_flow.rs
+++ b/crates/router/src/core/payments/flows/approve_flow.rs
@@ -5,7 +5,8 @@ use crate::{
core::{
errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{
- self, access_token, flows::gateway_context, helpers, transformers, PaymentData,
+ self, access_token, callback_urls::ConnectorCallbackUrls, flows::gateway_context,
+ helpers, transformers, PaymentData,
},
},
routes::SessionState,
@@ -28,6 +29,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsApproveRouterData> {
todo!()
}
@@ -44,6 +46,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsApproveRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Approve,
@@ -59,6 +62,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 393df9cc44..a8ee8c75ba 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -22,7 +22,7 @@ use hyperswitch_interfaces::{
consts as interface_consts, errors as interface_errors,
unified_connector_service::transformers as ucs_transformers,
};
-use hyperswitch_masking::ExposeInterface;
+use hyperswitch_masking::{ExposeInterface, PeekInterface};
use payment_methods::single_use_token;
use unified_connector_service_client::payments as payments_grpc;
@@ -40,9 +40,9 @@ use crate::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
- self, access_token, customers, flows::gateway_context, gateway,
- gateway as payments_gateway, helpers, session_token, tokenization, transformers,
- PaymentData,
+ self, access_token, callback_urls::ConnectorCallbackUrls, customers,
+ flows::gateway_context, gateway, gateway as payments_gateway, helpers, session_token,
+ tokenization, transformers, PaymentData,
},
unified_connector_service,
},
@@ -71,6 +71,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<
api::Authorize,
@@ -87,6 +88,7 @@ impl
merchant_connector_account,
merchant_recipient_data,
header_payload,
+ connector_callback_urls,
))
.await
}
@@ -153,6 +155,7 @@ impl
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<
api::Authorize,
@@ -178,6 +181,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -1471,16 +1475,16 @@ fn transform_redirection_response_for_pre_authenticate_flow(
match connector {
enums::connector_enums::Connector::Barclaycard => {
Ok(router_response_types::RedirectForm::BarclaycardAuthSetup {
- access_token,
- ddc_url,
- reference_id,
+ access_token: access_token.expose(),
+ ddc_url: ddc_url.expose(),
+ reference_id: reference_id.expose(),
})
}
enums::connector_enums::Connector::Cybersource => {
Ok(router_response_types::RedirectForm::CybersourceAuthSetup {
- access_token,
- ddc_url,
- reference_id,
+ access_token: access_token.expose(),
+ ddc_url: ddc_url.expose(),
+ reference_id: reference_id.expose(),
})
}
_ => Ok(response_data),
@@ -1591,19 +1595,25 @@ fn transform_response_for_pre_authenticate_flow(
directory_server_id: form_fields
.get("threeDSServerTransID")
.cloned()
- .unwrap_or_default(),
+ .unwrap_or_default()
+ .expose(),
three_ds_method_url: form_fields
.get("threeDsMethodUrl")
.cloned()
- .unwrap_or_else(|| endpoint.clone()),
+ .unwrap_or_else(|| endpoint.clone())
+ .expose(),
three_ds_method_data: form_fields
.get("threeDsMethodData")
.cloned()
- .unwrap_or_default(),
- message_version: form_fields.get("messageVersion").cloned(),
+ .unwrap_or_default()
+ .expose(),
+ message_version: form_fields
+ .get("messageVersion")
+ .cloned()
+ .map(ExposeInterface::expose),
three_ds_method_data_submission: form_fields
.get("threeDsMethodDataSubmission")
- .map(|v| v == "true")
+ .map(|v| v.peek() == "true")
.unwrap_or(true),
};
// Set connector_metadata with invoke data, clear redirection_data
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index bee513a934..859d2ef3c9 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -5,7 +5,10 @@ use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ PaymentData,
+ },
},
routes::{metrics, SessionState},
services,
@@ -27,6 +30,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Void,
@@ -42,6 +46,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -60,6 +65,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_router_data_for_cancel(
state,
diff --git a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs
index 294e04a136..4a3f048b85 100644
--- a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs
@@ -5,7 +5,10 @@ use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ PaymentData,
+ },
},
routes::{metrics, SessionState},
services,
@@ -30,6 +33,7 @@ impl
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
todo!()
}
@@ -46,6 +50,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostCaptureVoid,
@@ -61,6 +66,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/cancel_post_capture_sync_flow.rs b/crates/router/src/core/payments/flows/cancel_post_capture_sync_flow.rs
index 6d5d43dec4..fb428ac9f4 100644
--- a/crates/router/src/core/payments/flows/cancel_post_capture_sync_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_post_capture_sync_flow.rs
@@ -5,7 +5,10 @@ use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ PaymentData,
+ },
},
routes::SessionState,
services,
@@ -30,6 +33,7 @@ impl
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsCancelPostCaptureSyncRouterData> {
todo!()
}
@@ -46,6 +50,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsCancelPostCaptureSyncRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostCaptureVoidSync,
@@ -61,6 +66,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs
index 39b5040739..d439cdee60 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -5,7 +5,10 @@ use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, Feature, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ Feature, PaymentData,
+ },
},
routes::SessionState,
services,
@@ -29,6 +32,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Capture,
@@ -44,6 +48,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -64,6 +69,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>,
> {
diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
index ab42ed0eb7..d4c5231fca 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -15,7 +15,7 @@ use hyperswitch_interfaces::{
api as api_interface, api::ConnectorSpecifications, consts as interface_consts,
errors as interface_errors, unified_connector_service::transformers as ucs_transformers,
};
-use hyperswitch_masking::{self, ExposeInterface};
+use hyperswitch_masking::{self, ExposeInterface, Secret};
use unified_connector_service_client::payments as payments_grpc;
use super::{ConstructFlowSpecificData, Feature};
@@ -23,8 +23,9 @@ use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{
- self, access_token, gateway, gateway as payments_gateway,
- gateway::context as gateway_context, helpers, transformers, PaymentData,
+ self, access_token, callback_urls::ConnectorCallbackUrls, gateway,
+ gateway as payments_gateway, gateway::context as gateway_context, helpers,
+ transformers, PaymentData,
},
unified_connector_service as ucs_core,
},
@@ -54,6 +55,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
@@ -75,6 +77,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -89,6 +92,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
@@ -681,14 +685,14 @@ fn transform_redirection_response_for_authenticate_flow(
match connector {
connector_enums::Connector::Barclaycard => Ok(
router_response_types::RedirectForm::BarclaycardConsumerAuth {
- access_token,
- step_up_url,
+ access_token: access_token.expose(),
+ step_up_url: step_up_url.expose(),
},
),
connector_enums::Connector::Cybersource => Ok(
router_response_types::RedirectForm::CybersourceConsumerAuth {
- access_token,
- step_up_url,
+ access_token: access_token.expose(),
+ step_up_url: step_up_url.expose(),
},
),
_ => Ok(response_data),
@@ -897,7 +901,7 @@ pub async fn call_unified_connector_service_authenticate_proxy(
processor: &domain::Processor,
rollout_settings: crate::core::unified_connector_service::kill_switch::RolloutSettings,
force_3ds_challenge: Option<bool>,
- notification_url: Option<common_utils::types::Url>,
+ notification_url: Option<Secret<common_utils::types::Url>>,
acquirer_metadata: Option<serde_json::Value>,
) -> errors::CustomResult<
types::RouterData<
diff --git a/crates/router/src/core/payments/flows/extend_authorization_flow.rs b/crates/router/src/core/payments/flows/extend_authorization_flow.rs
index 60a8fd3d3c..1c76a165a9 100644
--- a/crates/router/src/core/payments/flows/extend_authorization_flow.rs
+++ b/crates/router/src/core/payments/flows/extend_authorization_flow.rs
@@ -4,7 +4,10 @@ use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ PaymentData,
+ },
},
routes::{metrics, SessionState},
services,
@@ -29,6 +32,7 @@ impl
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsExtendAuthorizationRouterData> {
todo!()
}
@@ -45,6 +49,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsExtendAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::ExtendAuthorization,
@@ -60,6 +65,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs
index e350696159..b1288b6897 100644
--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs
+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs
@@ -18,8 +18,9 @@ use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{
- self, access_token, customers, gateway, gateway::context as gateway_context, helpers,
- session_token, tokenization, transformers, PaymentData,
+ self, access_token, callback_urls::ConnectorCallbackUrls, customers, gateway,
+ gateway::context as gateway_context, helpers, session_token, tokenization,
+ transformers, PaymentData,
},
unified_connector_service::{self, ucs_logging_wrapper},
},
@@ -49,6 +50,7 @@ impl
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::enums::PaymentMethod>,
_payment_method_type: Option<common_enums::enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<
api::ExternalVaultProxy,
@@ -65,6 +67,7 @@ impl
merchant_connector_account,
merchant_recipient_data,
header_payload,
+ connector_callback_urls,
),
)
.await
@@ -89,6 +92,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<
api::ExternalVaultProxy,
@@ -106,6 +110,7 @@ impl
merchant_connector_account,
merchant_recipient_data,
header_payload,
+ connector_callback_urls,
),
)
.await
diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
index f0950ebeb7..73da82ef0b 100644
--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
@@ -5,7 +5,10 @@ use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, Feature, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ Feature, PaymentData,
+ },
},
routes::SessionState,
services,
@@ -32,6 +35,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::IncrementalAuthorization,
@@ -47,6 +51,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -61,6 +66,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
todo!()
}
diff --git a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs
index 7609e885e6..3117096a82 100644
--- a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs
+++ b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs
@@ -4,7 +4,10 @@ use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, Feature, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ Feature, PaymentData,
+ },
},
routes::SessionState,
services,
@@ -31,6 +34,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsPostSessionTokensRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostSessionTokens,
@@ -46,6 +50,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -60,6 +65,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsPostSessionTokensRouterData> {
todo!()
}
diff --git a/crates/router/src/core/payments/flows/pre_authorize_void_flow.rs b/crates/router/src/core/payments/flows/pre_authorize_void_flow.rs
index eabfa831f6..10a94814ee 100644
--- a/crates/router/src/core/payments/flows/pre_authorize_void_flow.rs
+++ b/crates/router/src/core/payments/flows/pre_authorize_void_flow.rs
@@ -5,7 +5,10 @@ use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ PaymentData,
+ },
},
routes::{metrics, SessionState},
services,
@@ -32,6 +35,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsPreAuthorizeVoidRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PreAuthorizeVoid,
@@ -47,6 +51,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index eff22f71a1..be901f728d 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -9,7 +9,10 @@ use crate::{
connector::utils::RouterData,
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
- payments::{self, access_token, gateway, helpers, transformers, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, gateway, helpers,
+ transformers, PaymentData,
+ },
},
routes::SessionState,
services::{self, api::ConnectorValidation, logger},
@@ -32,6 +35,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
@@ -49,6 +53,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -68,6 +73,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs
index 04cf2fed4b..603d76f3d4 100644
--- a/crates/router/src/core/payments/flows/reject_flow.rs
+++ b/crates/router/src/core/payments/flows/reject_flow.rs
@@ -4,7 +4,10 @@ use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
- payments::{self, access_token, helpers, transformers, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ PaymentData,
+ },
},
routes::SessionState,
services,
@@ -27,6 +30,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsRejectRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Reject,
@@ -42,6 +46,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -56,6 +61,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsRejectRouterData> {
todo!()
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index fc5a6394cf..b0804d01ef 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -21,7 +21,9 @@ use crate::{
configs::dimension_state,
errors::{self, ConnectorErrorExt, RouterResult},
payments::{
- self, access_token, customers, gateway,
+ self, access_token,
+ callback_urls::ConnectorCallbackUrls,
+ customers, gateway,
gateway::context as gateway_context,
helpers::{self},
transformers, PaymentData,
@@ -53,6 +55,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data_for_sdk_session(
state,
@@ -85,6 +88,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsSessionRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
@@ -104,6 +108,7 @@ impl
header_payload,
payment_method,
payment_method_type,
+ connector_callback_urls,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/session_update_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rs
index 73b55b80a7..619db3b1d3 100644
--- a/crates/router/src/core/payments/flows/session_update_flow.rs
+++ b/crates/router/src/core/payments/flows/session_update_flow.rs
@@ -4,7 +4,10 @@ use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, Feature, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ Feature, PaymentData,
+ },
},
routes::SessionState,
services,
@@ -31,6 +34,7 @@ impl
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
Box::pin(
transformers::construct_router_data_to_update_calculated_tax::<
@@ -42,6 +46,7 @@ impl
connector_id,
processor,
merchant_connector_account,
+ connector_callback_urls,
),
)
.await
@@ -57,6 +62,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
todo!()
}
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index 5aff546473..e68b67cb09 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -21,9 +21,9 @@ use crate::{
errors::{self, ConnectorErrorExt, RouterResult},
mandate,
payments::{
- self, access_token, customers, gateway, gateway as payments_gateway,
- gateway::context as gateway_context, helpers, session_token, tokenization,
- transformers, PaymentData,
+ self, access_token, callback_urls::ConnectorCallbackUrls, customers, gateway,
+ gateway as payments_gateway, gateway::context as gateway_context, helpers,
+ session_token, tokenization, transformers, PaymentData,
},
},
routes::SessionState,
@@ -51,6 +51,7 @@ impl
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::SetupMandateRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
@@ -70,6 +71,7 @@ impl
header_payload,
None,
None,
+ connector_callback_urls,
))
.await
}
@@ -93,6 +95,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_setup_mandate(
@@ -104,6 +107,7 @@ impl
merchant_connector_account,
merchant_recipient_data,
header_payload,
+ connector_callback_urls,
),
)
.await
diff --git a/crates/router/src/core/payments/flows/update_metadata_flow.rs b/crates/router/src/core/payments/flows/update_metadata_flow.rs
index 879df1dcc0..4dc8934d15 100644
--- a/crates/router/src/core/payments/flows/update_metadata_flow.rs
+++ b/crates/router/src/core/payments/flows/update_metadata_flow.rs
@@ -4,7 +4,10 @@ use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, Feature, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ Feature, PaymentData,
+ },
},
routes::SessionState,
services,
@@ -31,6 +34,7 @@ impl
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsUpdateMetadataRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_update_metadata(
@@ -42,6 +46,7 @@ impl
merchant_connector_account,
merchant_recipient_data,
header_payload,
+ connector_callback_urls,
),
)
.await
@@ -57,6 +62,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsUpdateMetadataRouterData> {
todo!()
}
diff --git a/crates/router/src/core/payments/flows/update_post_confirm_flow.rs b/crates/router/src/core/payments/flows/update_post_confirm_flow.rs
index b37f46bb97..3190ab848e 100644
--- a/crates/router/src/core/payments/flows/update_post_confirm_flow.rs
+++ b/crates/router/src/core/payments/flows/update_post_confirm_flow.rs
@@ -5,7 +5,10 @@ use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- payments::{self, access_token, helpers, transformers, Feature, PaymentData},
+ payments::{
+ self, access_token, callback_urls::ConnectorCallbackUrls, helpers, transformers,
+ Feature, PaymentData,
+ },
},
routes::SessionState,
services,
@@ -32,6 +35,7 @@ impl
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsUpdatePostConfirmRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_update_post_confirm(
@@ -40,6 +44,7 @@ impl
connector_id,
processor,
merchant_connector_account,
+ connector_callback_urls,
),
)
.await
@@ -55,6 +60,7 @@ impl
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _connector_callback_urls: &mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsUpdatePostConfirmRouterData> {
todo!()
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 1b7389d795..96ad89c795 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1391,61 +1391,6 @@ pub fn validate_customer_id_mandatory_cases(
}
}
-#[cfg(feature = "v1")]
-pub fn create_startpay_url(
- base_url: &str,
- payment_attempt: &PaymentAttempt,
- payment_intent: &PaymentIntent,
-) -> String {
- format!(
- "{}/payments/redirect/{}/{}/{}",
- base_url,
- payment_intent.get_id().get_string_repr(),
- payment_intent.processor_merchant_id.get_string_repr(),
- payment_attempt.attempt_id
- )
-}
-
-pub fn create_redirect_url(
- router_base_url: &String,
- payment_attempt: &PaymentAttempt,
- connector_name: impl std::fmt::Display,
- creds_identifier: Option<&str>,
-) -> String {
- let creds_identifier_path = creds_identifier.map_or_else(String::new, |cd| format!("/{cd}"));
- format!(
- "{}/payments/{}/{}/redirect/response/{}",
- router_base_url,
- payment_attempt.payment_id.get_string_repr(),
- payment_attempt.processor_merchant_id.get_string_repr(),
- connector_name,
- ) + creds_identifier_path.as_ref()
-}
-
-pub fn create_authentication_url(
- router_base_url: &str,
- payment_attempt: &PaymentAttempt,
-) -> String {
- format!(
- "{router_base_url}/payments/{}/3ds/authentication",
- payment_attempt.payment_id.get_string_repr()
- )
-}
-
-pub fn create_authorize_url(
- router_base_url: &str,
- payment_attempt: &PaymentAttempt,
- connector_name: impl std::fmt::Display,
-) -> String {
- format!(
- "{}/payments/{}/{}/authorize/{}",
- router_base_url,
- payment_attempt.payment_id.get_string_repr(),
- payment_attempt.processor_merchant_id.get_string_repr(),
- connector_name
- )
-}
-
pub fn create_webhook_url(
router_base_url: &str,
merchant_id: &id_type::MerchantId,
@@ -1459,25 +1404,6 @@ pub fn create_webhook_url(
)
}
-pub fn create_complete_authorize_url(
- router_base_url: &String,
- payment_attempt: &PaymentAttempt,
- connector_name: impl std::fmt::Display,
- creds_identifier: Option<&str>,
-) -> String {
- let creds_identifier = creds_identifier.map_or_else(String::new, |creds_identifier| {
- format!("/{creds_identifier}")
- });
- format!(
- "{}/payments/{}/{}/redirect/complete/{}{}",
- router_base_url,
- payment_attempt.payment_id.get_string_repr(),
- payment_attempt.processor_merchant_id.get_string_repr(),
- connector_name,
- creds_identifier
- )
-}
-
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
let recurring_details = req
.recurring_details
@@ -4496,7 +4422,7 @@ pub fn get_handle_response_url_for_modular_authentication(
business_profile: &domain::Profile,
response: &api_models::authentication::AuthenticationAuthenticateResponse,
connector: String,
- return_url: Option<String>,
+ return_url: Option<hyperswitch_masking::Secret<String>>,
client_secret: Option<&hyperswitch_masking::Secret<String>>,
amount: Option<MinorUnit>,
) -> RouterResult<api::RedirectionResponse> {
@@ -4516,7 +4442,7 @@ pub fn get_handle_response_url_for_modular_authentication(
let return_url = make_merchant_url_with_response_for_authentication(
business_profile,
redirection_response,
- authentication_return_url.as_ref(),
+ authentication_return_url.as_ref().map(PeekInterface::peek),
client_secret,
None,
)
@@ -4810,13 +4736,13 @@ pub fn make_url_with_signature(
.query_pairs()
.collect::<Vec<_>>()
.iter()
- .map(|(key, value)| (key.clone().into_owned(), value.clone().into_owned()))
+ .map(|(key, value)| (key.clone().into_owned(), value.clone().into_owned().into()))
.collect::<Vec<_>>();
Ok(api::RedirectionResponse {
return_url: base_url.to_string(),
params: parameters,
- return_url_with_query_params: url.to_string(),
+ return_url_with_query_params: url.to_string().into(),
http_method: if business_profile.redirect_to_merchant_with_http_post {
services::Method::Post.to_string()
} else {
@@ -4938,61 +4864,6 @@ pub fn generate_mandate(
}
}
-#[cfg(test)]
-mod generate_mandate_tests {
- use std::borrow::Cow;
-
- use common_types::payments::{AcceptanceType, CustomerAcceptance};
- use common_utils::{id_type, types::MinorUnit};
- use hyperswitch_domain_models::mandates::{MandateAmountData, MandateData, MandateDataType};
-
- use super::generate_mandate;
-
- /// A new mandate sets its own `created_at` rather than taking the database default.
- #[test]
- fn a_new_mandate_carries_its_own_created_at() {
- let mandate_data = MandateData {
- update_mandate_id: None,
- customer_acceptance: Some(CustomerAcceptance {
- acceptance_type: AcceptanceType::Offline,
- accepted_at: None,
- online: None,
- }),
- mandate_type: Some(MandateDataType::SingleUse(MandateAmountData {
- amount: MinorUnit::new(100),
- currency: common_enums::Currency::USD,
- start_date: None,
- end_date: None,
- metadata: None,
- })),
- };
- let customer_id = Some(id_type::CustomerId::try_from(Cow::Borrowed("cus_1")).unwrap());
-
- let before = common_utils::date_time::now();
- let mandate = generate_mandate(
- id_type::MerchantId::default(),
- id_type::PaymentId::try_from(Cow::Borrowed("pay_1")).unwrap(),
- "stripe".to_owned(),
- Some(mandate_data),
- &customer_id,
- "pm_1".to_owned(),
- None,
- None,
- None,
- None,
- None,
- None,
- )
- .unwrap()
- .expect("a mandate for mandate data and a customer");
-
- let after = common_utils::date_time::now();
-
- let created_at = mandate.created_at.expect("created_at is set");
- assert!(before <= created_at && created_at <= after, "{created_at}");
- }
-}
-
#[cfg(feature = "v1")]
// A function to manually authenticate the client secret with intent fulfillment time
pub fn authenticate_client_secret(
@@ -5195,316 +5066,8 @@ pub(crate) fn get_payment_id_from_client_secret(cs: &str) -> RouterResult<String
Ok(payment_id.to_string())
}
-#[cfg(feature = "v1")]
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_authenticate_client_secret_session_not_expired() {
- let payment_intent = PaymentIntent {
- payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
- merchant_id: id_type::MerchantId::default(),
- status: storage_enums::IntentStatus::RequiresCapture,
- amount: MinorUnit::new(200),
- currency: None,
- amount_captured: None,
- customer_id: None,
- description: None,
- return_url: None,
- metadata: None,
- connector_id: None,
- shipping_address_id: None,
- billing_address_id: None,
- mit_category: None,
- tokenization: None,
- statement_descriptor_name: None,
- statement_descriptor_suffix: None,
- created_at: common_utils::date_time::now(),
- modified_at: common_utils::date_time::now(),
- last_synced: None,
- setup_future_usage: None,
- fingerprint_id: None,
- off_session: None,
- client_secret: Some("1".to_string()),
- active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
- "nopes".to_string(),
- ),
- business_country: None,
- business_label: None,
- order_details: None,
- allowed_payment_method_types: None,
- connector_metadata: None,
- feature_metadata: None,
- attempt_count: 1,
- payment_link_id: None,
- profile_id: Some(common_utils::generate_profile_id_of_default_length()),
- merchant_decision: None,
- payment_confirm_source: None,
- surcharge_applicable: None,
- updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
- request_incremental_authorization: Some(
- common_enums::RequestIncrementalAuthorization::default(),
- ),
- incremental_authorization_allowed: None,
- authorization_count: None,
- session_expiry: Some(
- common_utils::date_time::now()
- .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
- ),
- request_external_three_ds_authentication: None,
- split_payments: None,
- frm_metadata: None,
- customer_details: None,
- billing_details: None,
- merchant_order_reference_id: None,
- shipping_details: None,
- is_payment_processor_token_flow: None,
- organization_id: id_type::OrganizationId::default(),
- shipping_cost: None,
- tax_details: None,
- skip_external_tax_calculation: None,
- request_extended_authorization: None,
- psd2_sca_exemption_type: None,
- processor_merchant_id: id_type::MerchantId::default(),
- created_by: None,
- force_3ds_challenge: None,
- force_3ds_challenge_trigger: None,
- is_iframe_redirection_enabled: None,
- is_payment_id_from_merchant: None,
- payment_channel: None,
- tax_status: None,
- discount_amount: None,
- order_date: None,
- shipping_amount_tax: None,
- value_added_tax_amount: None,
- value_added_tax_percent: None,
- vat_invoice_reference_number: None,
- order_commodity_code: None,
- duty_amount: None,
- enable_partial_authorization: None,
- enable_overcapture: None,
- billing_descriptor: None,
- is_account_funded_transaction: None,
- recipient_details: None,
- partner_merchant_identifier_details: None,
- state_metadata: None,
- installment_options: None,
- profile_acquirer_id: None,
- external_surcharge_strategy: None,
- external_surcharge_applicable: None,
- enable_avs_check: None,
- settlement_conclusion_applied: None,
- enable_account_name_verification: None,
- };
- let req_cs = Some("1".to_string());
- assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
- // Check if the result is an Ok variant
- }
-
- #[test]
- fn test_authenticate_client_secret_session_expired() {
- let created_at =
- common_utils::date_time::now().saturating_sub(time::Duration::seconds(20 * 60));
- let payment_intent = PaymentIntent {
- payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
- merchant_id: id_type::MerchantId::default(),
- status: storage_enums::IntentStatus::RequiresCapture,
- amount: MinorUnit::new(200),
- currency: None,
- amount_captured: None,
- customer_id: None,
- description: None,
- return_url: None,
- metadata: None,
- connector_id: None,
- shipping_address_id: None,
- mit_category: None,
- billing_address_id: None,
- statement_descriptor_name: None,
- statement_descriptor_suffix: None,
- created_at,
- modified_at: common_utils::date_time::now(),
- fingerprint_id: None,
- last_synced: None,
- setup_future_usage: None,
- off_session: None,
- client_secret: Some("1".to_string()),
- active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
- "nopes".to_string(),
- ),
- business_country: None,
- business_label: None,
- order_details: None,
- allowed_payment_method_types: None,
- connector_metadata: None,
- feature_metadata: None,
- attempt_count: 1,
- payment_link_id: None,
- profile_id: Some(common_utils::generate_profile_id_of_default_length()),
- merchant_decision: None,
- payment_confirm_source: None,
- surcharge_applicable: None,
- updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
- request_incremental_authorization: Some(
- common_enums::RequestIncrementalAuthorization::default(),
- ),
- incremental_authorization_allowed: None,
- authorization_count: None,
- session_expiry: Some(
- created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
- ),
- request_external_three_ds_authentication: None,
- split_payments: None,
- frm_metadata: None,
- customer_details: None,
- billing_details: None,
- merchant_order_reference_id: None,
- shipping_details: None,
- is_payment_processor_token_flow: None,
- organization_id: id_type::OrganizationId::default(),
- shipping_cost: None,
- tax_details: None,
- skip_external_tax_calculation: None,
- request_extended_authorization: None,
- psd2_sca_exemption_type: None,
- processor_merchant_id: id_type::MerchantId::default(),
- created_by: None,
- force_3ds_challenge: None,
- force_3ds_challenge_trigger: None,
- is_iframe_redirection_enabled: None,
- is_payment_id_from_merchant: None,
- payment_channel: None,
- tax_status: None,
- discount_amount: None,
- order_date: None,
- shipping_amount_tax: None,
- value_added_tax_amount: None,
- value_added_tax_percent: None,
- vat_invoice_reference_number: None,
- order_commodity_code: None,
- duty_amount: None,
- enable_partial_authorization: None,
- enable_overcapture: None,
- billing_descriptor: None,
- is_account_funded_transaction: None,
- recipient_details: None,
- tokenization: None,
- partner_merchant_identifier_details: None,
- state_metadata: None,
- installment_options: None,
- profile_acquirer_id: None,
- external_surcharge_strategy: None,
- external_surcharge_applicable: None,
- enable_avs_check: None,
- settlement_conclusion_applied: None,
- enable_account_name_verification: None,
- };
- let req_cs = Some("1".to_string());
- assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
- }
-
- #[test]
- fn test_authenticate_client_secret_expired() {
- let payment_intent = PaymentIntent {
- payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
- merchant_id: id_type::MerchantId::default(),
- status: storage_enums::IntentStatus::RequiresCapture,
- amount: MinorUnit::new(200),
- currency: None,
- amount_captured: None,
- customer_id: None,
- description: None,
- return_url: None,
- metadata: None,
- connector_id: None,
- mit_category: None,
- tokenization: None,
- shipping_address_id: None,
- billing_address_id: None,
- statement_descriptor_name: None,
- statement_descriptor_suffix: None,
- created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)),
- modified_at: common_utils::date_time::now(),
- last_synced: None,
- setup_future_usage: None,
- off_session: None,
- client_secret: None,
- fingerprint_id: None,
- active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
- "nopes".to_string(),
- ),
- business_country: None,
- business_label: None,
- order_details: None,
- allowed_payment_method_types: None,
- connector_metadata: None,
- feature_metadata: None,
- attempt_count: 1,
- payment_link_id: None,
- profile_id: Some(common_utils::generate_profile_id_of_default_length()),
- merchant_decision: None,
- payment_confirm_source: None,
- surcharge_applicable: None,
- updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
- request_incremental_authorization: Some(
- common_enums::RequestIncrementalAuthorization::default(),
- ),
- incremental_authorization_allowed: None,
- authorization_count: None,
- session_expiry: Some(
- common_utils::date_time::now()
- .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
- ),
- request_external_three_ds_authentication: None,
- split_payments: None,
- frm_metadata: None,
- customer_details: None,
- billing_details: None,
- merchant_order_reference_id: None,
- shipping_details: None,
- is_payment_processor_token_flow: None,
- organization_id: id_type::OrganizationId::default(),
- shipping_cost: None,
- tax_details: None,
- skip_external_tax_calculation: None,
- request_extended_authorization: None,
- psd2_sca_exemption_type: None,
- processor_merchant_id: id_type::MerchantId::default(),
- created_by: None,
- force_3ds_challenge: None,
- force_3ds_challenge_trigger: None,
- is_iframe_redirection_enabled: None,
- is_payment_id_from_merchant: None,
- payment_channel: None,
- tax_status: None,
- discount_amount: None,
- order_date: None,
- shipping_amount_tax: None,
- value_added_tax_amount: None,
- value_added_tax_percent: None,
- vat_invoice_reference_number: None,
- order_commodity_code: None,
- duty_amount: None,
- enable_partial_authorization: None,
- enable_overcapture: None,
- billing_descriptor: None,
- is_account_funded_transaction: None,
- recipient_details: None,
- partner_merchant_identifier_details: None,
- state_metadata: None,
- installment_options: None,
- profile_acquirer_id: None,
- external_surcharge_strategy: None,
- external_surcharge_applicable: None,
- enable_avs_check: None,
- settlement_conclusion_applied: None,
- enable_account_name_verification: None,
- };
- let req_cs = Some("1".to_string());
- assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
- }
-}
+mod tests;
// This function will be removed after moving this functionality to server_wrap and using cache instead of config
#[instrument(skip_all)]
@@ -6256,30 +5819,6 @@ pub fn is_manual_retry_allowed(
.map(|payment_status_check| payment_status_check && is_merchant_id_enabled_for_retries)
}
-#[cfg(test)]
-mod test {
- #[test]
- fn test_client_secret_parse() {
- let client_secret1 = "pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr";
- let client_secret2 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr";
- let client_secret3 =
- "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr";
-
- assert_eq!(
- "pay_3TgelAms4RQec8xSStjF",
- super::get_payment_id_from_client_secret(client_secret1).unwrap()
- );
- assert_eq!(
- "pay_3Tgel__Ams4RQ_secret_ec8xSStjF",
- super::get_payment_id_from_client_secret(client_secret2).unwrap()
- );
- assert_eq!(
- "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_",
- super::get_payment_id_from_client_secret(client_secret3).unwrap()
- );
- }
-}
-
#[instrument(skip_all)]
pub async fn get_additional_payment_data(
pm_data: &domain::PaymentMethodData,
@@ -10485,107 +10024,3 @@ pub fn update_request_data_with_mandate_id(
}
}
}
-
-#[cfg(test)]
-mod connector_response_card_merge_tests {
- use hyperswitch_domain_models::router_data::AdditionalPaymentMethodConnectorResponse;
-
- use super::add_connector_response_to_additional_payment_data;
-
- /// A connector that reports every card attribute it can, as Worldpay does when `<cardBin>` is
- /// enabled on the account.
- fn connector_card_response() -> AdditionalPaymentMethodConnectorResponse {
- AdditionalPaymentMethodConnectorResponse::Card {
- authentication_data: None,
- payment_checks: None,
- card_network: None,
- domestic_network: None,
- auth_code: Some("123456".to_string()),
- processor_card_network: Some(common_enums::CardNetwork::Visa),
- card_subtype: Some("ELECTRON".to_string()),
- card_segment_type: Some(common_enums::CardSegmentType::Commercial),
- funding_source: Some(common_enums::FundingSource::Debit),
- card_type: Some(common_enums::CardType::Debit),
- issuer_name: Some("CONNECTOR ISSUER".to_string()),
- issuer_country: Some(common_enums::CountryAlpha2::GB),
- }
- }
-
- fn merge(
- additional_card_info: api_models::payments::AdditionalCardInfo,
- ) -> api_models::payments::AdditionalCardInfo {
- let merged = add_connector_response_to_additional_payment_data(
- api_models::payments::AdditionalPaymentData::Card(Box::new(additional_card_info)),
- connector_card_response(),
- );
-
- match merged {
- api_models::payments::AdditionalPaymentData::Card(card) => *card,
- other => panic!("expected card additional payment data, got {other:?}"),
- }
- }
-
- #[test]
- fn connector_card_attributes_fill_an_empty_card_record() {
- let card = merge(api_models::payments::AdditionalCardInfo {
- card_isin: Some("444433".to_string()),
- ..Default::default()
- });
-
- assert_eq!(card.card_issuer.as_deref(), Some("CONNECTOR ISSUER"));
- assert_eq!(card.card_type.as_deref(), Some("DEBIT"));
- assert_eq!(card.card_subtype.as_deref(), Some("ELECTRON"));
- assert_eq!(
- card.card_segment_type,
- Some(common_enums::CardSegmentType::Commercial)
- );
- assert_eq!(
- card.funding_source,
- Some(common_enums::FundingSource::Debit)
- );
- assert_eq!(card.card_issuing_country.as_deref(), Some("GB"));
- assert_eq!(card.card_issuing_country_code.as_deref(), Some("GB"));
- assert_eq!(card.card_network, Some(common_enums::CardNetwork::Visa));
- assert_eq!(card.auth_code.as_deref(), Some("123456"));
- assert_eq!(card.card_isin.as_deref(), Some("444433"));
- }
-
- #[test]
- fn resolved_values_win_and_the_connector_only_fills_the_gaps() {
- let card = merge(api_models::payments::AdditionalCardInfo {
- card_issuer: Some("CURATED ISSUER".to_string()),
- card_type: Some("CREDIT".to_string()),
- card_issuing_country: Some("IN".to_string()),
- ..Default::default()
- });
-
- assert_eq!(card.card_issuer.as_deref(), Some("CURATED ISSUER"));
- assert_eq!(card.card_type.as_deref(), Some("CREDIT"));
- assert_eq!(card.card_issuing_country.as_deref(), Some("IN"));
- // The columns the BIN record left null are filled from the connector rather than staying
- // empty, which is the case that matters for BINs whose subtype is not recorded.
- assert_eq!(card.card_subtype.as_deref(), Some("ELECTRON"));
- assert_eq!(
- card.funding_source,
- Some(common_enums::FundingSource::Debit)
- );
- assert_eq!(
- card.card_segment_type,
- Some(common_enums::CardSegmentType::Commercial)
- );
- assert_eq!(card.auth_code.as_deref(), Some("123456"));
- }
-
- #[test]
- fn a_cobadge_resolved_network_is_not_overwritten() {
- let card = merge(api_models::payments::AdditionalCardInfo {
- card_network: Some(common_enums::CardNetwork::RuPay),
- ..Default::default()
- });
-
- // Debit routing selects the rail the payment authorizes on, so the connector's plain scheme
- // network must not replace it.
- assert_eq!(card.card_network, Some(common_enums::CardNetwork::RuPay));
- assert_eq!(card.card_issuer.as_deref(), Some("CONNECTOR ISSUER"));
- }
-}
diff --git a/crates/router/src/core/payments/helpers/tests.rs b/crates/router/src/core/payments/helpers/tests.rs
new file mode 100644
index 0000000000..442f56ff8c
--- /dev/null
+++ b/crates/router/src/core/payments/helpers/tests.rs
@@ -0,0 +1,5 @@
+mod client_secret;
+#[cfg(feature = "v1")]
+mod client_secret_session;
+mod connector_response_card_merge;
+mod generate_mandate;
diff --git a/crates/router/src/core/payments/helpers/tests/client_secret.rs b/crates/router/src/core/payments/helpers/tests/client_secret.rs
new file mode 100644
index 0000000000..654a20e998
--- /dev/null
+++ b/crates/router/src/core/payments/helpers/tests/client_secret.rs
@@ -0,0 +1,19 @@
+#[test]
+fn test_client_secret_parse() {
+ let client_secret1 = "pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr";
+ let client_secret2 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr";
+ let client_secret3 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr";
+
+ assert_eq!(
+ "pay_3TgelAms4RQec8xSStjF",
+ super::super::get_payment_id_from_client_secret(client_secret1).unwrap()
+ );
+ assert_eq!(
+ "pay_3Tgel__Ams4RQ_secret_ec8xSStjF",
+ super::super::get_payment_id_from_client_secret(client_secret2).unwrap()
+ );
+ assert_eq!(
+ "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_",
+ super::super::get_payment_id_from_client_secret(client_secret3).unwrap()
+ );
+}
diff --git a/crates/router/src/core/payments/helpers/tests/client_secret_session.rs b/crates/router/src/core/payments/helpers/tests/client_secret_session.rs
new file mode 100644
index 0000000000..ebaa3d1a20
--- /dev/null
+++ b/crates/router/src/core/payments/helpers/tests/client_secret_session.rs
@@ -0,0 +1,306 @@
+use super::super::*;
+
+#[test]
+fn test_authenticate_client_secret_session_not_expired() {
+ let payment_intent = PaymentIntent {
+ payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
+ merchant_id: id_type::MerchantId::default(),
+ status: storage_enums::IntentStatus::RequiresCapture,
+ amount: MinorUnit::new(200),
+ currency: None,
+ amount_captured: None,
+ customer_id: None,
+ description: None,
+ return_url: None,
+ metadata: None,
+ connector_id: None,
+ shipping_address_id: None,
+ billing_address_id: None,
+ mit_category: None,
+ tokenization: None,
+ statement_descriptor_name: None,
+ statement_descriptor_suffix: None,
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ last_synced: None,
+ setup_future_usage: None,
+ fingerprint_id: None,
+ off_session: None,
+ client_secret: Some("1".to_string()),
+ active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
+ "nopes".to_string(),
+ ),
+ business_country: None,
+ business_label: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ attempt_count: 1,
+ payment_link_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
+ merchant_decision: None,
+ payment_confirm_source: None,
+ surcharge_applicable: None,
+ updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
+ request_incremental_authorization: Some(
+ common_enums::RequestIncrementalAuthorization::default(),
+ ),
+ incremental_authorization_allowed: None,
+ authorization_count: None,
+ session_expiry: Some(
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
+ request_external_three_ds_authentication: None,
+ split_payments: None,
+ frm_metadata: None,
+ customer_details: None,
+ billing_details: None,
+ merchant_order_reference_id: None,
+ shipping_details: None,
+ is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ request_extended_authorization: None,
+ psd2_sca_exemption_type: None,
+ processor_merchant_id: id_type::MerchantId::default(),
+ created_by: None,
+ force_3ds_challenge: None,
+ force_3ds_challenge_trigger: None,
+ is_iframe_redirection_enabled: None,
+ is_payment_id_from_merchant: None,
+ payment_channel: None,
+ tax_status: None,
+ discount_amount: None,
+ order_date: None,
+ shipping_amount_tax: None,
+ value_added_tax_amount: None,
+ value_added_tax_percent: None,
+ vat_invoice_reference_number: None,
+ order_commodity_code: None,
+ duty_amount: None,
+ enable_partial_authorization: None,
+ enable_overcapture: None,
+ billing_descriptor: None,
+ is_account_funded_transaction: None,
+ recipient_details: None,
+ partner_merchant_identifier_details: None,
+ state_metadata: None,
+ installment_options: None,
+ profile_acquirer_id: None,
+ external_surcharge_strategy: None,
+ external_surcharge_applicable: None,
+ enable_avs_check: None,
+ settlement_conclusion_applied: None,
+ enable_account_name_verification: None,
+ };
+ let req_cs = Some("1".to_string());
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
+ // Check if the result is an Ok variant
+}
+
+#[test]
+fn test_authenticate_client_secret_session_expired() {
+ let created_at =
+ common_utils::date_time::now().saturating_sub(time::Duration::seconds(20 * 60));
+ let payment_intent = PaymentIntent {
+ payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
+ merchant_id: id_type::MerchantId::default(),
+ status: storage_enums::IntentStatus::RequiresCapture,
+ amount: MinorUnit::new(200),
+ currency: None,
+ amount_captured: None,
+ customer_id: None,
+ description: None,
+ return_url: None,
+ metadata: None,
+ connector_id: None,
+ shipping_address_id: None,
+ mit_category: None,
+ billing_address_id: None,
+ statement_descriptor_name: None,
+ statement_descriptor_suffix: None,
+ created_at,
+ modified_at: common_utils::date_time::now(),
+ fingerprint_id: None,
+ last_synced: None,
+ setup_future_usage: None,
+ off_session: None,
+ client_secret: Some("1".to_string()),
+ active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
+ "nopes".to_string(),
+ ),
+ business_country: None,
+ business_label: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ attempt_count: 1,
+ payment_link_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
+ merchant_decision: None,
+ payment_confirm_source: None,
+ surcharge_applicable: None,
+ updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
+ request_incremental_authorization: Some(
+ common_enums::RequestIncrementalAuthorization::default(),
+ ),
+ incremental_authorization_allowed: None,
+ authorization_count: None,
+ session_expiry: Some(
+ created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
+ request_external_three_ds_authentication: None,
+ split_payments: None,
+ frm_metadata: None,
+ customer_details: None,
+ billing_details: None,
+ merchant_order_reference_id: None,
+ shipping_details: None,
+ is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ request_extended_authorization: None,
+ psd2_sca_exemption_type: None,
+ processor_merchant_id: id_type::MerchantId::default(),
+ created_by: None,
+ force_3ds_challenge: None,
+ force_3ds_challenge_trigger: None,
+ is_iframe_redirection_enabled: None,
+ is_payment_id_from_merchant: None,
+ payment_channel: None,
+ tax_status: None,
+ discount_amount: None,
+ order_date: None,
+ shipping_amount_tax: None,
+ value_added_tax_amount: None,
+ value_added_tax_percent: None,
+ vat_invoice_reference_number: None,
+ order_commodity_code: None,
+ duty_amount: None,
+ enable_partial_authorization: None,
+ enable_overcapture: None,
+ billing_descriptor: None,
+ is_account_funded_transaction: None,
+ recipient_details: None,
+ tokenization: None,
+ partner_merchant_identifier_details: None,
+ state_metadata: None,
+ installment_options: None,
+ profile_acquirer_id: None,
+ external_surcharge_strategy: None,
+ external_surcharge_applicable: None,
+ enable_avs_check: None,
+ settlement_conclusion_applied: None,
+ enable_account_name_verification: None,
+ };
+ let req_cs = Some("1".to_string());
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
+}
+
+#[test]
+fn test_authenticate_client_secret_expired() {
+ let payment_intent = PaymentIntent {
+ payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
+ merchant_id: id_type::MerchantId::default(),
+ status: storage_enums::IntentStatus::RequiresCapture,
+ amount: MinorUnit::new(200),
+ currency: None,
+ amount_captured: None,
+ customer_id: None,
+ description: None,
+ return_url: None,
+ metadata: None,
+ connector_id: None,
+ mit_category: None,
+ tokenization: None,
+ shipping_address_id: None,
+ billing_address_id: None,
+ statement_descriptor_name: None,
+ statement_descriptor_suffix: None,
+ created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)),
+ modified_at: common_utils::date_time::now(),
+ last_synced: None,
+ setup_future_usage: None,
+ off_session: None,
+ client_secret: None,
+ fingerprint_id: None,
+ active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
+ "nopes".to_string(),
+ ),
+ business_country: None,
+ business_label: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ attempt_count: 1,
+ payment_link_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
+ merchant_decision: None,
+ payment_confirm_source: None,
+ surcharge_applicable: None,
+ updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
+ request_incremental_authorization: Some(
+ common_enums::RequestIncrementalAuthorization::default(),
+ ),
+ incremental_authorization_allowed: None,
+ authorization_count: None,
+ session_expiry: Some(
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
+ request_external_three_ds_authentication: None,
+ split_payments: None,
+ frm_metadata: None,
+ customer_details: None,
+ billing_details: None,
+ merchant_order_reference_id: None,
+ shipping_details: None,
+ is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ request_extended_authorization: None,
+ psd2_sca_exemption_type: None,
+ processor_merchant_id: id_type::MerchantId::default(),
+ created_by: None,
+ force_3ds_challenge: None,
+ force_3ds_challenge_trigger: None,
+ is_iframe_redirection_enabled: None,
+ is_payment_id_from_merchant: None,
+ payment_channel: None,
+ tax_status: None,
+ discount_amount: None,
+ order_date: None,
+ shipping_amount_tax: None,
+ value_added_tax_amount: None,
+ value_added_tax_percent: None,
+ vat_invoice_reference_number: None,
+ order_commodity_code: None,
+ duty_amount: None,
+ enable_partial_authorization: None,
+ enable_overcapture: None,
+ billing_descriptor: None,
+ is_account_funded_transaction: None,
+ recipient_details: None,
+ partner_merchant_identifier_details: None,
+ state_metadata: None,
+ installment_options: None,
+ profile_acquirer_id: None,
+ external_surcharge_strategy: None,
+ external_surcharge_applicable: None,
+ enable_avs_check: None,
+ settlement_conclusion_applied: None,
+ enable_account_name_verification: None,
+ };
+ let req_cs = Some("1".to_string());
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
+}
diff --git a/crates/router/src/core/payments/helpers/tests/connector_response_card_merge.rs b/crates/router/src/core/payments/helpers/tests/connector_response_card_merge.rs
new file mode 100644
index 0000000000..2bf8ce11c2
--- /dev/null
+++ b/crates/router/src/core/payments/helpers/tests/connector_response_card_merge.rs
@@ -0,0 +1,100 @@
+use hyperswitch_domain_models::router_data::AdditionalPaymentMethodConnectorResponse;
+
+use super::super::add_connector_response_to_additional_payment_data;
+
+/// A connector that reports every card attribute it can, as Worldpay does when `<cardBin>` is
+/// enabled on the account.
+fn connector_card_response() -> AdditionalPaymentMethodConnectorResponse {
+ AdditionalPaymentMethodConnectorResponse::Card {
+ authentication_data: None,
+ payment_checks: None,
+ card_network: None,
+ domestic_network: None,
+ auth_code: Some("123456".to_string()),
+ processor_card_network: Some(common_enums::CardNetwork::Visa),
+ card_subtype: Some("ELECTRON".to_string()),
+ card_segment_type: Some(common_enums::CardSegmentType::Commercial),
+ funding_source: Some(common_enums::FundingSource::Debit),
+ card_type: Some(common_enums::CardType::Debit),
+ issuer_name: Some("CONNECTOR ISSUER".to_string()),
+ issuer_country: Some(common_enums::CountryAlpha2::GB),
+ }
+}
+
+fn merge(
+ additional_card_info: api_models::payments::AdditionalCardInfo,
+) -> api_models::payments::AdditionalCardInfo {
+ let merged = add_connector_response_to_additional_payment_data(
+ api_models::payments::AdditionalPaymentData::Card(Box::new(additional_card_info)),
+ connector_card_response(),
+ );
+
+ match merged {
+ api_models::payments::AdditionalPaymentData::Card(card) => *card,
+ other => panic!("expected card additional payment data, got {other:?}"),
+ }
+}
+
+#[test]
+fn connector_card_attributes_fill_an_empty_card_record() {
+ let card = merge(api_models::payments::AdditionalCardInfo {
+ card_isin: Some("444433".to_string()),
+ ..Default::default()
+ });
+
+ assert_eq!(card.card_issuer.as_deref(), Some("CONNECTOR ISSUER"));
+ assert_eq!(card.card_type.as_deref(), Some("DEBIT"));
+ assert_eq!(card.card_subtype.as_deref(), Some("ELECTRON"));
+ assert_eq!(
+ card.card_segment_type,
+ Some(common_enums::CardSegmentType::Commercial)
+ );
+ assert_eq!(
+ card.funding_source,
+ Some(common_enums::FundingSource::Debit)
+ );
+ assert_eq!(card.card_issuing_country.as_deref(), Some("GB"));
+ assert_eq!(card.card_issuing_country_code.as_deref(), Some("GB"));
+ assert_eq!(card.card_network, Some(common_enums::CardNetwork::Visa));
+ assert_eq!(card.auth_code.as_deref(), Some("123456"));
+ assert_eq!(card.card_isin.as_deref(), Some("444433"));
+}
+
+#[test]
+fn resolved_values_win_and_the_connector_only_fills_the_gaps() {
+ let card = merge(api_models::payments::AdditionalCardInfo {
+ card_issuer: Some("CURATED ISSUER".to_string()),
+ card_type: Some("CREDIT".to_string()),
+ card_issuing_country: Some("IN".to_string()),
+ ..Default::default()
+ });
+
+ assert_eq!(card.card_issuer.as_deref(), Some("CURATED ISSUER"));
+ assert_eq!(card.card_type.as_deref(), Some("CREDIT"));
+ assert_eq!(card.card_issuing_country.as_deref(), Some("IN"));
+ // The columns the BIN record left null are filled from the connector rather than staying
+ // empty, which is the case that matters for BINs whose subtype is not recorded.
+ assert_eq!(card.card_subtype.as_deref(), Some("ELECTRON"));
+ assert_eq!(
+ card.funding_source,
+ Some(common_enums::FundingSource::Debit)
+ );
+ assert_eq!(
+ card.card_segment_type,
+ Some(common_enums::CardSegmentType::Commercial)
+ );
+ assert_eq!(card.auth_code.as_deref(), Some("123456"));
+}
+
+#[test]
+fn a_cobadge_resolved_network_is_not_overwritten() {
+ let card = merge(api_models::payments::AdditionalCardInfo {
+ card_network: Some(common_enums::CardNetwork::RuPay),
+ ..Default::default()
+ });
+
+ // Debit routing selects the rail the payment authorizes on, so the connector's plain scheme
+ // network must not replace it.
+ assert_eq!(card.card_network, Some(common_enums::CardNetwork::RuPay));
+ assert_eq!(card.card_issuer.as_deref(), Some("CONNECTOR ISSUER"));
+}
diff --git a/crates/router/src/core/payments/helpers/tests/generate_mandate.rs b/crates/router/src/core/payments/helpers/tests/generate_mandate.rs
new file mode 100644
index 0000000000..22c62b24ff
--- /dev/null
+++ b/crates/router/src/core/payments/helpers/tests/generate_mandate.rs
@@ -0,0 +1,51 @@
+use std::borrow::Cow;
+
+use common_types::payments::{AcceptanceType, CustomerAcceptance};
+use common_utils::{id_type, types::MinorUnit};
+use hyperswitch_domain_models::mandates::{MandateAmountData, MandateData, MandateDataType};
+
+use super::super::generate_mandate;
+
+/// A new mandate sets its own `created_at` rather than taking the database default.
+#[test]
+fn a_new_mandate_carries_its_own_created_at() {
+ let mandate_data = MandateData {
+ update_mandate_id: None,
+ customer_acceptance: Some(CustomerAcceptance {
+ acceptance_type: AcceptanceType::Offline,
+ accepted_at: None,
+ online: None,
+ }),
+ mandate_type: Some(MandateDataType::SingleUse(MandateAmountData {
+ amount: MinorUnit::new(100),
+ currency: common_enums::Currency::USD,
+ start_date: None,
+ end_date: None,
+ metadata: None,
+ })),
+ };
+ let customer_id = Some(id_type::CustomerId::try_from(Cow::Borrowed("cus_1")).unwrap());
+
+ let before = common_utils::date_time::now();
+ let mandate = generate_mandate(
+ id_type::MerchantId::default(),
+ id_type::PaymentId::try_from(Cow::Borrowed("pay_1")).unwrap(),
+ "stripe".to_owned(),
+ Some(mandate_data),
+ &customer_id,
+ "pm_1".to_owned(),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+ .unwrap()
+ .expect("a mandate for mandate data and a customer");
+
+ let after = common_utils::date_time::now();
+
+ let created_at = mandate.created_at.expect("created_at is set");
+ assert!(before <= created_at && created_at <= after, "{created_at}");
+}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 2787e8b028..ff85b1805e 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -27,12 +27,9 @@ use tracing_futures::Instrument;
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
#[cfg(feature = "v1")]
+use crate::routes::payments::callback_routes::ConnectorCallbackPath;
use crate::{
consts,
- core::utils::create_encrypted_data,
- events::audit_events::{AuditEvent, AuditEventType},
-};
-use crate::{
core::{
authentication,
blocklist::utils as blocklist_utils,
@@ -53,8 +50,10 @@ use crate::{
types::{ClickToPay, UnifiedAuthenticationService},
},
utils as core_utils,
+ utils::create_encrypted_data,
},
- routes::{app::ReqState, SessionState},
+ events::audit_events::{AuditEvent, AuditEventType},
+ routes::{app::ReqState, payments::callback_routes::PaymentCallbackRoute, SessionState},
services,
types::{
api::{self, ConnectorCallType, PaymentIdTypeExt},
@@ -2187,11 +2186,16 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
authentication::utils::get_authentication_connector_data(state, platform.get_processor(), business_profile, None).await?;
- let return_url = helpers::create_authorize_url(
+ let return_url = PaymentCallbackRoute::authorize_url(
&state.base_url,
- &payment_data.payment_attempt.clone(),
- payment_data.payment_attempt.connector.as_ref().get_required_value("connector")?,
- );
+ state.payment_callback_config().await?.mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_data.payment_attempt.payment_id.clone(),
+ merchant_id: payment_data.payment_attempt.processor_merchant_id.clone(),
+ connector: payment_data.payment_attempt.connector.as_ref()
+ .get_required_value("connector")?.to_string(),
+ },
+ ).persist(state).await?;
let domain_address = payment_data.address.get_payment_method_billing().map(|address| address.clone().foreign_into());
let shipping = payment_data.address.get_shipping().map(|address| address.clone().foreign_into());
diff --git a/crates/router/src/core/payments/session_operation.rs b/crates/router/src/core/payments/session_operation.rs
index 8595cbeb98..9860c7ed4e 100644
--- a/crates/router/src/core/payments/session_operation.rs
+++ b/crates/router/src/core/payments/session_operation.rs
@@ -94,17 +94,17 @@ where
)
.await?;
- Res::generate_response(
+ Res::generate_response_with_callbacks(
+ &state,
payment_data,
customer,
- &state.base_url,
operation,
- &state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&platform,
)
+ .await
}
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index a63ef1a339..f64a25ba15 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -49,25 +49,38 @@ use hyperswitch_domain_models::{
router_data_v2::{flow_common_types, RouterDataV2},
ApiModelToDieselModelConvertor,
};
+#[cfg(feature = "v1")]
+use hyperswitch_interfaces::api::ConnectorCommon;
+use hyperswitch_interfaces::api::ConnectorRedirectResponse;
#[cfg(feature = "v2")]
use hyperswitch_interfaces::api::ConnectorSpecifications;
#[cfg(feature = "v2")]
use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion;
-use hyperswitch_masking::{ExposeInterface, Maskable, Secret};
#[cfg(feature = "v2")]
-use hyperswitch_masking::{ExposeOptionInterface, PeekInterface};
+use hyperswitch_masking::ExposeOptionInterface;
+use hyperswitch_masking::{ExposeInterface, Maskable, PeekInterface, Secret};
use router_env::{instrument, tracing};
-use super::{flows::Feature, types::AuthenticationData, OperationSessionGetters, PaymentData};
+use super::{
+ callback_urls::{ConnectorCallbackUrls, SdkCallbackUrls},
+ flows::Feature,
+ types::AuthenticationData,
+ OperationSessionGetters, PaymentData,
+};
use crate::{
configs::settings::ConnectorRequestReferenceIdConfig,
core::{
+ configs::payment_callback::PaymentCallbackMode,
errors::{self, RouterResponse, RouterResult},
payments::{self, helpers},
utils as core_utils,
},
headers::{X_CONNECTOR_HTTP_STATUS_CODE, X_PAYMENT_CONFIRM_SOURCE},
- routes::{metrics, SessionState},
+ routes::{
+ metrics,
+ payments::callback_routes::{ConnectorCallbackPath, StartCallbackPath},
+ SessionState,
+ },
services::{self, RedirectForm},
types::{
self,
@@ -101,6 +114,7 @@ pub async fn construct_router_data_to_update_calculated_tax<'a, F, T>(
processor: &domain::Processor,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
@@ -119,6 +133,7 @@ pub async fn construct_router_data_to_update_calculated_tax<'a, F, T>(
connector_id: &str,
processor: &domain::Processor,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
@@ -155,6 +170,8 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let additional_data = PaymentAdditionalData {
+ callback_mode: state.payment_callback_config().await?.mode,
+ connector_callback_urls,
router_base_url: state.base_url.clone(),
connector_name: connector_id.to_string(),
payment_data: payment_data.clone(),
@@ -346,6 +363,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<types::PaymentsAuthorizeRouterData> {
use hyperswitch_masking::ExposeOptionInterface;
@@ -369,12 +387,18 @@ pub async fn construct_payment_router_data_for_authorize<'a>(
let router_base_url = &state.base_url;
let attempt = &payment_data.payment_attempt;
- let complete_authorize_url = Some(helpers::create_complete_authorize_url(
- router_base_url,
- attempt,
- connector_id,
- None,
- ));
+ let complete_authorize_url = Some(
+ connector_callback_urls
+ .redirect_complete_url(
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ &attempt.payment_id,
+ &attempt.processor_merchant_id,
+ connector_id,
+ None,
+ )
+ .clone(),
+ );
let webhook_url = match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
@@ -457,6 +481,17 @@ pub async fn construct_payment_router_data_for_authorize<'a>(
// TODO: few fields are repeated in both routerdata and request
let request = types::PaymentsAuthorizeData {
+ router_notification_url: connector_callback_urls.notification_url(
+ api::ConnectorData::convert_connector(connector_id)?.get_notification_callback(),
+ router_base_url,
+ state.payment_callback_config().await?.mode,
+ &ConnectorCallbackPath {
+ payment_id: attempt.payment_id.clone(),
+ merchant_id: attempt.processor_merchant_id.clone(),
+ connector: connector_id.to_string(),
+ },
+ None,
+ ),
payment_method_data: payment_data
.payment_method_data
.get_required_value("payment_method_data")?,
@@ -484,7 +519,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(
enrolled_for_3ds: true,
related_transaction_id: None,
payment_method_type: payment_data.payment_attempt.payment_method_subtype,
- router_return_url: Some(router_return_url),
+ router_return_url: Some(router_return_url.into()),
webhook_url,
complete_authorize_url,
customer_id: customer_id.clone(),
@@ -651,6 +686,7 @@ pub async fn construct_external_vault_proxy_payment_router_data<'a>(
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<types::ExternalVaultProxyPaymentsRouterData> {
use hyperswitch_masking::ExposeOptionInterface;
@@ -674,12 +710,18 @@ pub async fn construct_external_vault_proxy_payment_router_data<'a>(
let router_base_url = &state.base_url;
let attempt = &payment_data.payment_attempt;
- let complete_authorize_url = Some(helpers::create_complete_authorize_url(
- router_base_url,
- attempt,
- connector_id,
- None,
- ));
+ let complete_authorize_url = Some(
+ connector_callback_urls
+ .redirect_complete_url(
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ &attempt.payment_id,
+ &attempt.processor_merchant_id,
+ connector_id,
+ None,
+ )
+ .clone(),
+ );
let webhook_url = match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
@@ -753,7 +795,7 @@ pub async fn construct_external_vault_proxy_payment_router_data<'a>(
enrolled_for_3ds: true,
related_transaction_id: None,
payment_method_type: payment_data.payment_attempt.payment_method_subtype,
- router_return_url: Some(router_return_url),
+ router_return_url: Some(router_return_url.into()),
webhook_url,
complete_authorize_url,
customer_id: customer_id.clone(),
@@ -820,6 +862,7 @@ pub async fn construct_external_vault_proxy_payment_router_data_v1<'a>(
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<types::ExternalVaultProxyPaymentsRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
@@ -841,12 +884,18 @@ pub async fn construct_external_vault_proxy_payment_router_data_v1<'a>(
.map(|mca_id| mca_id.get_string_repr().to_owned())
.unwrap_or_else(|| connector_id.to_owned());
- let complete_authorize_url = Some(helpers::create_complete_authorize_url(
- &state.base_url,
- attempt,
- connector_id,
- None,
- ));
+ let complete_authorize_url = Some(
+ connector_callback_urls
+ .redirect_complete_url(
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ &attempt.payment_id,
+ &attempt.processor_merchant_id,
+ connector_id,
+ None,
+ )
+ .clone(),
+ );
let webhook_url = Some(helpers::create_webhook_url(
&state.base_url,
@@ -854,12 +903,18 @@ pub async fn construct_external_vault_proxy_payment_router_data_v1<'a>(
&merchant_connector_account_id_or_connector_name,
));
- let router_return_url = Some(helpers::create_redirect_url(
- &state.base_url,
- attempt,
- connector_id,
- payment_data.creds_identifier.as_deref(),
- ));
+ let router_return_url = Some(
+ connector_callback_urls
+ .redirect_response_url(
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ &attempt.payment_id,
+ &attempt.processor_merchant_id,
+ connector_id,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let amount = payment_data.payment_attempt.get_total_amount();
@@ -1765,6 +1820,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>(
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<types::SetupMandateRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
@@ -1789,12 +1845,18 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>(
let router_base_url = &state.base_url;
let attempt = &payment_data.payment_attempt;
- let complete_authorize_url = Some(helpers::create_complete_authorize_url(
- router_base_url,
- attempt,
- connector_id,
- None,
- ));
+ let complete_authorize_url = Some(
+ connector_callback_urls
+ .redirect_complete_url(
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ &attempt.payment_id,
+ &attempt.processor_merchant_id,
+ connector_id,
+ None,
+ )
+ .clone(),
+ );
let webhook_url = match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
@@ -1863,7 +1925,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>(
off_session: None,
tokenization: None,
setup_mandate_details: None,
- router_return_url: Some(router_return_url.clone()),
+ router_return_url: Some(router_return_url.clone().into()),
webhook_url,
browser_info,
email,
@@ -2012,6 +2074,7 @@ pub async fn construct_payment_router_data<'a, F, T>(
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
@@ -2079,6 +2142,8 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let additional_data = PaymentAdditionalData {
+ callback_mode: state.payment_callback_config().await?.mode,
+ connector_callback_urls,
router_base_url: state.base_url.clone(),
connector_name: connector_id.to_string(),
payment_data: payment_data.clone(),
@@ -2368,6 +2433,7 @@ pub async fn construct_payment_router_data_for_update_metadata<'a>(
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<
api::UpdateMetadata,
@@ -2426,6 +2492,8 @@ pub async fn construct_payment_router_data_for_update_metadata<'a>(
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let additional_data = PaymentAdditionalData {
+ callback_mode: state.payment_callback_config().await?.mode,
+ connector_callback_urls,
router_base_url: state.base_url.clone(),
connector_name: connector_id.to_string(),
payment_data: payment_data.clone(),
@@ -2589,22 +2657,91 @@ pub async fn construct_payment_router_data_for_update_metadata<'a>(
pub trait ToResponse<F, D, Op>
where
- Self: Sized,
+ Self: Sized + Send,
Op: Debug,
D: OperationSessionGetters<F>,
{
+ #[cfg(feature = "v1")]
+ #[allow(async_fn_in_trait, clippy::too_many_arguments)]
+ async fn generate_response_with_callbacks(
+ state: &SessionState,
+ data: D,
+ auth_flow: services::AuthFlow,
+ operation: Op,
+ connector_http_status_code: Option<u16>,
+ external_latency: Option<u128>,
+ is_latency_header_enabled: Option<bool>,
+ platform: &domain::Platform,
+ ) -> RouterResponse<Self>
+ where
+ D: Send,
+ Op: Send,
+ {
+ let mut sdk_callback_urls = SdkCallbackUrls::default();
+ let response = Self::generate_response(
+ data,
+ auth_flow,
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ operation,
+ &state.conf.connector_request_reference_id_config,
+ connector_http_status_code,
+ external_latency,
+ is_latency_header_enabled,
+ platform,
+ &mut sdk_callback_urls,
+ )?;
+ sdk_callback_urls.persist(state).await?;
+ Ok(response)
+ }
+ #[cfg(feature = "v2")]
+ #[allow(async_fn_in_trait, clippy::too_many_arguments)]
+ async fn generate_response_with_callbacks(
+ state: &SessionState,
+ data: D,
+ customer: Option<domain::Customer>,
+ operation: Op,
+ connector_http_status_code: Option<u16>,
+ external_latency: Option<u128>,
+ is_latency_header_enabled: Option<bool>,
+ platform: &domain::Platform,
+ ) -> RouterResponse<Self>
+ where
+ D: Send,
+ Op: Send,
+ {
+ let mut sdk_callback_urls = SdkCallbackUrls::default();
+ let response = Self::generate_response(
+ data,
+ customer,
+ &state.base_url,
+ state.payment_callback_config().await?.mode,
+ operation,
+ &state.conf.connector_request_reference_id_config,
+ connector_http_status_code,
+ external_latency,
+ is_latency_header_enabled,
+ platform,
+ &mut sdk_callback_urls,
+ )?;
+ sdk_callback_urls.persist(state).await?;
+ Ok(response)
+ }
+
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
fn generate_response(
data: D,
auth_flow: services::AuthFlow,
base_url: &str,
+ callback_mode: PaymentCallbackMode,
operation: Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
platform: &domain::Platform,
+ sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self>;
#[cfg(feature = "v2")]
@@ -2613,12 +2750,14 @@ where
data: D,
customer: Option<domain::Customer>,
base_url: &str,
+ callback_mode: PaymentCallbackMode,
operation: Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self>;
}
@@ -2832,12 +2971,14 @@ where
payment_data: D,
auth_flow: services::AuthFlow,
base_url: &str,
+ callback_mode: PaymentCallbackMode,
operation: Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
platform: &domain::Platform,
+ sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
let captures = payment_data
.get_multiple_capture_data()
@@ -2860,6 +3001,7 @@ where
captures,
auth_flow,
base_url,
+ callback_mode,
&operation,
connector_request_reference_id_config,
connector_http_status_code,
@@ -2867,6 +3009,7 @@ where
is_latency_header_enabled,
platform.get_processor(),
platform.get_initiator(),
+ sdk_callback_urls,
)
}
}
@@ -2883,12 +3026,14 @@ where
payment_data: D,
_auth_flow: services::AuthFlow,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
@@ -2921,12 +3066,14 @@ where
payment_data: D,
_customer: Option<domain::Customer>,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
@@ -2951,12 +3098,14 @@ where
payment_data: D,
_auth_flow: services::AuthFlow,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
let mut amount = payment_data.get_payment_intent().amount;
let shipping_cost = payment_data.get_payment_intent().shipping_cost;
@@ -3011,12 +3160,14 @@ where
payment_data: D,
_customer: Option<domain::Customer>,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
let payment_intent = payment_data.get_payment_intent();
let client_secret = payment_data.get_client_secret();
@@ -3122,12 +3273,14 @@ where
payment_data: D,
_customer: Option<domain::Customer>,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
@@ -3654,12 +3807,14 @@ where
payment_data: D,
_auth_flow: services::AuthFlow,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
let papal_sdk_next_action =
paypal_sdk_next_steps_check(payment_data.get_payment_attempt().clone())?;
@@ -3691,12 +3846,14 @@ where
payment_data: D,
_auth_flow: services::AuthFlow,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
@@ -3779,12 +3936,14 @@ where
_customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
todo!()
}
@@ -3795,12 +3954,14 @@ where
payment_data: D,
_auth_flow: services::AuthFlow,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_platform: &domain::Platform,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<Self> {
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_data
@@ -3874,11 +4035,13 @@ pub fn payments_to_payments_response<Op, F: Clone, D>(
_customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
+ _callback_mode: PaymentCallbackMode,
_operation: &Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
+ _sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<api_models::payments::PaymentsResponse>
where
Op: Debug,
@@ -3897,6 +4060,7 @@ pub fn payments_to_payments_response<Op, F: Clone, D>(
captures: Option<Vec<storage::Capture>>,
_auth_flow: services::AuthFlow,
base_url: &str,
+ callback_mode: PaymentCallbackMode,
operation: &Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
@@ -3904,6 +4068,7 @@ pub fn payments_to_payments_response<Op, F: Clone, D>(
_is_latency_header_enabled: Option<bool>,
processor: &domain::Processor,
initiator: Option<&domain::Initiator>,
+ sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResponse<api::PaymentsResponse>
where
Op: Debug,
@@ -4071,13 +4236,6 @@ where
})
.unwrap_or_default(),
);
- let connector_name = payment_attempt.connector.as_deref().unwrap_or_default();
- let router_return_url = helpers::create_redirect_url(
- &base_url.to_string(),
- &payment_attempt,
- connector_name,
- payment_data.get_creds_identifier(),
- );
let output = if payments::is_start_pay(&operation)
&& payment_attempt.authentication_data.is_some()
@@ -4089,15 +4247,36 @@ where
let form: RedirectForm = serde_json::from_value(redirection_data)
.map_err(|_| errors::ApiErrorResponse::InternalServerError)?;
+ let connector_name = payment_attempt
+ .connector
+ .as_deref()
+ .get_required_value("connector")?;
+ let connector = api::ConnectorData::convert_connector(connector_name)?;
+ let callback_url = sdk_callback_urls
+ .redirection_form_callback_url(
+ connector.get_redirect_callback(&form),
+ base_url,
+ callback_mode,
+ &ConnectorCallbackPath {
+ payment_id: payment_attempt.payment_id.clone(),
+ merchant_id: payment_attempt.processor_merchant_id.clone(),
+ connector: connector.id().to_string(),
+ },
+ payment_data.get_creds_identifier(),
+ )
+ .cloned();
services::ApplicationResponse::Form(Box::new(services::RedirectionFormData {
redirect_form: form,
+ callback_url,
payment_method_data: payment_data.get_payment_method_data().cloned(),
amount,
currency: currency.to_string(),
}))
} else {
let mut next_action_response = None;
+ let third_party_sdk_session =
+ third_party_sdk_session_next_action(&payment_attempt, operation);
// Early exit for terminal payment statuses - don't evaluate next_action at all
if payment_intent.status.is_in_terminal_state() {
@@ -4125,9 +4304,6 @@ where
let next_action_invoke_hidden_frame =
next_action_invoke_hidden_frame(&payment_attempt)?;
- let next_action_invoke_ddc_iframe =
- next_action_invoke_ddc_iframe(&payment_attempt, base_url)?;
-
if payment_intent.status == enums::IntentStatus::RequiresCustomerAction
|| bank_transfer_next_steps.is_some()
|| next_action_voucher.is_some()
@@ -4138,91 +4314,150 @@ where
|| next_action_containing_fetch_qr_code_url.is_some()
|| payment_data.get_authentication().is_some()
{
- next_action_response = next_action_invoke_ddc_iframe.map(|ddc_iframe_data| {
- api_models::payments::NextActionData::InvokeDdc {
- ddc_data: api_models::payments::DDCData {
- iframe_url: ddc_iframe_data.iframe_url,
- timeout_ms: ddc_iframe_data.timeout_ms,
- }
- }
- }).or(
- payment_attempt.authentication_data.as_ref().map(|_| {
- // Check if iframe redirection is enabled in the business profile
- let redirect_url = helpers::create_startpay_url(
+ next_action_response = next_action_invoke_ddc_iframe(
+ payment_attempt.connector_metadata.as_ref(),
+ base_url,
+ callback_mode,
+ &StartCallbackPath {
+ payment_id: payment_intent.get_id().clone(),
+ merchant_id: payment_intent.processor_merchant_id.clone(),
+ attempt_id: payment_attempt.attempt_id.clone(),
+ },
+ sdk_callback_urls,
+ )?
+ .map(|ddc_iframe_data| {
+ api_models::payments::NextActionData::InvokeDdc {
+ ddc_data: api_models::payments::DDCData {
+ iframe_url: ddc_iframe_data.iframe_url,
+ timeout_ms: ddc_iframe_data.timeout_ms,
+ },
+ }
+ });
+ if next_action_response.is_none()
+ && payment_attempt.authentication_data.is_some()
+ && !third_party_sdk_session
+ {
+ let redirect_url = sdk_callback_urls
+ .start_url(
+ base_url,
+ callback_mode,
+ payment_intent.get_id(),
+ &payment_intent.processor_merchant_id,
+ &payment_attempt.attempt_id,
+ )
+ .clone();
+ next_action_response = Some(
+ if payment_intent
+ .is_iframe_redirection_enabled
+ .unwrap_or(false)
+ {
+ let connector = payment_attempt
+ .connector
+ .as_deref()
+ .get_required_value("connector")?;
+ let redirect_response_url = sdk_callback_urls
+ .redirect_response_url(
base_url,
- &payment_attempt,
- &payment_intent,
- );
- // Check if redirection inside popup is enabled in the payment intent
- if payment_intent.is_iframe_redirection_enabled.unwrap_or(false) {
- api_models::payments::NextActionData::RedirectInsidePopup {
- popup_url: redirect_url,
- redirect_response_url:router_return_url
- }
- } else {
- api_models::payments::NextActionData::RedirectToUrl {
- redirect_to_url: redirect_url,
- }
- }
- }))
- .or(bank_transfer_next_steps
- .map(|bank_transfer| {
- api_models::payments::NextActionData::DisplayBankTransferInformation {
- bank_transfer_steps_and_charges_details: bank_transfer,
- }
- }))
- .or(next_action_voucher.map(|voucher_data| {
- api_models::payments::NextActionData::DisplayVoucherInformation {
- voucher_details: voucher_data,
- }
- }))
- .or(next_action_mobile_payment.map(|mobile_payment_data| {
- api_models::payments::NextActionData::CollectOtp {
- consent_data_required: mobile_payment_data.consent_data_required,
- }
- }))
- .or(next_action_containing_qr_code_url.map(|qr_code_data| {
- api_models::payments::NextActionData::foreign_from(qr_code_data)
- }))
- .or(next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| {
- api_models::payments::NextActionData::FetchQrCodeInformation {
- qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url
- }
- }))
- .or(papal_sdk_next_action.map(|paypal_next_action_data| {
- api_models::payments::NextActionData::InvokeSdkClient{
- next_action_data: paypal_next_action_data
- }
- }))
- .or(upi_next_action)
- .or(next_action_containing_wait_screen.map(|wait_screen_data| {
- api_models::payments::NextActionData::WaitScreenInformation {
- display_from_timestamp: wait_screen_data.display_from_timestamp,
- display_to_timestamp: wait_screen_data.display_to_timestamp,
- poll_config: wait_screen_data.poll_config,
- }
- }))
- .or(match payment_data.get_authentication(){
- Some(authentication_store) => {
- let authentication = &authentication_store.authentication;
- if payment_intent.status == common_enums::IntentStatus::RequiresCustomerAction && authentication_store.cavv.is_none() && authentication.is_separate_authn_required(){
- // if preAuthn and separate authentication needed.
- let poll_config = payment_data.get_poll_config().unwrap_or_default();
- let request_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_intent.payment_id);
- let payment_connector_name = payment_attempt.connector
- .as_ref()
- .get_required_value("connector")?;
- let is_jwt_flow = authentication.is_jwt_flow()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to determine if the authentication is JWT flow")?;
- Some(api_models::payments::NextActionData::ThreeDsInvoke {
+ callback_mode,
+ &payment_attempt.payment_id,
+ &payment_attempt.processor_merchant_id,
+ connector,
+ payment_data.get_creds_identifier(),
+ )
+ .clone();
+ api_models::payments::NextActionData::RedirectInsidePopup {
+ popup_url: redirect_url,
+ redirect_response_url,
+ }
+ } else {
+ api_models::payments::NextActionData::RedirectToUrl {
+ redirect_to_url: redirect_url,
+ }
+ },
+ );
+ }
+ next_action_response = next_action_response
+ .or(bank_transfer_next_steps.map(|bank_transfer| {
+ api_models::payments::NextActionData::DisplayBankTransferInformation {
+ bank_transfer_steps_and_charges_details: bank_transfer,
+ }
+ }))
+ .or(next_action_voucher.map(|voucher_data| {
+ api_models::payments::NextActionData::DisplayVoucherInformation {
+ voucher_details: voucher_data,
+ }
+ }))
+ .or(next_action_mobile_payment.map(|mobile_payment_data| {
+ api_models::payments::NextActionData::CollectOtp {
+ consent_data_required: mobile_payment_data.consent_data_required,
+ }
+ }))
+ .or(next_action_containing_qr_code_url.map(|qr_code_data| {
+ api_models::payments::NextActionData::foreign_from(qr_code_data)
+ }))
+ .or(
+ next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| {
+ api_models::payments::NextActionData::FetchQrCodeInformation {
+ qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url,
+ }
+ }),
+ )
+ .or(papal_sdk_next_action.map(|paypal_next_action_data| {
+ api_models::payments::NextActionData::InvokeSdkClient {
+ next_action_data: paypal_next_action_data,
+ }
+ }))
+ .or(upi_next_action)
+ .or(next_action_containing_wait_screen.map(|wait_screen_data| {
+ api_models::payments::NextActionData::WaitScreenInformation {
+ display_from_timestamp: wait_screen_data.display_from_timestamp,
+ display_to_timestamp: wait_screen_data.display_to_timestamp,
+ poll_config: wait_screen_data.poll_config,
+ }
+ }));
+ if next_action_response.is_none() && !third_party_sdk_session {
+ next_action_response = match payment_data.get_authentication() {
+ Some(authentication_store) => {
+ let authentication = &authentication_store.authentication;
+ if payment_intent.status
+ == common_enums::IntentStatus::RequiresCustomerAction
+ && authentication_store.cavv.is_none()
+ && authentication.is_separate_authn_required()
+ {
+ // if preAuthn and separate authentication needed.
+ let poll_config =
+ payment_data.get_poll_config().unwrap_or_default();
+ let request_poll_id =
+ core_utils::get_external_authentication_request_poll_id(
+ &payment_intent.payment_id,
+ );
+ let connector = payment_attempt
+ .connector
+ .as_deref()
+ .get_required_value("connector")?;
+ let is_jwt_flow = authentication
+ .is_jwt_flow()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to determine if the authentication is JWT flow",
+ )?;
+ let three_ds_authorize_url = sdk_callback_urls
+ .authorize_url(
+ base_url,
+ callback_mode,
+ &payment_attempt.payment_id,
+ &payment_attempt.processor_merchant_id,
+ connector,
+ )
+ .clone();
+ let three_ds_authentication_url = Secret::new(format!(
+ "{base_url}/payments/{}/3ds/authentication",
+ payment_attempt.payment_id.get_string_repr(),
+ ));
+ Some(api_models::payments::NextActionData::ThreeDsInvoke {
three_ds_data: api_models::payments::ThreeDsData {
- three_ds_authentication_url: helpers::create_authentication_url(base_url, &payment_attempt),
- three_ds_authorize_url: helpers::create_authorize_url(
- base_url,
- &payment_attempt,
- payment_connector_name,
- ),
+ three_ds_authentication_url,
+ three_ds_authorize_url,
three_ds_method_details: authentication.three_ds_method_url.as_ref().zip(authentication.three_ds_method_data.as_ref()).map(|(three_ds_method_url,three_ds_method_data )|{
api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData {
three_ds_method_data_submission: true,
@@ -4251,23 +4486,25 @@ where
three_ds_connector: authentication.authentication_connector.clone(),
},
})
- }else{
- None
- }
- },
- None => None
- })
- .or(match next_action_invoke_hidden_frame{
- Some(threeds_invoke_data) => Some(construct_connector_invoke_hidden_frame(
- threeds_invoke_data,
- )?),
- None => None
- });
+ } else {
+ None
+ }
+ }
+ None => None,
+ };
+ }
+ next_action_response =
+ next_action_response.or(match next_action_invoke_hidden_frame {
+ Some(threeds_invoke_data) => Some(construct_connector_invoke_hidden_frame(
+ threeds_invoke_data,
+ )?),
+ None => None,
+ });
}
};
// next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response)
- if third_party_sdk_session_next_action(&payment_attempt, operation) {
+ if third_party_sdk_session {
next_action_response = Some(
api_models::payments::NextActionData::ThirdPartySdkSessionToken {
session_token: payment_data.get_sessions_token().first().cloned(),
@@ -4723,21 +4960,32 @@ pub fn next_action_invoke_hidden_frame(
}
pub fn next_action_invoke_ddc_iframe(
- payment_attempt: &storage::PaymentAttempt,
+ connector_metadata: Option<&serde_json::Value>,
base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ path: &StartCallbackPath,
+ sdk_callback_urls: &mut SdkCallbackUrls,
) -> RouterResult<Option<api_models::payments::PaymentConnectorInvokeDDCData>> {
let ddc_iframe_data: Option<
error_stack::Result<
api_models::payments::PaymentConnectorInvokeDDCData,
common_utils::errors::ParsingError,
>,
- > = payment_attempt.connector_metadata.clone().map(|metadata| {
+ > = connector_metadata.cloned().map(|metadata| {
let meta = metadata
.parse_value::<api_models::payments::PaymentConnectorInvokeDDCMetadata>(
"PaymentConnectorInvokeDDCData",
)?;
- let full_iframe_url = format!("{}{}", base_url, meta.iframe_url);
- let iframe_url = url::Url::parse(&full_iframe_url)
+ // Persisted iframe paths are legacy metadata; issue a fresh start URL
+ // through the response collector instead of returning that stored path.
+ let full_iframe_url = sdk_callback_urls.start_url(
+ base_url,
+ callback_mode,
+ &path.payment_id,
+ &path.merchant_id,
+ &path.attempt_id,
+ );
+ let iframe_url = url::Url::parse(full_iframe_url.peek())
.change_context(common_utils::errors::ParsingError::UrlParsingError)
.attach_printable("Failed to parse DDC iframe URL after joining with base_url")?;
Ok(api_models::payments::PaymentConnectorInvokeDDCData {
@@ -5304,12 +5552,13 @@ impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::paymen
}
}
-#[derive(Clone)]
pub struct PaymentAdditionalData<'a, F>
where
F: Clone,
{
+ callback_mode: PaymentCallbackMode,
router_base_url: String,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
connector_name: String,
payment_data: PaymentData<F>,
state: &'a SessionState,
@@ -5332,12 +5581,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.clone()
.map(types::BrowserInformation::from);
- let complete_authorize_url = Some(helpers::create_complete_authorize_url(
- router_base_url,
- attempt,
- connector_name,
- payment_data.creds_identifier.as_deref(),
- ));
+ let complete_authorize_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_complete_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let merchant_connector_account_id_or_connector_name = payment_data
.payment_attempt
@@ -5351,12 +5607,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
&attempt.processor_merchant_id,
merchant_connector_account_id_or_connector_name,
));
- let router_return_url = Some(helpers::create_redirect_url(
- router_base_url,
- attempt,
- connector_name,
- payment_data.creds_identifier.as_deref(),
- ));
+ let router_return_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_response_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let payment_method_data = payment_data.payment_method_data.or_else(|| {
if payment_data.mandate_id.is_some() {
@@ -5394,6 +5657,17 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
let shipping_cost = payment_data.payment_intent.amount_details.shipping_cost;
Ok(Self {
+ router_notification_url: additional_data.connector_callback_urls.notification_url(
+ api::ConnectorData::convert_connector(connector_name)?.get_notification_callback(),
+ router_base_url,
+ additional_data.callback_mode,
+ &ConnectorCallbackPath {
+ payment_id: attempt.payment_id.clone(),
+ merchant_id: attempt.processor_merchant_id.clone(),
+ connector: connector_name.clone(),
+ },
+ payment_data.creds_identifier.as_deref(),
+ ),
payment_method_data: payment_method_data
.unwrap_or(domain::PaymentMethodData::Card(domain::Card::default())),
amount,
@@ -5583,12 +5857,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
})
.transpose()?;
- let complete_authorize_url = Some(helpers::create_complete_authorize_url(
- router_base_url,
- attempt,
- connector_name,
- payment_data.creds_identifier.as_deref(),
- ));
+ let complete_authorize_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_complete_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let merchant_connector_account_id_or_connector_name = payment_data
.payment_attempt
@@ -5602,12 +5883,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
&attempt.processor_merchant_id,
merchant_connector_account_id_or_connector_name,
));
- let router_return_url = Some(helpers::create_redirect_url(
- router_base_url,
- attempt,
- connector_name,
- payment_data.creds_identifier.as_deref(),
- ));
+ let router_return_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_response_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_data.payment_attempt
@@ -5687,6 +5975,17 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.attach_printable("Failed to parse recipient details")?;
Ok(Self {
+ router_notification_url: additional_data.connector_callback_urls.notification_url(
+ api::ConnectorData::convert_connector(connector_name)?.get_notification_callback(),
+ router_base_url,
+ additional_data.callback_mode,
+ &ConnectorCallbackPath {
+ payment_id: attempt.payment_id.clone(),
+ merchant_id: attempt.processor_merchant_id.clone(),
+ connector: connector_name.clone(),
+ },
+ payment_data.creds_identifier.as_deref(),
+ ),
payment_method_data: (payment_method_data.get_required_value("payment_method_data")?),
setup_future_usage: payment_data
.payment_attempt
@@ -6475,15 +6774,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSess
.payment_intent
.merchant_order_reference_id
.clone();
- let router_base_url = &additional_data.router_base_url;
- let connector_name = &additional_data.connector_name;
- let attempt = &payment_data.payment_attempt;
- let router_return_url = Some(helpers::create_redirect_url(
- router_base_url,
- attempt,
- connector_name,
- payment_data.creds_identifier.as_deref(),
- ));
+ let router_return_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_response_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
Ok(Self {
amount, //need to change after we move to connector module
order_amount: payment_data.payment_intent.amount,
@@ -7308,12 +7611,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ
let router_base_url = &additional_data.router_base_url;
let connector_name = &additional_data.connector_name;
let attempt = &payment_data.payment_attempt;
- let router_return_url = Some(helpers::create_redirect_url(
- router_base_url,
- attempt,
- connector_name,
- payment_data.creds_identifier.as_deref(),
- ));
+ let router_return_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_response_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let browser_info: Option<types::BrowserInformation> = attempt
.browser_info
.clone()
@@ -7339,12 +7649,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ
&attempt.processor_merchant_id,
merchant_connector_account_id_or_connector_name,
));
- let complete_authorize_url = Some(helpers::create_complete_authorize_url(
- router_base_url,
- attempt,
- connector_name,
- payment_data.creds_identifier.as_deref(),
- ));
+ let complete_authorize_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_complete_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let connector = api_models::enums::Connector::from_str(connector_name)
.change_context(errors::ConnectorError::InvalidConnectorName)
@@ -7562,9 +7879,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz
.get_optional_feature_metadata()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse payment feature metadata")?;
- let router_base_url = &additional_data.router_base_url;
let connector_name = &additional_data.connector_name;
- let attempt = &payment_data.payment_attempt;
let browser_info: Option<types::BrowserInformation> = payment_data
.payment_attempt
.browser_info
@@ -7582,12 +7897,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz
}
});
let amount = payment_data.payment_attempt.get_total_amount();
- let complete_authorize_url = Some(helpers::create_complete_authorize_url(
- router_base_url,
- attempt,
- connector_name,
- payment_data.creds_identifier.as_deref(),
- ));
+ let complete_authorize_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_complete_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let braintree_metadata = payment_data
.payment_intent
.connector_metadata
@@ -7612,12 +7934,19 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz
payment_data.token_data.as_ref(),
);
- let router_return_url = Some(helpers::create_redirect_url(
- &additional_data.router_base_url.to_string(),
- &payment_data.payment_attempt,
- connector_name,
- payment_data.clone().get_creds_identifier(),
- ));
+ let router_return_url = Some(
+ additional_data
+ .connector_callback_urls
+ .redirect_response_url(
+ &additional_data.router_base_url,
+ additional_data.callback_mode,
+ &payment_data.payment_attempt.payment_id,
+ &payment_data.payment_attempt.processor_merchant_id,
+ &additional_data.connector_name,
+ payment_data.creds_identifier.as_deref(),
+ )
+ .clone(),
+ );
let recipient_details = payment_data
.payment_intent
@@ -8465,6 +8794,7 @@ pub async fn construct_payment_router_data_for_update_post_confirm<'a>(
connector_id: &str,
processor: &domain::Processor,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ connector_callback_urls: &'a mut ConnectorCallbackUrls,
) -> RouterResult<
types::RouterData<
api::UpdatePostConfirm,
@@ -8523,6 +8853,8 @@ pub async fn construct_payment_router_data_for_update_post_confirm<'a>(
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let additional_data = PaymentAdditionalData {
+ callback_mode: state.payment_callback_config().await?.mode,
+ connector_callback_urls,
router_base_url: state.base_url.clone(),
connector_name: connector_id.to_string(),
payment_data: payment_data.clone(),
diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rs
index 83d5859d0e..254e5abdcb 100644
--- a/crates/router/src/core/payments/vault_session.rs
+++ b/crates/router/src/core/payments/vault_session.rs
@@ -461,7 +461,7 @@ where
if should_call_connector {
// Create customer at connector and update the customer table to store this data
let router_data = payment_data
- .construct_router_data(
+ .construct_router_data_with_callbacks(
state,
connector.connector.id(),
processor,
diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rs
index b5ffca9e53..385572f188 100644
--- a/crates/router/src/core/unified_authentication_service.rs
+++ b/crates/router/src/core/unified_authentication_service.rs
@@ -45,7 +45,7 @@ use hyperswitch_domain_models::{
UasPreAuthenticationRouterData,
},
};
-use hyperswitch_masking::{ExposeInterface, PeekInterface};
+use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use super::{
errors::{RouterResponse, RouterResult},
@@ -408,7 +408,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {
message_category: MessageCategory,
device_channel: payments::DeviceChannel,
authentication: hyperswitch_domain_models::authentication::Authentication,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
@@ -464,7 +464,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {
message_category: MessageCategory,
device_channel: payments::DeviceChannel,
authentication: hyperswitch_domain_models::authentication::Authentication,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
@@ -588,7 +588,7 @@ pub async fn create_new_authentication(
acquirer_country_code: Option<String>,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<common_enums::Currency>,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
customer_details: Option<common_utils::encryption::Encryption>,
processor: &domain::Processor,
@@ -768,7 +768,7 @@ pub async fn authentication_create_core(
customer_details
.map(|details| {
common_utils::ext_traits::Encode::encode_to_value(&details)
- .map(hyperswitch_masking::Secret::<serde_json::Value>::new)
+ .map(Secret::<serde_json::Value>::new)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable(
"Unable to encode customer details to serde_json::Value",
@@ -937,9 +937,7 @@ impl
Ok(Self {
authentication_id: authentication.authentication_id,
- client_secret: authentication
- .authentication_client_secret
- .map(hyperswitch_masking::Secret::new),
+ client_secret: authentication.authentication_client_secret.map(Secret::new),
amount,
currency,
force_3ds_challenge: authentication.force_3ds_challenge,
@@ -1107,7 +1105,7 @@ pub async fn authentication_eligibility_core(
let notification_url = match authentication.return_url {
Some(ref url) => Some(
- url::Url::parse(url)
+ url::Url::parse(url.peek())
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse return url")?,
),
@@ -1274,7 +1272,7 @@ pub async fn authentication_eligibility_core(
three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id),
three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),
merchant_country_code: merchant_country_code.clone(),
- notification_url,
+ notification_url: notification_url.map(Into::into),
webhook_url:None
});
@@ -1498,7 +1496,7 @@ pub async fn authentication_authenticate_core(
.inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err))
.attach_printable("cavv not present after authentication status is success")?;
(
- Some(hyperswitch_masking::Secret::new(tokenised_data.value1)),
+ Some(Secret::new(tokenised_data.value1)),
authentication.eci.clone(),
)
} else {
@@ -1794,7 +1792,7 @@ pub async fn authentication_retrieve_eligibility_check_core(
impl
ForeignTryFrom<(
&hyperswitch_domain_models::authentication::Authentication,
- Option<hyperswitch_masking::Secret<String>>,
+ Option<Secret<String>>,
Option<String>,
diesel_models::business_profile::AuthenticationConnectorDetails,
)> for AuthenticationAuthenticateResponse
@@ -1804,7 +1802,7 @@ impl
fn foreign_try_from(
(authentication, authentication_value, eci, authentication_details): (
&hyperswitch_domain_models::authentication::Authentication,
- Option<hyperswitch_masking::Secret<String>>,
+ Option<Secret<String>>,
Option<String>,
diesel_models::business_profile::AuthenticationConnectorDetails,
),
@@ -2335,7 +2333,7 @@ pub async fn authentication_sync_core(
status: updated_authentication.authentication_status,
client_secret: updated_authentication
.authentication_client_secret
- .map(hyperswitch_masking::Secret::new),
+ .map(Secret::new),
amount,
currency,
authentication_connector,
@@ -2487,7 +2485,7 @@ pub async fn authentication_post_sync_core(
updated_authentication
.authentication_client_secret
.clone()
- .map(hyperswitch_masking::Secret::new)
+ .map(Secret::new)
.as_ref(),
updated_authentication.amount,
)?;
diff --git a/crates/router/src/core/unified_authentication_service/types.rs b/crates/router/src/core/unified_authentication_service/types.rs
index 282ff5b9e9..eee7537c59 100644
--- a/crates/router/src/core/unified_authentication_service/types.rs
+++ b/crates/router/src/core/unified_authentication_service/types.rs
@@ -11,6 +11,7 @@ use hyperswitch_domain_models::{
BrowserInformation,
},
};
+use hyperswitch_masking::Secret;
use crate::{
core::{errors::RouterResult, payments::helpers::MerchantConnectorAccountType},
@@ -89,7 +90,7 @@ pub trait UnifiedAuthenticationService {
_message_category: MessageCategory,
_device_channel: payments::DeviceChannel,
_authentication: hyperswitch_domain_models::authentication::Authentication,
- _return_url: Option<String>,
+ _return_url: Option<Secret<String>>,
_sdk_information: Option<payments::SdkInformation>,
_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
_email: Option<common_utils::pii::Email>,
@@ -117,7 +118,7 @@ pub trait UnifiedAuthenticationService {
_message_category: MessageCategory,
_device_channel: payments::DeviceChannel,
_authentication_data: hyperswitch_domain_models::authentication::Authentication,
- _return_url: Option<String>,
+ _return_url: Option<Secret<String>>,
_sdk_information: Option<payments::SdkInformation>,
_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
_email: Option<common_utils::pii::Email>,
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 2ffc618f7b..3e12065ad0 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -2778,7 +2778,7 @@ pub fn build_connector_feature_data_from_auth_mca(
merchant_connector_account: &MerchantConnectorAccountType,
force_3ds_challenge: Option<bool>,
results_response_notification_url: Option<String>,
- notification_url: Option<common_utils::types::Url>,
+ notification_url: Option<Secret<common_utils::types::Url>>,
acquirer_metadata: Option<serde_json::Value>,
) -> CustomResult<Option<Secret<String>>, UnifiedConnectorServiceError> {
merchant_connector_account
@@ -2801,7 +2801,7 @@ pub fn build_connector_feature_data_from_auth_mca(
if let Some(url) = notification_url {
obj.insert(
"notification_url".to_string(),
- serde_json::Value::String(url.get_string_repr().to_string()),
+ serde_json::Value::String(url.peek().get_string_repr().to_string()),
);
}
if let Some(serde_json::Value::Object(acquirer)) = acquirer_metadata {
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index 611949264e..907ae9288c 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -779,7 +779,11 @@ impl
address: Some(address),
metadata: None,
connector_feature_data: None,
- return_url: router_data.request.router_return_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
test_mode: router_data.test_mode,
customer: Some(payments_grpc::Customer {
first_name: None,
@@ -955,7 +959,11 @@ impl
currency: currency.into(),
}),
payment_method: Some(payment_method),
- return_url: router_data.request.router_return_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
address: Some(address),
auth_type: auth_type.into(),
enrolled_for_3ds: Some(router_data.request.enrolled_for_3ds),
@@ -999,7 +1007,11 @@ impl
.map(|order_tax_amount| order_tax_amount.get_amount_as_i64()),
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: router_data.request.webhook_url.clone(),
- complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ complete_authorize_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
setup_future_usage: setup_future_usage.map(|s| s.into()),
off_session: router_data.request.off_session,
is_stored_credential: router_data.request.is_stored_credential,
@@ -1063,7 +1075,11 @@ impl
.map(|payment_channel| payment_channel.into()),
connector_feature_data: get_nuvei_previous_leg_feature_data(router_data)?,
locale: router_data.request.locale.clone(),
- continue_redirection_url: router_data.request.complete_authorize_url.clone(),
+ continue_redirection_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
redirection_response: None,
threeds_completion_indicator: None,
tokenization_strategy: router_data
@@ -1253,7 +1269,11 @@ impl
currency: currency.into(),
}),
payment_method,
- return_url: router_data.request.router_return_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
address: Some(address),
auth_type: auth_type.into(),
enrolled_for_3ds: Some(true),
@@ -1290,7 +1310,11 @@ impl
order_tax_amount: None,
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: None,
- complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ complete_authorize_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
setup_future_usage: setup_future_usage.map(|s| s.into()),
off_session: router_data.request.off_session,
is_stored_credential: router_data.request.is_stored_credential,
@@ -1343,7 +1367,11 @@ impl
.as_ref()
.map(payments_grpc::BillingDescriptor::foreign_from),
locale: None,
- continue_redirection_url: router_data.request.complete_authorize_url.clone(),
+ continue_redirection_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
redirection_response: router_data
.request
.redirect_response
@@ -1842,8 +1870,16 @@ impl
address: Some(address),
authentication_data,
metadata: None,
- return_url: router_data.request.router_return_url.clone(),
- continue_redirection_url: router_data.request.complete_authorize_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
+ continue_redirection_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
state: None,
redirection_response: router_data
.request
@@ -1972,8 +2008,16 @@ impl
.attach_printable("Failed to serialize device_channel/sdk_information metadata")?
.into(),
),
- return_url: router_data.request.router_return_url.clone(),
- continue_redirection_url: router_data.request.complete_authorize_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
+ continue_redirection_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
state: None,
redirection_response: router_data
.request
@@ -2303,8 +2347,16 @@ impl
address: Some(address),
enrolled_for_3ds: router_data.request.enrolled_for_3ds,
metadata,
- return_url: router_data.request.router_return_url.clone(),
- continue_redirection_url: router_data.request.complete_authorize_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
+ continue_redirection_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
state,
browser_info: router_data
.request
@@ -2415,8 +2467,16 @@ impl
address: Some(address),
enrolled_for_3ds: router_data.request.enrolled_for_3ds,
metadata,
- return_url: router_data.request.router_return_url.clone(),
- continue_redirection_url: router_data.request.complete_authorize_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
+ continue_redirection_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
state: None,
browser_info: router_data
.request
@@ -2648,7 +2708,11 @@ impl
}),
billing_descriptor: None,
payment_method,
- return_url: router_data.request.complete_authorize_url.clone(),
+ return_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
address: Some(address),
auth_type: auth_type.into(),
enrolled_for_3ds: Some(false),
@@ -2680,7 +2744,11 @@ impl
order_tax_amount: None,
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: None, // CompleteAuthorize doesn't have webhook_url
- complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ complete_authorize_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
setup_future_usage: router_data
.request
.setup_future_usage
@@ -2843,7 +2911,11 @@ impl
currency: currency.into(),
}),
payment_method: Some(payment_method),
- return_url: router_data.request.router_return_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
address: Some(address),
auth_type: auth_type.into(),
enrolled_for_3ds: Some(router_data.request.enrolled_for_3ds),
@@ -2887,7 +2959,11 @@ impl
}),
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: router_data.request.webhook_url.clone(),
- complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ complete_authorize_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
setup_future_usage: setup_future_usage.map(|s| s.into()),
off_session: router_data.request.off_session,
is_stored_credential: router_data.request.is_stored_credential,
@@ -3059,7 +3135,11 @@ impl
}),
billing_descriptor: None,
payment_method,
- return_url: router_data.request.router_return_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
address: Some(address),
auth_type: auth_type.into(),
enrolled_for_3ds: Some(router_data.request.enrolled_for_3ds),
@@ -3104,7 +3184,11 @@ impl
.map(|order_tax_amount| order_tax_amount.get_amount_as_i64()),
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: router_data.request.webhook_url.clone(),
- complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ complete_authorize_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
setup_future_usage: setup_future_usage.map(|s| s.into()),
off_session: router_data.request.off_session,
is_stored_credential: None,
@@ -3332,9 +3416,17 @@ impl
.transpose()
.change_context(UnifiedConnectorServiceError::RequestEncodingFailed)?
.map(|s| s.into()),
- return_url: router_data.request.router_return_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
webhook_url: router_data.request.webhook_url.clone(),
- complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ complete_authorize_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
session_token: router_data.session_token.clone(),
order_tax_amount: None,
order_category: router_data
@@ -3572,7 +3664,11 @@ impl
test_mode: router_data.test_mode,
payment_method_type,
state,
- return_url: router_data.request.router_return_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
description: router_data.description.clone(),
connector_customer_id: router_data.connector_customer.clone(),
address: Some(address),
@@ -3629,7 +3725,11 @@ impl
}),
additional_payment_data,
auth_type: Some(auth_type.into()),
- complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ complete_authorize_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
split_payments: router_data
.request
.split_payments
@@ -3860,7 +3960,11 @@ impl
test_mode: router_data.test_mode,
payment_method_type,
state,
- return_url: router_data.request.router_return_url.clone(),
+ return_url: router_data
+ .request
+ .router_return_url
+ .clone()
+ .map(ExposeInterface::expose),
description: router_data.description.clone(),
connector_customer_id: router_data.connector_customer.clone(),
address: Some(address),
@@ -3957,7 +4061,11 @@ impl
auth_type: Some(auth_type.into()),
// Provide the HS complete-authorize URL so a wallet MIT that needs buyer
// re-approval returns to HS (→ CompleteAuthorize) rather than the merchant URL.
- complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ complete_authorize_url: router_data
+ .request
+ .complete_authorize_url
+ .clone()
+ .map(ExposeInterface::expose),
payment_channel: router_data
.request
.payment_channel
@@ -11891,92 +11999,4 @@ impl
}
#[cfg(test)]
-mod ucs_embedded_error_tests {
- #[cfg(feature = "payouts")]
- use common_enums::PayoutStatus;
- use hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData;
-
- use super::{payments_grpc, ErrorResponse, PayoutsResponseData};
- use crate::types::transformers::ForeignTryFrom;
-
- fn connector_error() -> payments_grpc::ErrorInfo {
- payments_grpc::ErrorInfo {
- connector_details: Some(payments_grpc::ConnectorErrorDetails {
- code: Some("connector_error".to_string()),
- message: Some("connector rejected the request".to_string()),
- reason: Some("invalid request".to_string()),
- ..Default::default()
- }),
- ..Default::default()
- }
- }
-
- #[cfg(feature = "payouts")]
- #[test]
- fn payout_connector_http_error_maps_to_error_response() {
- let response = payments_grpc::PayoutServiceTransferResponse {
- payout_status: Some(payments_grpc::payout_enums::PayoutStatus::Failed.into()),
- connector_payout_id: Some("connector-payout-id".to_string()),
- error: Some(connector_error()),
- status_code: 422,
- ..Default::default()
- };
-
- let result =
- <Result<PayoutsResponseData, ErrorResponse> as ForeignTryFrom<_>>::foreign_try_from((
- response,
- PayoutStatus::Pending,
- ))
- .expect("the UCS payout response should be parseable");
- let error = result.expect_err("connector HTTP errors must use RouterData's error path");
-
- assert_eq!(error.status_code, 422);
- assert_eq!(error.code, "connector_error");
- assert_eq!(
- error.connector_transaction_id.as_deref(),
- Some("connector-payout-id")
- );
- }
-
- #[cfg(feature = "payouts")]
- #[test]
- fn payout_http_success_preserves_business_failure_status() {
- let response = payments_grpc::PayoutServiceTransferResponse {
- payout_status: Some(payments_grpc::payout_enums::PayoutStatus::Failed.into()),
- connector_payout_id: Some("connector-payout-id".to_string()),
- error: Some(connector_error()),
- status_code: 200,
- ..Default::default()
- };
-
- let result =
- <Result<PayoutsResponseData, ErrorResponse> as ForeignTryFrom<_>>::foreign_try_from((
- response,
- PayoutStatus::Pending,
- ))
- .expect("the UCS payout response should be parseable");
- let response = result.expect("HTTP-success business failures retain payout status");
-
- assert_eq!(response.status, Some(PayoutStatus::Failed));
- assert_eq!(response.error_code.as_deref(), Some("connector_error"));
- }
-
- #[test]
- fn surcharge_connector_error_is_not_defaulted_to_zero() {
- let response = payments_grpc::SurchargeServiceCalculateResponse {
- connector_surcharge_id: Some("connector-surcharge-id".to_string()),
- status_code: 502,
- error: Some(connector_error()),
- ..Default::default()
- };
-
- let result = <Result<SurchargeCalculationResponseData, ErrorResponse> as ForeignTryFrom<
- _,
- >>::foreign_try_from(response)
- .expect("the UCS surcharge response should be parseable");
- let error = result.expect_err("connector errors must not become a zero surcharge");
-
- assert_eq!(error.status_code, 502);
- assert_eq!(error.code, "connector_error");
- }
-}
+mod tests;
diff --git a/crates/router/src/core/unified_connector_service/transformers/tests.rs b/crates/router/src/core/unified_connector_service/transformers/tests.rs
new file mode 100644
index 0000000000..f9936bbc85
--- /dev/null
+++ b/crates/router/src/core/unified_connector_service/transformers/tests.rs
@@ -0,0 +1,87 @@
+#[cfg(feature = "payouts")]
+use common_enums::PayoutStatus;
+use hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData;
+
+use super::{payments_grpc, ErrorResponse, PayoutsResponseData};
+use crate::types::transformers::ForeignTryFrom;
+
+fn connector_error() -> payments_grpc::ErrorInfo {
+ payments_grpc::ErrorInfo {
+ connector_details: Some(payments_grpc::ConnectorErrorDetails {
+ code: Some("connector_error".to_string()),
+ message: Some("connector rejected the request".to_string()),
+ reason: Some("invalid request".to_string()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+}
+
+#[cfg(feature = "payouts")]
+#[test]
+fn payout_connector_http_error_maps_to_error_response() {
+ let response = payments_grpc::PayoutServiceTransferResponse {
+ payout_status: Some(payments_grpc::payout_enums::PayoutStatus::Failed.into()),
+ connector_payout_id: Some("connector-payout-id".to_string()),
+ error: Some(connector_error()),
+ status_code: 422,
+ ..Default::default()
+ };
+
+ let result =
+ <Result<PayoutsResponseData, ErrorResponse> as ForeignTryFrom<_>>::foreign_try_from((
+ response,
+ PayoutStatus::Pending,
+ ))
+ .expect("the UCS payout response should be parseable");
+ let error = result.expect_err("connector HTTP errors must use RouterData's error path");
+
+ assert_eq!(error.status_code, 422);
+ assert_eq!(error.code, "connector_error");
+ assert_eq!(
+ error.connector_transaction_id.as_deref(),
+ Some("connector-payout-id")
+ );
+}
+
+#[cfg(feature = "payouts")]
+#[test]
+fn payout_http_success_preserves_business_failure_status() {
+ let response = payments_grpc::PayoutServiceTransferResponse {
+ payout_status: Some(payments_grpc::payout_enums::PayoutStatus::Failed.into()),
+ connector_payout_id: Some("connector-payout-id".to_string()),
+ error: Some(connector_error()),
+ status_code: 200,
+ ..Default::default()
+ };
+
+ let result =
+ <Result<PayoutsResponseData, ErrorResponse> as ForeignTryFrom<_>>::foreign_try_from((
+ response,
+ PayoutStatus::Pending,
+ ))
+ .expect("the UCS payout response should be parseable");
+ let response = result.expect("HTTP-success business failures retain payout status");
+
+ assert_eq!(response.status, Some(PayoutStatus::Failed));
+ assert_eq!(response.error_code.as_deref(), Some("connector_error"));
+}
+
+#[test]
+fn surcharge_connector_error_is_not_defaulted_to_zero() {
+ let response = payments_grpc::SurchargeServiceCalculateResponse {
+ connector_surcharge_id: Some("connector-surcharge-id".to_string()),
+ status_code: 502,
+ error: Some(connector_error()),
+ ..Default::default()
+ };
+
+ let result = <Result<SurchargeCalculationResponseData, ErrorResponse> as ForeignTryFrom<
+ _,
+ >>::foreign_try_from(response)
+ .expect("the UCS surcharge response should be parseable");
+ let error = result.expect_err("connector errors must not become a zero surcharge");
+
+ assert_eq!(error.status_code, 502);
+ assert_eq!(error.code, "connector_error");
+}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 38cc569a25..ecd6505494 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -3054,7 +3054,7 @@ pub async fn get_sso_auth_url(
return_url: String::new(),
http_method: String::new(),
params: Vec::with_capacity(0),
- return_url_with_query_params: url.to_string(),
+ return_url_with_query_params: url.to_string().into(),
})
})
}
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index dbd22f5abe..905d8925fa 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -1129,106 +1129,7 @@ pub fn get_split_refunds(
}
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn validate_id_length_constraint() {
- let payment_id =
- "abcdefghijlkmnopqrstuvwzyzabcdefghijknlmnopsjkdnfjsknfkjsdnfspoig".to_string(); //length = 65
-
- let result = validate_id(payment_id, "payment_id");
- assert!(result.is_err());
- }
-
- #[test]
- fn validate_id_proper_response() {
- let payment_id = "abcdefghijlkmnopqrstjhbjhjhkhbhgcxdfxvmhb".to_string();
-
- let result = validate_id(payment_id.clone(), "payment_id");
- assert!(result.is_ok());
- let result = result.unwrap_or_default();
- assert_eq!(result, payment_id);
- }
-
- #[test]
- fn test_generate_id() {
- let generated_id = generate_id(consts::ID_LENGTH, "ref");
- assert_eq!(generated_id.len(), consts::ID_LENGTH + 4)
- }
-
- #[test]
- fn test_filter_objects_based_on_profile_id_list() {
- #[derive(PartialEq, Debug, Clone)]
- struct Object {
- profile_id: Option<common_utils::id_type::ProfileId>,
- }
-
- impl Object {
- pub fn new(profile_id: &'static str) -> Self {
- Self {
- profile_id: Some(
- common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(
- profile_id,
- ))
- .expect("invalid profile ID"),
- ),
- }
- }
- }
-
- impl GetProfileId for Object {
- fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
- self.profile_id.as_ref()
- }
- }
-
- fn new_profile_id(profile_id: &'static str) -> common_utils::id_type::ProfileId {
- common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(profile_id))
- .expect("invalid profile ID")
- }
-
- // non empty object_list and profile_id_list
- let object_list = vec![
- Object::new("p1"),
- Object::new("p2"),
- Object::new("p2"),
- Object::new("p4"),
- Object::new("p5"),
- ];
- let profile_id_list = vec![
- new_profile_id("p1"),
- new_profile_id("p2"),
- new_profile_id("p3"),
- ];
- let filtered_list =
- filter_objects_based_on_profile_id_list(Some(profile_id_list), object_list.clone());
- let expected_result = vec![Object::new("p1"), Object::new("p2"), Object::new("p2")];
- assert_eq!(filtered_list, expected_result);
-
- // non empty object_list and empty profile_id_list
- let empty_profile_id_list = vec![];
- let filtered_list = filter_objects_based_on_profile_id_list(
- Some(empty_profile_id_list),
- object_list.clone(),
- );
- let expected_result = vec![];
- assert_eq!(filtered_list, expected_result);
-
- // non empty object_list and None profile_id_list
- let profile_id_list_as_none = None;
- let filtered_list =
- filter_objects_based_on_profile_id_list(profile_id_list_as_none, object_list);
- let expected_result = vec![
- Object::new("p1"),
- Object::new("p2"),
- Object::new("p2"),
- Object::new("p4"),
- Object::new("p5"),
- ];
- assert_eq!(filtered_list, expected_result);
- }
-}
+mod tests;
// Dispute Stage can move linearly from PreDispute -> Dispute -> PreArbitration -> Arbitration -> DisputeReversal
pub fn validate_dispute_stage(
@@ -2552,9 +2453,10 @@ pub fn get_modular_authentication_request_poll_id(
}
pub fn get_html_redirect_response_after_ddc(
- return_url_with_query_params: String,
+ return_url_with_query_params: Secret<String>,
redirect_mode: &str, // "required" or "if_required"
-) -> RouterResult<String> {
+) -> RouterResult<Secret<String>> {
+ let return_url_with_query_params = return_url_with_query_params.peek();
Ok(html! {
head {
title { "Redirect Form" }
@@ -2593,12 +2495,14 @@ pub fn get_html_redirect_response_after_ddc(
"#)))
}
}
- .into_string())
+ .into_string()
+ .into())
}
pub fn get_html_redirect_response_popup(
- return_url_with_query_params: String,
-) -> RouterResult<String> {
+ return_url_with_query_params: Secret<String>,
+) -> RouterResult<Secret<String>> {
+ let return_url_with_query_params = return_url_with_query_params.peek();
Ok(html! {
head {
title { "Redirect Form" }
@@ -2626,16 +2530,17 @@ pub fn get_html_redirect_response_popup(
"#)))
}
}
- .into_string())
+ .into_string().into())
}
#[cfg(feature = "v1")]
pub fn get_html_redirect_response_for_external_authentication(
- return_url_with_query_params: String,
+ return_url_with_query_params: Secret<String>,
payment_response: &api_models::payments::PaymentsResponse,
payment_id: common_utils::id_type::PaymentId,
poll_config: &PollConfig,
-) -> RouterResult<String> {
+) -> RouterResult<Secret<String>> {
+ let return_url_with_query_params = return_url_with_query_params.peek();
// if intent_status is requires_customer_action then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url
let html = match payment_response.status {
IntentStatus::RequiresCustomerAction => {
@@ -2709,16 +2614,17 @@ pub fn get_html_redirect_response_for_external_authentication(
.into_string()
},
};
- Ok(html)
+ Ok(html.into())
}
#[cfg(feature = "v1")]
pub fn get_html_redirect_response_for_external_modular_authentication(
- return_url_with_query_params: String,
+ return_url_with_query_params: Secret<String>,
authentication_response: &api_models::authentication::AuthenticationResponse,
authentication_id: common_utils::id_type::AuthenticationId,
poll_config: &PollConfig,
-) -> RouterResult<String> {
+) -> RouterResult<Secret<String>> {
+ let return_url_with_query_params = return_url_with_query_params.peek();
// if authentication_status is pending then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url
let html = match authentication_response.status {
common_enums::AuthenticationStatus::Pending => {
@@ -2792,7 +2698,7 @@ pub fn get_html_redirect_response_for_external_modular_authentication(
.into_string()
},
};
- Ok(html)
+ Ok(html.into())
}
#[inline]
diff --git a/crates/router/src/core/utils/tests.rs b/crates/router/src/core/utils/tests.rs
new file mode 100644
index 0000000000..2dade0c711
--- /dev/null
+++ b/crates/router/src/core/utils/tests.rs
@@ -0,0 +1,94 @@
+use super::*;
+
+#[test]
+fn validate_id_length_constraint() {
+ let payment_id =
+ "abcdefghijlkmnopqrstuvwzyzabcdefghijknlmnopsjkdnfjsknfkjsdnfspoig".to_string(); //length = 65
+
+ let result = validate_id(payment_id, "payment_id");
+ assert!(result.is_err());
+}
+
+#[test]
+fn validate_id_proper_response() {
+ let payment_id = "abcdefghijlkmnopqrstjhbjhjhkhbhgcxdfxvmhb".to_string();
+
+ let result = validate_id(payment_id.clone(), "payment_id");
+ assert!(result.is_ok());
+ let result = result.unwrap_or_default();
+ assert_eq!(result, payment_id);
+}
+
+#[test]
+fn test_generate_id() {
+ let generated_id = generate_id(consts::ID_LENGTH, "ref");
+ assert_eq!(generated_id.len(), consts::ID_LENGTH + 4)
+}
+
+#[test]
+fn test_filter_objects_based_on_profile_id_list() {
+ #[derive(PartialEq, Debug, Clone)]
+ struct Object {
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ }
+
+ impl Object {
+ pub fn new(profile_id: &'static str) -> Self {
+ Self {
+ profile_id: Some(
+ common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(profile_id))
+ .expect("invalid profile ID"),
+ ),
+ }
+ }
+ }
+
+ impl GetProfileId for Object {
+ fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
+ self.profile_id.as_ref()
+ }
+ }
+
+ fn new_profile_id(profile_id: &'static str) -> common_utils::id_type::ProfileId {
+ common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(profile_id))
+ .expect("invalid profile ID")
+ }
+
+ // non empty object_list and profile_id_list
+ let object_list = vec![
+ Object::new("p1"),
+ Object::new("p2"),
+ Object::new("p2"),
+ Object::new("p4"),
+ Object::new("p5"),
+ ];
+ let profile_id_list = vec![
+ new_profile_id("p1"),
+ new_profile_id("p2"),
+ new_profile_id("p3"),
+ ];
+ let filtered_list =
+ filter_objects_based_on_profile_id_list(Some(profile_id_list), object_list.clone());
+ let expected_result = vec![Object::new("p1"), Object::new("p2"), Object::new("p2")];
+ assert_eq!(filtered_list, expected_result);
+
+ // non empty object_list and empty profile_id_list
+ let empty_profile_id_list = vec![];
+ let filtered_list =
+ filter_objects_based_on_profile_id_list(Some(empty_profile_id_list), object_list.clone());
+ let expected_result = vec![];
+ assert_eq!(filtered_list, expected_result);
+
+ // non empty object_list and None profile_id_list
+ let profile_id_list_as_none = None;
+ let filtered_list =
+ filter_objects_based_on_profile_id_list(profile_id_list_as_none, object_list);
+ let expected_result = vec![
+ Object::new("p1"),
+ Object::new("p2"),
+ Object::new("p2"),
+ Object::new("p4"),
+ Object::new("p5"),
+ ];
+ assert_eq!(filtered_list, expected_result);
+}
diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs
index f18685e46c..2de62a932a 100644
--- a/crates/router/src/events/api_logs.rs
+++ b/crates/router/src/events/api_logs.rs
@@ -89,7 +89,7 @@ impl ApiEvent {
.headers()
.get("user-agent")
.and_then(|user_agent_value| user_agent_value.to_str().ok().map(ToOwned::to_owned)),
- url_path: http_req.path().to_string(),
+ url_path: router_env::request_path::path_for_telemetry(http_req).into_owned(),
event_type,
hs_latency,
http_method: http_method.to_string(),
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 5e0fda646b..2951013d67 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -413,6 +413,11 @@ pub async fn start_server(
errors::ApplicationError::ApiClientError(error.current_context().clone())
})?);
let state = Box::pin(AppState::new(conf, tx, api_client, service_name)).await;
+ core::configs::payment_callback::PaymentCallbackConfig::validate_at_startup(&state)
+ .await
+ .map_err(|error| {
+ errors::ApplicationError::InvalidConfigurationValueError(format!("{error:?}"))
+ })?;
// Spawn a thread for collecting metrics at fixed intervals. It has to run against the
// caches the state built, not a set of its own.
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 7d14a7b85b..f30b477389 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -36,7 +36,7 @@ use storage_impl::{
redis::{cache::Caches, RedisStore},
MockDb,
};
-use tokio::sync::oneshot;
+use tokio::sync::{oneshot, OnceCell};
use self::settings::Tenant;
#[cfg(all(feature = "v2", feature = "oltp"))]
@@ -94,8 +94,6 @@ use crate::analytics::routes::{
};
#[cfg(feature = "olap")]
use crate::analytics::AnalyticsProvider;
-#[cfg(feature = "partial-auth")]
-use crate::errors::RouterResult;
#[cfg(feature = "oltp")]
use crate::routes::authentication;
#[cfg(feature = "v1")]
@@ -120,7 +118,9 @@ pub use crate::{
};
use crate::{
configs::{secrets_transformers, Settings},
+ core::configs::payment_callback::PaymentCallbackConfig,
db::kafka_store::{KafkaStore, TenantID},
+ errors::RouterResult,
routes::{hypersense as hypersense_routes, three_ds_decision_rule},
};
@@ -157,6 +157,7 @@ pub struct SessionState {
pub superposition_service: Arc<SuperpositionClient>,
/// Bounded request context used to correlate v1 payment I/O metrics.
pub payment_metrics_context: Option<PaymentMetricsContext>,
+ payment_callback_config: Arc<OnceCell<PaymentCallbackConfig>>,
}
impl scheduler::SchedulerSessionState for SessionState {
fn get_db(&self) -> Box<dyn SchedulerInterface> {
@@ -183,6 +184,13 @@ impl scheduler::SchedulerSessionState for SessionState {
}
}
impl SessionState {
+ /// Resolve the runtime callback policy once for this request and its clones.
+ pub async fn payment_callback_config(&self) -> RouterResult<&PaymentCallbackConfig> {
+ self.payment_callback_config
+ .get_or_try_init(|| PaymentCallbackConfig::load(self))
+ .await
+ }
+
pub fn set_store(&mut self, store: Box<dyn StorageInterface>) {
self.store = store;
}
@@ -752,6 +760,7 @@ impl AppState {
enhancement: self.enhancement.clone(),
superposition_service: self.superposition_service.clone(),
payment_metrics_context: None,
+ payment_callback_config: Arc::default(),
})
}
@@ -1021,6 +1030,17 @@ impl Proxy {
}
}
+#[cfg(feature = "v1")]
+fn configure_payment_callback_routes(config: &mut web::ServiceConfig) {
+ use strum::IntoEnumIterator;
+
+ use super::payments::callback_routes::PaymentCallbackRoute;
+
+ for callback in PaymentCallbackRoute::iter() {
+ config.service(callback.resource());
+ }
+}
+
#[cfg(feature = "v1")]
impl Payments {
pub fn server(state: AppState) -> Scope {
@@ -1089,9 +1109,14 @@ impl Payments {
}
#[cfg(feature = "oltp")]
{
+ use super::payments::callback_routes::PaymentCallbackRoute;
+
route = route
.service(web::resource("").route(web::post().to(payments::payments_create)))
- .service(web::resource("/payment_link").route(web::post().to(payments::payment_link_create)))
+ .service(
+ web::resource("/payment_link")
+ .route(web::post().to(payments::payment_link_create)),
+ )
.service(
web::resource("/session_tokens")
.route(web::post().to(payments::payments_connector_session)),
@@ -1106,21 +1131,25 @@ impl Payments {
.route(web::post().to(payments::payments_update)),
)
.service(
- web::resource("/{payment_id}/post_session_tokens").route(web::post().to(payments::payments_post_session_tokens)),
+ web::resource("/{payment_id}/post_session_tokens")
+ .route(web::post().to(payments::payments_post_session_tokens)),
)
.service(
- web::resource("/{payment_id}/confirm").route(web::post().to(payments::payments_confirm)),
+ web::resource("/{payment_id}/confirm")
+ .route(web::post().to(payments::payments_confirm)),
)
.service(
- web::resource("/{payment_id}/cancel").route(web::post().to(payments::payments_cancel)),
+ web::resource("/{payment_id}/cancel")
+ .route(web::post().to(payments::payments_cancel)),
)
.service(
web::resource("/{payment_id}/cancel_post_capture")
- .route(web::post().to(payments::payments_cancel_post_capture))
- .route(web::get().to(payments::payments_cancel_post_capture_retrieve))
+ .route(web::post().to(payments::payments_cancel_post_capture))
+ .route(web::get().to(payments::payments_cancel_post_capture_retrieve)),
)
.service(
- web::resource("/{payment_id}/capture").route(web::post().to(payments::payments_capture)),
+ web::resource("/{payment_id}/capture")
+ .route(web::post().to(payments::payments_capture)),
)
.service(
web::resource("/{payment_id}/approve")
@@ -1134,63 +1163,43 @@ impl Payments {
web::resource("/{payment_id}/eligibility_check")
.route(web::post().to(payments::payments_submit_eligibility_check)),
)
- .service(
- web::resource("/{payment_id}/client")
- .route(web::get().to(payment_methods::list_payment_methods_for_payments_client)),
- )
+ .service(web::resource("/{payment_id}/client").route(
+ web::get().to(payment_methods::list_payment_methods_for_payments_client),
+ ))
.service(
web::resource("/{payment_id}/eligibility")
.route(web::post().to(payments::payments_submit_eligibility)),
)
+ .configure(configure_payment_callback_routes)
+ .service(PaymentCallbackRoute::Start.legacy_resource())
+ .service(PaymentCallbackRoute::RedirectResponse.legacy_resource())
+ .service(PaymentCallbackRoute::RedirectResponseWithCredentials.legacy_resource())
+ .service(PaymentCallbackRoute::RedirectComplete.legacy_resource())
+ .service(PaymentCallbackRoute::RedirectCompleteWithCredentials.legacy_resource())
+ .service(PaymentCallbackRoute::Authorize.legacy_resource())
.service(
- web::resource("/redirect/{payment_id}/{merchant_id}/{attempt_id}")
- .route(web::get().to(payments::payments_start)),
- )
- .service(
- web::resource(
- "/{payment_id}/{merchant_id}/redirect/response/{connector}/{creds_identifier}",
- )
- .route(web::get().to(payments::payments_redirect_response_with_creds_identifier)),
- )
- .service(
- web::resource("/{payment_id}/{merchant_id}/redirect/response/{connector}")
- .route(web::get().to(payments::payments_redirect_response))
- .route(web::post().to(payments::payments_redirect_response))
- )
- .service(
- web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}/{creds_identifier}")
- .route(web::get().to(payments::payments_complete_authorize_redirect_with_creds_identifier))
- .route(web::post().to(payments::payments_complete_authorize_redirect_with_creds_identifier))
- )
- .service(
- web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}")
- .route(web::get().to(payments::payments_complete_authorize_redirect))
- .route(web::post().to(payments::payments_complete_authorize_redirect)),
+ web::resource("/{payment_id}/3ds/authentication")
+ .route(web::post().to(payments::payments_external_authentication)),
)
.service(
web::resource("/{payment_id}/complete_authorize")
.route(web::post().to(payments::payments_complete_authorize)),
)
.service(
- web::resource("/{payment_id}/incremental_authorization").route(web::post().to(payments::payments_incremental_authorization)),
- )
- .service(
- web::resource("/{payment_id}/extend_authorization").route(web::post().to(payments::payments_extend_authorization)),
- )
- .service(
- web::resource("/{payment_id}/{merchant_id}/authorize/{connector}")
- .route(web::post().to(payments::post_3ds_payments_authorize))
- .route(web::get().to(payments::post_3ds_payments_authorize))
+ web::resource("/{payment_id}/incremental_authorization")
+ .route(web::post().to(payments::payments_incremental_authorization)),
)
.service(
- web::resource("/{payment_id}/3ds/authentication").route(web::post().to(payments::payments_external_authentication)),
+ web::resource("/{payment_id}/extend_authorization")
+ .route(web::post().to(payments::payments_extend_authorization)),
)
.service(
- web::resource("/{payment_id}/extended_card_info").route(web::get().to(payments::retrieve_extended_card_info)),
+ web::resource("/{payment_id}/extended_card_info")
+ .route(web::get().to(payments::retrieve_extended_card_info)),
)
.service(
- web::resource("{payment_id}/calculate_tax")
- .route(web::post().to(payments::payments_dynamic_tax_calculation)),
+ web::resource("{payment_id}/calculate_tax")
+ .route(web::post().to(payments::payments_dynamic_tax_calculation)),
)
.service(
web::resource("{payment_id}/update_metadata")
diff --git a/crates/router/src/routes/dummy_connector/core.rs b/crates/router/src/routes/dummy_connector/core.rs
index 0d7fb9627c..4e43318219 100644
--- a/crates/router/src/routes/dummy_connector/core.rs
+++ b/crates/router/src/routes/dummy_connector/core.rs
@@ -130,7 +130,7 @@ pub async fn payment_complete(
params: vec![],
return_url_with_query_params: updated_payment_data
.return_url
- .unwrap_or(state.conf.dummy_connector.default_return_url.clone()),
+ .unwrap_or(state.conf.dummy_connector.default_return_url.clone().into()),
http_method: "GET".to_string(),
headers: vec![],
},
@@ -140,7 +140,12 @@ pub async fn payment_complete(
api_models::payments::RedirectionResponse {
return_url: String::new(),
params: vec![],
- return_url_with_query_params: state.conf.dummy_connector.default_return_url.clone(),
+ return_url_with_query_params: state
+ .conf
+ .dummy_connector
+ .default_return_url
+ .clone()
+ .into(),
http_method: "GET".to_string(),
headers: vec![],
},
diff --git a/crates/router/src/routes/dummy_connector/types.rs b/crates/router/src/routes/dummy_connector/types.rs
index 9167612285..ec640480ca 100644
--- a/crates/router/src/routes/dummy_connector/types.rs
+++ b/crates/router/src/routes/dummy_connector/types.rs
@@ -93,7 +93,7 @@ impl DummyConnectorPaymentAttempt {
self,
status: DummyConnectorStatus,
next_action: Option<DummyConnectorNextAction>,
- return_url: Option<String>,
+ return_url: Option<Secret<String>>,
) -> DummyConnectorPaymentData {
DummyConnectorPaymentData {
attempt_id: self.attempt_id,
@@ -116,7 +116,7 @@ pub struct DummyConnectorPaymentRequest {
pub amount: i64,
pub currency: Currency,
pub payment_method_data: DummyConnectorPaymentMethodData,
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
pub connector: DummyConnectors,
}
@@ -295,7 +295,7 @@ pub struct DummyConnectorPaymentData {
pub payment_method_type: DummyConnectorPaymentMethodType,
pub connector: DummyConnectors,
pub next_action: Option<DummyConnectorNextAction>,
- pub return_url: Option<String>,
+ pub return_url: Option<Secret<String>>,
}
impl DummyConnectorPaymentData {
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index b1220fad89..e281bb9ad7 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -1,6 +1,10 @@
#[cfg(feature = "v1")]
use std::time::Instant;
+#[cfg(feature = "v1")]
+use callback_routes::{
+ ConnectorCallbackPath, ConnectorCallbackWithCredentialsPath, StartCallbackPath,
+};
#[cfg(feature = "v1")]
use common_utils::types::keymanager::KeyManagerState;
@@ -16,6 +20,9 @@ use crate::{
},
services::authorization::permissions::Permission,
};
+
+pub mod callback_routes;
+pub mod callback_tokens;
pub mod helpers;
use actix_web::{web, Responder};
use error_stack::report;
@@ -723,14 +730,22 @@ pub async fn payments_update_intent(
pub async fn payments_start(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- path: web::Path<(
- common_utils::id_type::PaymentId,
- common_utils::id_type::MerchantId,
- String,
- )>,
+ path: web::Path<StartCallbackPath>,
) -> impl Responder {
let flow = Flow::PaymentsStart;
- let (payment_id, merchant_id, attempt_id) = path.into_inner();
+ let path = path.into_inner();
+ let callback_auth = match callback_tokens::PaymentCallbackAuth::from_request(
+ callback_tokens::PaymentCallbackFields::Start(&path),
+ &req,
+ ) {
+ Ok(auth) => auth,
+ Err(error) => return api::log_and_return_error_response(error),
+ };
+ let StartCallbackPath {
+ payment_id,
+ merchant_id,
+ attempt_id,
+ } = path;
let payload = payment_types::PaymentsStartRequest {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
@@ -768,7 +783,7 @@ pub async fn payments_start(
None,
)
},
- &auth::MerchantIdAuth(merchant_id),
+ &callback_auth,
locking_action,
))
.await
@@ -1671,14 +1686,22 @@ pub async fn payments_redirect_response(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
- path: web::Path<(
- common_utils::id_type::PaymentId,
- common_utils::id_type::MerchantId,
- String,
- )>,
+ path: web::Path<ConnectorCallbackPath>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
- let (payment_id, merchant_id, connector) = path.into_inner();
+ let path = path.into_inner();
+ let callback_auth = match callback_tokens::PaymentCallbackAuth::from_request(
+ callback_tokens::PaymentCallbackFields::RedirectResponse(&path),
+ &req,
+ ) {
+ Ok(auth) => auth,
+ Err(error) => return api::log_and_return_error_response(error),
+ };
+ let ConnectorCallbackPath {
+ payment_id,
+ merchant_id,
+ connector,
+ } = path;
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
@@ -1693,6 +1716,7 @@ pub async fn payments_redirect_response(
creds_identifier: None,
};
let locking_action = payload.get_locking_input(flow.clone());
+
Box::pin(api::server_wrap(
flow,
state,
@@ -1707,7 +1731,7 @@ pub async fn payments_redirect_response(
req,
)
},
- &auth::MerchantIdAuth(merchant_id),
+ &callback_auth,
locking_action,
))
.await
@@ -1718,14 +1742,22 @@ pub async fn payments_redirect_response(
pub async fn payments_redirect_response_with_creds_identifier(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- path: web::Path<(
- common_utils::id_type::PaymentId,
- common_utils::id_type::MerchantId,
- String,
- String,
- )>,
+ path: web::Path<ConnectorCallbackWithCredentialsPath>,
) -> impl Responder {
- let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner();
+ let path = path.into_inner();
+ let callback_auth = match callback_tokens::PaymentCallbackAuth::from_request(
+ callback_tokens::PaymentCallbackFields::RedirectResponseWithCredentials(&path),
+ &req,
+ ) {
+ Ok(auth) => auth,
+ Err(error) => return api::log_and_return_error_response(error),
+ };
+ let ConnectorCallbackWithCredentialsPath {
+ payment_id,
+ merchant_id,
+ connector,
+ creds_identifier,
+ } = path;
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
@@ -1741,6 +1773,7 @@ pub async fn payments_redirect_response_with_creds_identifier(
};
let flow = Flow::PaymentsRedirect;
let locking_action = payload.get_locking_input(flow.clone());
+
Box::pin(api::server_wrap(
flow,
state,
@@ -1755,7 +1788,7 @@ pub async fn payments_redirect_response_with_creds_identifier(
req,
)
},
- &auth::MerchantIdAuth(merchant_id),
+ &callback_auth,
locking_action,
))
.await
@@ -1767,14 +1800,22 @@ pub async fn payments_complete_authorize_redirect(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
- path: web::Path<(
- common_utils::id_type::PaymentId,
- common_utils::id_type::MerchantId,
- String,
- )>,
+ path: web::Path<ConnectorCallbackPath>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
- let (payment_id, merchant_id, connector) = path.into_inner();
+ let path = path.into_inner();
+ let callback_auth = match callback_tokens::PaymentCallbackAuth::from_request(
+ callback_tokens::PaymentCallbackFields::RedirectComplete(&path),
+ &req,
+ ) {
+ Ok(auth) => auth,
+ Err(error) => return api::log_and_return_error_response(error),
+ };
+ let ConnectorCallbackPath {
+ payment_id,
+ merchant_id,
+ connector,
+ } = path;
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
@@ -1789,6 +1830,7 @@ pub async fn payments_complete_authorize_redirect(
creds_identifier: None,
};
let locking_action = payload.get_locking_input(flow.clone());
+
Box::pin(api::server_wrap(
flow,
state,
@@ -1803,7 +1845,7 @@ pub async fn payments_complete_authorize_redirect(
req,
)
},
- &auth::MerchantIdAuth(merchant_id),
+ &callback_auth,
locking_action,
))
.await
@@ -1815,15 +1857,23 @@ pub async fn payments_complete_authorize_redirect_with_creds_identifier(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
- path: web::Path<(
- common_utils::id_type::PaymentId,
- common_utils::id_type::MerchantId,
- String,
- String,
- )>,
+ path: web::Path<ConnectorCallbackWithCredentialsPath>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
- let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner();
+ let path = path.into_inner();
+ let callback_auth = match callback_tokens::PaymentCallbackAuth::from_request(
+ callback_tokens::PaymentCallbackFields::RedirectCompleteWithCredentials(&path),
+ &req,
+ ) {
+ Ok(auth) => auth,
+ Err(error) => return api::log_and_return_error_response(error),
+ };
+ let ConnectorCallbackWithCredentialsPath {
+ payment_id,
+ merchant_id,
+ connector,
+ creds_identifier,
+ } = path;
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
@@ -1838,6 +1888,7 @@ pub async fn payments_complete_authorize_redirect_with_creds_identifier(
creds_identifier: Some(creds_identifier),
};
let locking_action = payload.get_locking_input(flow.clone());
+
Box::pin(api::server_wrap(
flow,
state,
@@ -1852,7 +1903,7 @@ pub async fn payments_complete_authorize_redirect_with_creds_identifier(
req,
)
},
- &auth::MerchantIdAuth(merchant_id),
+ &callback_auth,
locking_action,
))
.await
@@ -3113,31 +3164,35 @@ where
(Some(l), None) | (None, Some(l)) => Some(l),
(None, None) => None,
};
- return payment_types::PaymentsResponse::generate_response(
- pd,
- auth_flow,
- &state.base_url,
- operation,
- &state.conf.connector_request_reference_id_config,
- connector_status_code,
- total_ext_latency,
- header_payload.x_hs_latency,
- &platform,
- );
+ return {
+ payment_types::PaymentsResponse::generate_response_with_callbacks(
+ &state,
+ pd,
+ auth_flow,
+ operation,
+ connector_status_code,
+ total_ext_latency,
+ header_payload.x_hs_latency,
+ &platform,
+ )
+ .await
+ };
}
}
- payment_types::PaymentsResponse::generate_response(
- payment_data,
- auth_flow,
- &state.base_url,
- operation,
- &state.conf.connector_request_reference_id_config,
- connector_http_status_code,
- external_latency,
- header_payload.x_hs_latency,
- &platform,
- )
+ {
+ payment_types::PaymentsResponse::generate_response_with_callbacks(
+ &state,
+ payment_data,
+ auth_flow,
+ operation,
+ connector_http_status_code,
+ external_latency,
+ header_payload.x_hs_latency,
+ &platform,
+ )
+ .await
+ }
}
}
api_models::enums::PaymentType::SetupMandate => {
@@ -3346,15 +3401,23 @@ pub async fn post_3ds_payments_authorize(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
- path: web::Path<(
- common_utils::id_type::PaymentId,
- common_utils::id_type::MerchantId,
- String,
- )>,
+ path: web::Path<ConnectorCallbackPath>,
) -> impl Responder {
let flow = Flow::PaymentsAuthorize;
- let (payment_id, merchant_id, connector) = path.into_inner();
+ let path = path.into_inner();
+ let callback_auth = match callback_tokens::PaymentCallbackAuth::from_request(
+ callback_tokens::PaymentCallbackFields::Authorize(&path),
+ &req,
+ ) {
+ Ok(auth) => auth,
+ Err(error) => return api::log_and_return_error_response(error),
+ };
+ let ConnectorCallbackPath {
+ payment_id,
+ merchant_id,
+ connector,
+ } = path;
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let param_string = req.query_string();
let payload = payments::PaymentsRedirectResponseData {
@@ -3383,7 +3446,7 @@ pub async fn post_3ds_payments_authorize(
req,
)
},
- &auth::MerchantIdAuth(merchant_id),
+ &callback_auth,
locking_action,
))
.await
diff --git a/crates/router/src/routes/payments/callback_routes.rs b/crates/router/src/routes/payments/callback_routes.rs
new file mode 100644
index 0000000000..5e1fd09d90
--- /dev/null
+++ b/crates/router/src/routes/payments/callback_routes.rs
@@ -0,0 +1,240 @@
+//! Named payment callbacks and their URL path constructors.
+//!
+//! URL constructors include the base URL and `/payments` scope. Actix registration
+//! iterates every variant, so adding a route requires a matching path and handler
+//! at compile time.
+
+#[cfg(feature = "v1")]
+use actix_web::{web, Resource};
+
+use super::callback_tokens::{PaymentCallbackFields, PaymentCallbackUrl};
+use crate::core::configs::payment_callback::PaymentCallbackMode;
+#[cfg(feature = "v1")]
+use crate::routes::payments;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::EnumIter)]
+pub enum PaymentCallbackRoute {
+ Start,
+ RedirectResponse,
+ RedirectResponseWithCredentials,
+ RedirectComplete,
+ RedirectCompleteWithCredentials,
+ Authorize,
+}
+
+impl PaymentCallbackRoute {
+ pub const CALLBACK_TOKEN: &'static str = "{callback_token}";
+ pub const PAYMENT_ID: &'static str = "{payment_id}";
+ pub const MERCHANT_ID: &'static str = "{merchant_id}";
+ pub const ATTEMPT_ID: &'static str = "{attempt_id}";
+ pub const CONNECTOR: &'static str = "{connector}";
+ pub const CREDS_IDENTIFIER: &'static str = "{creds_identifier}";
+
+ pub const fn name(self) -> &'static str {
+ match self {
+ Self::Start => "payment_callback_start",
+ Self::RedirectResponse => "payment_callback_redirect_response",
+ Self::RedirectResponseWithCredentials => {
+ "payment_callback_redirect_response_with_credentials"
+ }
+ Self::RedirectComplete => "payment_callback_redirect_complete",
+ Self::RedirectCompleteWithCredentials => {
+ "payment_callback_redirect_complete_with_credentials"
+ }
+ Self::Authorize => "payment_callback_authorize",
+ }
+ }
+
+ pub fn path(self) -> String {
+ self.with_callback_token(Self::CALLBACK_TOKEN)
+ }
+
+ pub(super) fn with_callback_token(self, token: &str) -> String {
+ let prefix = format!(
+ "/{}/{}/redirect/token/{token}",
+ Self::PAYMENT_ID,
+ Self::MERCHANT_ID,
+ );
+ match self {
+ Self::Start => format!("{prefix}/start/{}", Self::ATTEMPT_ID),
+ Self::RedirectResponse => format!("{prefix}/response/{}", Self::CONNECTOR),
+ Self::RedirectResponseWithCredentials => format!(
+ "{prefix}/response/{}/{}",
+ Self::CONNECTOR,
+ Self::CREDS_IDENTIFIER,
+ ),
+ Self::RedirectComplete => format!("{prefix}/complete/{}", Self::CONNECTOR),
+ Self::RedirectCompleteWithCredentials => format!(
+ "{prefix}/complete/{}/{}",
+ Self::CONNECTOR,
+ Self::CREDS_IDENTIFIER,
+ ),
+ Self::Authorize => format!("{prefix}/authorize/{}", Self::CONNECTOR),
+ }
+ }
+
+ pub fn legacy_name(self) -> String {
+ format!("{}_legacy", self.name())
+ }
+
+ pub fn legacy_path(self) -> String {
+ match self {
+ Self::Start => format!(
+ "/redirect/{}/{}/{}",
+ Self::PAYMENT_ID,
+ Self::MERCHANT_ID,
+ Self::ATTEMPT_ID,
+ ),
+ Self::RedirectResponse => format!(
+ "/{}/{}/redirect/response/{}",
+ Self::PAYMENT_ID,
+ Self::MERCHANT_ID,
+ Self::CONNECTOR,
+ ),
+ Self::RedirectResponseWithCredentials => format!(
+ "/{}/{}/redirect/response/{}/{}",
+ Self::PAYMENT_ID,
+ Self::MERCHANT_ID,
+ Self::CONNECTOR,
+ Self::CREDS_IDENTIFIER,
+ ),
+ Self::RedirectComplete => format!(
+ "/{}/{}/redirect/complete/{}",
+ Self::PAYMENT_ID,
+ Self::MERCHANT_ID,
+ Self::CONNECTOR,
+ ),
+ Self::RedirectCompleteWithCredentials => format!(
+ "/{}/{}/redirect/complete/{}/{}",
+ Self::PAYMENT_ID,
+ Self::MERCHANT_ID,
+ Self::CONNECTOR,
+ Self::CREDS_IDENTIFIER,
+ ),
+ Self::Authorize => format!(
+ "/{}/{}/authorize/{}",
+ Self::PAYMENT_ID,
+ Self::MERCHANT_ID,
+ Self::CONNECTOR,
+ ),
+ }
+ }
+
+ pub fn start_url(
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ fields: &StartCallbackPath,
+ ) -> PaymentCallbackUrl {
+ PaymentCallbackFields::Start(fields).create_url(base_url, callback_mode)
+ }
+
+ pub fn redirect_response_url(
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ fields: &ConnectorCallbackPath,
+ ) -> PaymentCallbackUrl {
+ PaymentCallbackFields::RedirectResponse(fields).create_url(base_url, callback_mode)
+ }
+
+ pub fn redirect_response_with_credentials_url(
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ fields: &ConnectorCallbackWithCredentialsPath,
+ ) -> PaymentCallbackUrl {
+ PaymentCallbackFields::RedirectResponseWithCredentials(fields)
+ .create_url(base_url, callback_mode)
+ }
+
+ pub fn redirect_complete_url(
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ fields: &ConnectorCallbackPath,
+ ) -> PaymentCallbackUrl {
+ PaymentCallbackFields::RedirectComplete(fields).create_url(base_url, callback_mode)
+ }
+
+ pub fn redirect_complete_with_credentials_url(
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ fields: &ConnectorCallbackWithCredentialsPath,
+ ) -> PaymentCallbackUrl {
+ PaymentCallbackFields::RedirectCompleteWithCredentials(fields)
+ .create_url(base_url, callback_mode)
+ }
+
+ pub fn authorize_url(
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ fields: &ConnectorCallbackPath,
+ ) -> PaymentCallbackUrl {
+ PaymentCallbackFields::Authorize(fields).create_url(base_url, callback_mode)
+ }
+
+ /// Build the named resource with the methods and handlers for this callback.
+ #[cfg(feature = "v1")]
+ pub fn resource(self) -> Resource {
+ self.routes(web::resource(self.path()).name(self.name()))
+ }
+
+ /// Build the original callback resource for the compatibility rollout.
+ #[cfg(feature = "v1")]
+ pub fn legacy_resource(self) -> Resource {
+ self.routes(web::resource(self.legacy_path()).name(&self.legacy_name()))
+ }
+
+ #[cfg(feature = "v1")]
+ fn routes(self, resource: Resource) -> Resource {
+ match self {
+ Self::Start => resource.route(web::get().to(payments::payments_start)),
+ Self::RedirectResponse => resource
+ .route(web::get().to(payments::payments_redirect_response))
+ .route(web::post().to(payments::payments_redirect_response)),
+ Self::RedirectResponseWithCredentials => resource
+ .route(web::get().to(payments::payments_redirect_response_with_creds_identifier)),
+ Self::RedirectComplete => resource
+ .route(web::get().to(payments::payments_complete_authorize_redirect))
+ .route(web::post().to(payments::payments_complete_authorize_redirect)),
+ Self::RedirectCompleteWithCredentials => resource
+ .route(
+ web::get()
+ .to(payments::payments_complete_authorize_redirect_with_creds_identifier),
+ )
+ .route(
+ web::post()
+ .to(payments::payments_complete_authorize_redirect_with_creds_identifier),
+ ),
+ Self::Authorize => resource
+ .route(web::post().to(payments::post_3ds_payments_authorize))
+ .route(web::get().to(payments::post_3ds_payments_authorize)),
+ }
+ }
+}
+
+// The active API version supplies a concrete payment ID type.
+#[cfg(feature = "v1")]
+pub(crate) type CallbackPaymentId = common_utils::id_type::PaymentId;
+#[cfg(feature = "v2")]
+pub(crate) type CallbackPaymentId = common_utils::id_type::GlobalPaymentId;
+
+// Named extractors ignore the callback token; authentication reads it separately.
+#[derive(Debug, serde::Deserialize)]
+pub struct StartCallbackPath {
+ pub payment_id: CallbackPaymentId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub attempt_id: String,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct ConnectorCallbackPath {
+ pub payment_id: CallbackPaymentId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub connector: String,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct ConnectorCallbackWithCredentialsPath {
+ pub payment_id: CallbackPaymentId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub connector: String,
+ pub creds_identifier: String,
+}
diff --git a/crates/router/src/routes/payments/callback_tokens.rs b/crates/router/src/routes/payments/callback_tokens.rs
new file mode 100644
index 0000000000..5de4b023b0
--- /dev/null
+++ b/crates/router/src/routes/payments/callback_tokens.rs
@@ -0,0 +1,316 @@
+//! Registration and atomic consumption of single-use payment callback URLs.
+
+use error_stack::ResultExt;
+#[cfg(all(test, feature = "v1"))]
+use hyperswitch_masking::PeekInterface;
+use hyperswitch_masking::Secret;
+use sha2::{Digest, Sha256};
+use uuid::Uuid;
+
+use super::callback_routes::{
+ ConnectorCallbackPath, ConnectorCallbackWithCredentialsPath, PaymentCallbackRoute,
+ StartCallbackPath,
+};
+#[cfg(feature = "v1")]
+use crate::services::authentication::{
+ AuthenticateAndFetch, AuthenticationData, AuthenticationType, MerchantIdAuth,
+};
+use crate::{
+ core::{
+ configs::payment_callback::PaymentCallbackMode,
+ errors::{self, RouterResult},
+ },
+ routes::SessionState,
+};
+const UNUSED: &str = "unused";
+
+/// Route identity plus its concrete, already-validated path parameters.
+#[derive(Clone, Copy)]
+pub(super) enum PaymentCallbackFields<'a> {
+ Start(&'a StartCallbackPath),
+ RedirectResponse(&'a ConnectorCallbackPath),
+ RedirectResponseWithCredentials(&'a ConnectorCallbackWithCredentialsPath),
+ RedirectComplete(&'a ConnectorCallbackPath),
+ RedirectCompleteWithCredentials(&'a ConnectorCallbackWithCredentialsPath),
+ Authorize(&'a ConnectorCallbackPath),
+}
+
+impl<'a> PaymentCallbackFields<'a> {
+ pub(super) fn create_url(
+ self,
+ base_url: &str,
+ callback_mode: PaymentCallbackMode,
+ ) -> PaymentCallbackUrl {
+ let route = self.route();
+ let (path, key) = if callback_mode.issues_tokens() {
+ let token = common_utils::generate_uuid_v4();
+ let path = route.with_callback_token(&token.to_string());
+ let key = self.key(&token);
+ (path, Some(key))
+ } else {
+ (route.legacy_path(), None)
+ };
+ let path = match self {
+ Self::Start(fields) => path
+ .replace(
+ PaymentCallbackRoute::PAYMENT_ID,
+ fields.payment_id.get_string_repr(),
+ )
+ .replace(
+ PaymentCallbackRoute::MERCHANT_ID,
+ fields.merchant_id.get_string_repr(),
+ )
+ .replace(PaymentCallbackRoute::ATTEMPT_ID, &fields.attempt_id),
+ Self::RedirectResponse(fields)
+ | Self::RedirectComplete(fields)
+ | Self::Authorize(fields) => path
+ .replace(
+ PaymentCallbackRoute::PAYMENT_ID,
+ fields.payment_id.get_string_repr(),
+ )
+ .replace(
+ PaymentCallbackRoute::MERCHANT_ID,
+ fields.merchant_id.get_string_repr(),
+ )
+ .replace(PaymentCallbackRoute::CONNECTOR, &fields.connector),
+ Self::RedirectResponseWithCredentials(fields)
+ | Self::RedirectCompleteWithCredentials(fields) => path
+ .replace(
+ PaymentCallbackRoute::PAYMENT_ID,
+ fields.payment_id.get_string_repr(),
+ )
+ .replace(
+ PaymentCallbackRoute::MERCHANT_ID,
+ fields.merchant_id.get_string_repr(),
+ )
+ .replace(PaymentCallbackRoute::CONNECTOR, &fields.connector)
+ .replace(
+ PaymentCallbackRoute::CREDS_IDENTIFIER,
+ &fields.creds_identifier,
+ ),
+ };
+ let path = format!("/payments{path}");
+ PaymentCallbackUrl {
+ key,
+ url: Secret::new(format!("{base_url}{path}")),
+ }
+ }
+
+ fn route(self) -> PaymentCallbackRoute {
+ match self {
+ Self::Start(_) => PaymentCallbackRoute::Start,
+ Self::RedirectResponse(_) => PaymentCallbackRoute::RedirectResponse,
+ Self::RedirectResponseWithCredentials(_) => {
+ PaymentCallbackRoute::RedirectResponseWithCredentials
+ }
+ Self::RedirectComplete(_) => PaymentCallbackRoute::RedirectComplete,
+ Self::RedirectCompleteWithCredentials(_) => {
+ PaymentCallbackRoute::RedirectCompleteWithCredentials
+ }
+ Self::Authorize(_) => PaymentCallbackRoute::Authorize,
+ }
+ }
+
+ fn key(self, token: &Uuid) -> redis_interface::RedisKey {
+ let route = self.route();
+ match self {
+ Self::Start(path) => path.callback_key(route, token),
+ Self::RedirectResponse(path) | Self::RedirectComplete(path) | Self::Authorize(path) => {
+ path.callback_key(route, token)
+ }
+ Self::RedirectResponseWithCredentials(path)
+ | Self::RedirectCompleteWithCredentials(path) => path.callback_key(route, token),
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ fn merchant_id(self) -> &'a common_utils::id_type::MerchantId {
+ match self {
+ Self::Start(path) => &path.merchant_id,
+ Self::RedirectResponse(path) | Self::RedirectComplete(path) | Self::Authorize(path) => {
+ &path.merchant_id
+ }
+ Self::RedirectResponseWithCredentials(path)
+ | Self::RedirectCompleteWithCredentials(path) => &path.merchant_id,
+ }
+ }
+}
+
+trait CallbackHashInput {
+ fn hash_input(&self) -> String;
+
+ // Hash the bearer credential so Redis keys and command instrumentation do not
+ // contain usable tokens. RedisConnectionWithContext applies the tenant prefix.
+ fn callback_key(&self, route: PaymentCallbackRoute, token: &Uuid) -> redis_interface::RedisKey {
+ let mut digest = Sha256::new();
+ digest.update(Self::concatenate_fields(&[route.name()]));
+ digest.update(self.hash_input());
+ digest.update(token.as_bytes());
+ format!("payment_callback_token:{:x}", digest.finalize()).into()
+ }
+
+ // Byte-length framing distinguishes values even when they contain delimiters.
+ fn concatenate_fields(fields: &[&str]) -> String {
+ let mut input = String::new();
+ for field in fields {
+ input.push_str(&field.len().to_string());
+ input.push(':');
+ input.push_str(field);
+ }
+ input
+ }
+}
+
+impl CallbackHashInput for StartCallbackPath {
+ fn hash_input(&self) -> String {
+ Self::concatenate_fields(&[
+ self.payment_id.get_string_repr(),
+ self.merchant_id.get_string_repr(),
+ &self.attempt_id,
+ ])
+ }
+}
+
+impl CallbackHashInput for ConnectorCallbackPath {
+ fn hash_input(&self) -> String {
+ Self::concatenate_fields(&[
+ self.payment_id.get_string_repr(),
+ self.merchant_id.get_string_repr(),
+ &self.connector,
+ ])
+ }
+}
+
+impl CallbackHashInput for ConnectorCallbackWithCredentialsPath {
+ fn hash_input(&self) -> String {
+ Self::concatenate_fields(&[
+ self.payment_id.get_string_repr(),
+ self.merchant_id.get_string_repr(),
+ &self.connector,
+ &self.creds_identifier,
+ ])
+ }
+}
+
+/// A callback URL and its optional pending Redis registration.
+#[derive(Clone)]
+pub struct PaymentCallbackUrl {
+ url: Secret<String>,
+ key: Option<redis_interface::RedisKey>,
+}
+
+impl PaymentCallbackUrl {
+ pub async fn persist(self, state: &SessionState) -> RouterResult<Secret<String>> {
+ if let Some(key) = self.key {
+ let ttl = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
+ let connection = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let result = connection
+ .set_key_if_not_exists_with_expiry(&key, UNUSED, Some(ttl))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ if !matches!(result, redis_interface::SetnxReply::KeySet) {
+ return Err(errors::ApiErrorResponse::InternalServerError.into());
+ }
+ }
+ Ok(self.url)
+ }
+
+ pub fn url(&self) -> &Secret<String> {
+ &self.url
+ }
+}
+
+/// Opt-in authentication for protected callback handlers. Consume the token
+/// after merchant authentication succeeds and before server_wrap takes a lock.
+/// Original URLs are accepted only in legacy and migration modes.
+#[cfg(feature = "v1")]
+pub struct PaymentCallbackAuth {
+ merchant_auth: MerchantIdAuth,
+ key: Option<redis_interface::RedisKey>,
+}
+
+#[cfg(feature = "v1")]
+impl PaymentCallbackAuth {
+ fn parse_token(value: &str) -> RouterResult<Uuid> {
+ let token =
+ Uuid::parse_str(value).change_context(errors::ApiErrorResponse::Unauthorized)?;
+ if token.get_version_num() != 4 || token.to_string() != value {
+ return Err(errors::ApiErrorResponse::Unauthorized.into());
+ }
+ Ok(token)
+ }
+
+ fn request_key(
+ fields: PaymentCallbackFields<'_>,
+ request: &actix_web::HttpRequest,
+ ) -> RouterResult<Option<redis_interface::RedisKey>> {
+ let route = fields.route();
+ match request.match_name() {
+ Some(name) if name == route.name() => (),
+ Some(name) if name == route.legacy_name() => return Ok(None),
+ _ => return Err(errors::ApiErrorResponse::Unauthorized.into()),
+ }
+ let token = Self::parse_token(
+ request
+ .match_info()
+ .get("callback_token")
+ .ok_or(errors::ApiErrorResponse::Unauthorized)?,
+ )?;
+ Ok(Some(fields.key(&token)))
+ }
+
+ pub(super) fn from_request(
+ fields: PaymentCallbackFields<'_>,
+ request: &actix_web::HttpRequest,
+ ) -> RouterResult<Self> {
+ Ok(Self {
+ merchant_auth: MerchantIdAuth(fields.merchant_id().clone()),
+ key: Self::request_key(fields, request)?,
+ })
+ }
+
+ fn validate_mode(&self, mode: PaymentCallbackMode) -> RouterResult<()> {
+ if self.key.is_none() && !mode.allows_legacy() {
+ return Err(errors::ApiErrorResponse::Unauthorized.into());
+ }
+ Ok(())
+ }
+}
+
+#[cfg(feature = "v1")]
+#[async_trait::async_trait]
+impl AuthenticateAndFetch<AuthenticationData, SessionState> for PaymentCallbackAuth {
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &actix_web::http::header::HeaderMap,
+ state: &SessionState,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ self.validate_mode(state.payment_callback_config().await?.mode)?;
+ let auth = self
+ .merchant_auth
+ .authenticate_and_fetch(request_headers, state)
+ .await?;
+ let Some(key) = self.key.as_ref() else {
+ return Ok(auth);
+ };
+ let connection = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let value = connection
+ .consume_key(key)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ if value.as_deref() != Some(UNUSED) {
+ return Err(errors::ApiErrorResponse::Unauthorized.into());
+ }
+ Ok(auth)
+ }
+}
+
+#[cfg(test)]
+#[cfg(feature = "v1")]
+mod tests;
diff --git a/crates/router/src/routes/payments/callback_tokens/tests.rs b/crates/router/src/routes/payments/callback_tokens/tests.rs
new file mode 100644
index 0000000000..4013766fec
--- /dev/null
+++ b/crates/router/src/routes/payments/callback_tokens/tests.rs
@@ -0,0 +1,387 @@
+use actix_web::{http::Method, test as actix_test, web, App, HttpRequest, HttpResponse, Resource};
+
+use super::*;
+
+const ROUTES: [PaymentCallbackRoute; 6] = [
+ PaymentCallbackRoute::Start,
+ PaymentCallbackRoute::RedirectResponse,
+ PaymentCallbackRoute::RedirectResponseWithCredentials,
+ PaymentCallbackRoute::RedirectComplete,
+ PaymentCallbackRoute::RedirectCompleteWithCredentials,
+ PaymentCallbackRoute::Authorize,
+];
+const MODES: [PaymentCallbackMode; 3] = [
+ PaymentCallbackMode::Legacy,
+ PaymentCallbackMode::Migration,
+ PaymentCallbackMode::Enforced,
+];
+
+struct CallbackPaths {
+ start: StartCallbackPath,
+ connector: ConnectorCallbackPath,
+ credentials: ConnectorCallbackWithCredentialsPath,
+}
+impl CallbackPaths {
+ fn new() -> Self {
+ let payment_id =
+ common_utils::id_type::PaymentId::wrap("pay_1".to_string()).expect("payment ID");
+ let merchant_id =
+ common_utils::id_type::MerchantId::wrap("merchant_1".to_string()).expect("merchant ID");
+ Self {
+ start: StartCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ attempt_id: "attempt_1".into(),
+ },
+ connector: ConnectorCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: "stripe".into(),
+ },
+ credentials: ConnectorCallbackWithCredentialsPath {
+ payment_id,
+ merchant_id,
+ connector: "stripe".into(),
+ creds_identifier: "creds_1".into(),
+ },
+ }
+ }
+ fn fields(&self, route: PaymentCallbackRoute) -> PaymentCallbackFields<'_> {
+ match route {
+ PaymentCallbackRoute::Start => PaymentCallbackFields::Start(&self.start),
+ PaymentCallbackRoute::RedirectResponse => {
+ PaymentCallbackFields::RedirectResponse(&self.connector)
+ }
+ PaymentCallbackRoute::RedirectResponseWithCredentials => {
+ PaymentCallbackFields::RedirectResponseWithCredentials(&self.credentials)
+ }
+ PaymentCallbackRoute::RedirectComplete => {
+ PaymentCallbackFields::RedirectComplete(&self.connector)
+ }
+ PaymentCallbackRoute::RedirectCompleteWithCredentials => {
+ PaymentCallbackFields::RedirectCompleteWithCredentials(&self.credentials)
+ }
+ PaymentCallbackRoute::Authorize => PaymentCallbackFields::Authorize(&self.connector),
+ }
+ }
+ fn url(&self, route: PaymentCallbackRoute, mode: PaymentCallbackMode) -> PaymentCallbackUrl {
+ let base = "https://router.test";
+ match route {
+ PaymentCallbackRoute::Start => PaymentCallbackRoute::start_url(base, mode, &self.start),
+ PaymentCallbackRoute::RedirectResponse => {
+ PaymentCallbackRoute::redirect_response_url(base, mode, &self.connector)
+ }
+ PaymentCallbackRoute::RedirectResponseWithCredentials => {
+ PaymentCallbackRoute::redirect_response_with_credentials_url(
+ base,
+ mode,
+ &self.credentials,
+ )
+ }
+ PaymentCallbackRoute::RedirectComplete => {
+ PaymentCallbackRoute::redirect_complete_url(base, mode, &self.connector)
+ }
+ PaymentCallbackRoute::RedirectCompleteWithCredentials => {
+ PaymentCallbackRoute::redirect_complete_with_credentials_url(
+ base,
+ mode,
+ &self.credentials,
+ )
+ }
+ PaymentCallbackRoute::Authorize => {
+ PaymentCallbackRoute::authorize_url(base, mode, &self.connector)
+ }
+ }
+ }
+}
+fn resolved_path(route: PaymentCallbackRoute) -> String {
+ route
+ .legacy_path()
+ .replace(PaymentCallbackRoute::PAYMENT_ID, "pay_1")
+ .replace(PaymentCallbackRoute::MERCHANT_ID, "merchant_1")
+ .replace(PaymentCallbackRoute::ATTEMPT_ID, "attempt_1")
+ .replace(PaymentCallbackRoute::CONNECTOR, "stripe")
+ .replace(PaymentCallbackRoute::CREDS_IDENTIFIER, "creds_1")
+}
+
+fn resolved_token_path(route: PaymentCallbackRoute, token: &str) -> String {
+ let prefix = format!("/payments/pay_1/merchant_1/redirect/token/{token}");
+ match route {
+ PaymentCallbackRoute::Start => format!("{prefix}/start/attempt_1"),
+ PaymentCallbackRoute::RedirectResponse => format!("{prefix}/response/stripe"),
+ PaymentCallbackRoute::RedirectResponseWithCredentials => {
+ format!("{prefix}/response/stripe/creds_1")
+ }
+ PaymentCallbackRoute::RedirectComplete => format!("{prefix}/complete/stripe"),
+ PaymentCallbackRoute::RedirectCompleteWithCredentials => {
+ format!("{prefix}/complete/stripe/creds_1")
+ }
+ PaymentCallbackRoute::Authorize => format!("{prefix}/authorize/stripe"),
+ }
+}
+
+#[tokio::test]
+async fn issuance_obeys_rollout_mode_for_every_protected_route() {
+ let paths = CallbackPaths::new();
+ let mut seen = std::collections::HashSet::new();
+ for route in ROUTES {
+ for mode in MODES {
+ let path = resolved_path(route);
+ let pending = paths.url(route, mode);
+ let url = url::Url::parse(pending.url().peek()).expect("URL");
+ assert!(url.query().is_none());
+ if mode == PaymentCallbackMode::Legacy {
+ assert_eq!(url.path(), format!("/payments{path}"));
+ assert!(pending.key.is_none());
+ } else {
+ let token = PaymentCallbackAuth::parse_token(
+ url.path_segments()
+ .expect("segments")
+ .nth(5)
+ .expect("token"),
+ )
+ .expect("UUID");
+ assert!(seen.insert(token));
+ assert_eq!(url.path(), resolved_token_path(route, &token.to_string()));
+ assert_eq!(
+ format!("{:?}", pending.key),
+ format!("{:?}", Some(paths.fields(route).key(&token)))
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn callback_keys_bind_the_route_and_use_stable_field_encoding() {
+ let paths = CallbackPaths::new();
+ let token = Uuid::parse_str("d9dc53cc-d1a1-4f57-9077-d20c2d614daa").expect("UUID");
+ let expected: redis_interface::RedisKey =
+ "payment_callback_token:8e7e467a9e7bb32891e4adad4922ceeb8d2a623f01664737aa0416017ef01c42"
+ .into();
+ assert_eq!(
+ format!(
+ "{:?}",
+ paths.fields(PaymentCallbackRoute::Start).key(&token)
+ ),
+ format!("{expected:?}")
+ );
+ let keys = ROUTES
+ .into_iter()
+ .map(|route| format!("{:?}", paths.fields(route).key(&token)))
+ .collect::<std::collections::HashSet<_>>();
+ assert_eq!(keys.len(), ROUTES.len());
+ assert_ne!(
+ StartCallbackPath::concatenate_fields(&["a", "bc"]),
+ StartCallbackPath::concatenate_fields(&["ab", "c"])
+ );
+}
+
+#[test]
+fn malformed_and_noncanonical_tokens_are_rejected() {
+ let token = common_utils::generate_uuid_v4();
+ assert_eq!(
+ PaymentCallbackAuth::parse_token(&token.to_string()).expect("UUID"),
+ token
+ );
+ for value in [
+ String::new(),
+ "invalid".into(),
+ Uuid::nil().to_string(),
+ "D9DC53CC-D1A1-4F57-9077-D20C2D614DAA".into(),
+ format!("{{{token}}}"),
+ "6ba7b810-9dad-11d1-80b4-00c04fd430c8".into(),
+ ] {
+ assert!(PaymentCallbackAuth::parse_token(&value).is_err());
+ }
+}
+
+fn echo_auth(
+ request: &HttpRequest,
+ fields: PaymentCallbackFields<'_>,
+ mode: PaymentCallbackMode,
+) -> HttpResponse {
+ match PaymentCallbackAuth::from_request(fields, request).and_then(|auth| {
+ auth.validate_mode(mode)?;
+ Ok(auth)
+ }) {
+ Ok(auth) => HttpResponse::Ok().body(format!("{:?}|{}", auth.key, request.query_string())),
+ Err(_) => HttpResponse::Unauthorized().finish(),
+ }
+}
+async fn echo_start(
+ request: HttpRequest,
+ mode: web::Data<PaymentCallbackMode>,
+ path: web::Path<StartCallbackPath>,
+) -> HttpResponse {
+ echo_auth(&request, PaymentCallbackFields::Start(&path), **mode)
+}
+async fn echo_connector(
+ request: HttpRequest,
+ route: web::Data<PaymentCallbackRoute>,
+ mode: web::Data<PaymentCallbackMode>,
+ path: web::Path<ConnectorCallbackPath>,
+) -> HttpResponse {
+ let fields = match **route {
+ PaymentCallbackRoute::RedirectResponse => PaymentCallbackFields::RedirectResponse(&path),
+ PaymentCallbackRoute::RedirectComplete => PaymentCallbackFields::RedirectComplete(&path),
+ PaymentCallbackRoute::Authorize => PaymentCallbackFields::Authorize(&path),
+ _ => panic!("Expected a connector callback route"),
+ };
+ echo_auth(&request, fields, **mode)
+}
+async fn echo_credentials(
+ request: HttpRequest,
+ route: web::Data<PaymentCallbackRoute>,
+ mode: web::Data<PaymentCallbackMode>,
+ path: web::Path<ConnectorCallbackWithCredentialsPath>,
+) -> HttpResponse {
+ let fields = match **route {
+ PaymentCallbackRoute::RedirectResponseWithCredentials => {
+ PaymentCallbackFields::RedirectResponseWithCredentials(&path)
+ }
+ PaymentCallbackRoute::RedirectCompleteWithCredentials => {
+ PaymentCallbackFields::RedirectCompleteWithCredentials(&path)
+ }
+ _ => panic!("Expected a connector callback route with credentials"),
+ };
+ echo_auth(&request, fields, **mode)
+}
+fn test_resource(route: PaymentCallbackRoute, legacy: bool) -> Resource {
+ let resource = if legacy {
+ web::resource(route.legacy_path()).name(&route.legacy_name())
+ } else {
+ web::resource(route.path()).name(route.name())
+ }
+ .app_data(web::Data::new(route));
+ match route {
+ PaymentCallbackRoute::Start => resource
+ .route(web::get().to(echo_start))
+ .route(web::post().to(echo_start)),
+ PaymentCallbackRoute::RedirectResponseWithCredentials
+ | PaymentCallbackRoute::RedirectCompleteWithCredentials => resource
+ .route(web::get().to(echo_credentials))
+ .route(web::post().to(echo_credentials)),
+ _ => resource
+ .route(web::get().to(echo_connector))
+ .route(web::post().to(echo_connector)),
+ }
+}
+
+#[actix_web::test]
+async fn callback_routes_accept_legacy_only_during_rollout_and_always_validate_path_tokens() {
+ let paths = CallbackPaths::new();
+ let query = "connector_param=a%2fb&connector_param=c+d&flag&empty=";
+ for mode in MODES {
+ for route in ROUTES {
+ let path = resolved_path(route);
+ let pending = paths.url(route, PaymentCallbackMode::Migration);
+ let url = url::Url::parse(pending.url().peek()).expect("URL");
+ let uri = format!("{}?{query}", url.path());
+ let expected = format!("{:?}|{query}", pending.key);
+ let app = actix_test::init_service(
+ App::new().app_data(web::Data::new(mode)).service(
+ web::scope("/payments")
+ .service(test_resource(route, false))
+ .service(test_resource(route, true)),
+ ),
+ )
+ .await;
+ for method in [Method::GET, Method::POST] {
+ let response = actix_test::call_service(
+ &app,
+ actix_test::TestRequest::default()
+ .method(method.clone())
+ .uri(&uri)
+ .to_request(),
+ )
+ .await;
+ assert_eq!(response.status(), actix_web::http::StatusCode::OK);
+ assert_eq!(
+ std::str::from_utf8(&actix_test::read_body(response).await)
+ .expect("key and query"),
+ expected
+ );
+ let legacy = actix_test::call_service(
+ &app,
+ actix_test::TestRequest::default()
+ .method(method)
+ .uri(&format!("/payments{path}?{query}"))
+ .to_request(),
+ )
+ .await;
+ if mode != PaymentCallbackMode::Enforced {
+ assert_eq!(legacy.status(), actix_web::http::StatusCode::OK);
+ assert_eq!(
+ std::str::from_utf8(&actix_test::read_body(legacy).await)
+ .expect("legacy query"),
+ format!("None|{query}")
+ );
+ } else {
+ assert_eq!(legacy.status(), actix_web::http::StatusCode::UNAUTHORIZED);
+ }
+ }
+ for (old, new) in [
+ ("pay_1", "pay_2"),
+ ("merchant_1", "merchant_2"),
+ ("attempt_1", "attempt_2"),
+ ("stripe", "adyen"),
+ ("creds_1", "creds_2"),
+ ] {
+ let changed = uri.replace(old, new);
+ if changed == uri {
+ continue;
+ }
+ let body = actix_test::call_and_read_body(
+ &app,
+ actix_test::TestRequest::get().uri(&changed).to_request(),
+ )
+ .await;
+ assert_ne!(std::str::from_utf8(&body).expect("changed key"), expected);
+ }
+ for token in ["invalid".to_string(), Uuid::nil().to_string()] {
+ let response = actix_test::call_service(
+ &app,
+ actix_test::TestRequest::get()
+ .uri(&format!("{}?{query}", resolved_token_path(route, &token)))
+ .to_request(),
+ )
+ .await;
+ assert_eq!(response.status(), actix_web::http::StatusCode::UNAUTHORIZED);
+ }
+ }
+ }
+}
+
+#[actix_web::test]
+async fn callback_auth_rejects_unmatched_and_unprotected_routes() {
+ let paths = CallbackPaths::new();
+ let request = actix_test::TestRequest::get()
+ .uri("/other")
+ .to_http_request();
+ assert!(
+ PaymentCallbackAuth::request_key(PaymentCallbackFields::Start(&paths.start), &request)
+ .is_err()
+ );
+ let app = actix_test::init_service(
+ App::new()
+ .app_data(web::Data::new(PaymentCallbackMode::Migration))
+ .service(
+ web::resource(PaymentCallbackRoute::Start.path())
+ .name("unprotected_route")
+ .route(web::get().to(echo_start)),
+ ),
+ )
+ .await;
+ let pending = paths.url(PaymentCallbackRoute::Start, PaymentCallbackMode::Migration);
+ let url = url::Url::parse(pending.url().peek()).expect("URL");
+ // The test resource is mounted without the /payments scope.
+ let response = actix_test::call_service(
+ &app,
+ actix_test::TestRequest::get()
+ .uri(url.path().strip_prefix("/payments").expect("scope"))
+ .to_request(),
+ )
+ .await;
+ assert_eq!(response.status(), actix_web::http::StatusCode::UNAUTHORIZED);
+}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 1964605fb4..5b2d031f77 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -422,7 +422,7 @@ where
E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context,
{
let request_method = request.method().as_str();
- let url_path = request.path();
+ let url_path = router_env::request_path::path_for_telemetry(request);
let unmasked_incoming_header_keys = state.conf().unmasked_headers.keys;
@@ -442,7 +442,7 @@ where
});
tracing::Span::current().record("request_method", request_method);
- tracing::Span::current().record("request_url_path", url_path);
+ tracing::Span::current().record("request_url_path", url_path.as_ref());
let start_instant = Instant::now();
@@ -504,6 +504,7 @@ where
let config = state.conf();
build_redirection_form(
&redirection_data.redirect_form,
+ redirection_data.callback_url.as_ref(),
redirection_data.payment_method_data,
redirection_data.amount,
redirection_data.currency,
@@ -725,7 +726,10 @@ pub fn http_redirect_response<T: body::MessageBody + 'static>(
.content_type(mime::APPLICATION_JSON)
.append_header((
"Location",
- redirection_response.return_url_with_query_params,
+ redirection_response
+ .return_url_with_query_params
+ .peek()
+ .as_str(),
))
.status(http::StatusCode::FOUND)
.body(response)
@@ -871,12 +875,16 @@ impl Authenticate for api_models::payments::PaymentsRejectRequest {}
pub fn build_redirection_form(
form: &RedirectForm,
+ callback_url: Option<&hyperswitch_masking::Secret<String>>,
payment_method_data: Option<PaymentMethodData>,
amount: String,
currency: String,
config: Settings,
) -> maud::Markup {
use maud::PreEscaped;
+ let callback_url = callback_url
+ .map(|url| url.peek().as_str())
+ .unwrap_or_default();
let logging_template =
include_str!("redirection/assets/redirect_error_logs_push.js").to_string();
match form {
@@ -928,9 +936,9 @@ pub fn build_redirection_form(
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
- form action=(PreEscaped(endpoint)) method=(method.to_string()) #payment_form {
+ form action=(PreEscaped(endpoint.peek())) method=(method.to_string()) #payment_form {
@for (field, value) in form_fields {
- input type="hidden" name=(field) value=(value);
+ input type="hidden" name=(field) value=(value.peek());
}
}
(PreEscaped(format!(r#"
@@ -953,9 +961,10 @@ pub fn build_redirection_form(
}
}
},
- RedirectForm::Html { html_data } => {
- PreEscaped(format!("{html_data} <script>{logging_template}</script>"))
- }
+ RedirectForm::Html { html_data } => PreEscaped(format!(
+ "{} <script>{logging_template}</script>",
+ html_data.peek()
+ )),
RedirectForm::BarclaycardAuthSetup {
access_token,
ddc_url,
@@ -967,7 +976,7 @@ pub fn build_redirection_form(
head {
meta name="viewport" content="width=device-width, initial-scale=1";
}
- body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
+ body data-callback-url=(callback_url) style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
@@ -1002,7 +1011,9 @@ pub fn build_redirection_form(
{logging_template}
window.addEventListener(\"message\", function(event) {{
if (event.origin.endsWith(\"cardinaltrusted.com\") || event.origin.endsWith(\"cardinalcommerce.com\")) {{
- window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\");
+ var callback = new URL(document.body.getAttribute('data-callback-url'));
+ callback.searchParams.set(\"referenceId\", \"{reference_id}\");
+ window.location.href = callback.toString();
}}
}}, false);
</script>
@@ -1076,7 +1087,7 @@ pub fn build_redirection_form(
meta name="viewport" content="width=device-width, initial-scale=1";
(PreEscaped(format!("<script src=\"{bluesnap_sdk_url}web-sdk/5/bluesnap.js\"></script>")))
}
- body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
+ body data-callback-url=(callback_url) style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
@@ -1104,7 +1115,9 @@ pub fn build_redirection_form(
function(sdkResponse) {{
// console.log(sdkResponse);
var f = document.createElement('form');
- f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/bluesnap?paymentToken={payment_fields_token}\");
+ var callback = new URL(document.body.getAttribute('data-callback-url'));
+ callback.searchParams.set(\"paymentToken\", \"{payment_fields_token}\");
+ f.action = callback.toString();
f.method='POST';
var i=document.createElement('input');
i.type='hidden';
@@ -1131,7 +1144,7 @@ pub fn build_redirection_form(
head {
meta name="viewport" content="width=device-width, initial-scale=1";
}
- body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
+ body data-callback-url=(callback_url) style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
@@ -1176,7 +1189,9 @@ pub fn build_redirection_form(
return;
}}
- window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\");
+ var callback = new URL(document.body.getAttribute('data-callback-url'));
+ callback.searchParams.set(\"referenceId\", \"{reference_id}\");
+ window.location.href = callback.toString();
}}, false);
</script>
")))
@@ -1274,10 +1289,11 @@ pub fn build_redirection_form(
head {
(PreEscaped(r#"<script src="https://cdn.paymeservice.com/hf/v1/hostedfields.js"></script>"#))
}
+ body data-callback-url=(callback_url) {
(PreEscaped(format!("<script>
{logging_template}
var f = document.createElement('form');
- f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/payme\");
+ f.action = document.body.getAttribute('data-callback-url');
f.method='POST';
PayMe.clientData()
.then((data) => {{
@@ -1294,6 +1310,7 @@ pub fn build_redirection_form(
}});
</script>
")))
+ }
}
}
RedirectForm::Braintree {
@@ -1302,6 +1319,7 @@ pub fn build_redirection_form(
bin,
acs_url,
} => {
+ let acs_url = acs_url.peek();
maud::html! {
(maud::DOCTYPE)
html {
@@ -1311,7 +1329,7 @@ pub fn build_redirection_form(
// (PreEscaped(r#"<script src="https://js.braintreegateway.com/web/3.97.1/js/hosted-fields.js"></script>"#))
}
- body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
+ body data-callback-url=(callback_url) data-complete-callback-url=(acs_url) style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
@@ -1364,7 +1382,7 @@ pub fn build_redirection_form(
if(err) {{
console.error(err);
var f = document.createElement('form');
- f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/response/braintree\");
+ f.action = document.body.getAttribute('data-callback-url');
var i = document.createElement('input');
i.type = 'hidden';
f.method='POST';
@@ -1377,7 +1395,7 @@ pub fn build_redirection_form(
}} else {{
// console.log(payload);
var f = document.createElement('form');
- f.action=\"{acs_url}\";
+ f.action = document.body.getAttribute('data-complete-callback-url');
var i = document.createElement('input');
i.type = 'hidden';
f.method='POST';
@@ -1406,7 +1424,7 @@ pub fn build_redirection_form(
head {
(PreEscaped(r#"<script src="https://secure.networkmerchants.com/js/v1/Gateway.js"></script>"#))
}
- body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
+ body data-callback-url=(callback_url) style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader-wrapper" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
@@ -1452,7 +1470,7 @@ pub fn build_redirection_form(
threeDSsecureInterface.on('complete', function(e) {{
var responseForm = document.createElement('form');
- responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/([^/]+)\\/([^/]+)\\/[^/]+/, \"payments/$1/$2/redirect/complete/nmi\");
+ responseForm.action = document.body.getAttribute('data-callback-url');
responseForm.method='POST';
var item1=document.createElement('input');
@@ -1509,7 +1527,7 @@ pub fn build_redirection_form(
threeDSsecureInterface.on('failure', function(e) {{
var responseForm = document.createElement('form');
- responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/([^/]+)\\/([^/]+)\\/[^/]+/, \"payments/$1/$2/redirect/complete/nmi\");
+ responseForm.action = document.body.getAttribute('data-callback-url');
responseForm.method='POST';
var error_code=document.createElement('input');
@@ -1543,13 +1561,14 @@ pub fn build_redirection_form(
(PreEscaped(format!(r#"<script src='{mifinity_base_url}widgets/sgpg.js?58190a411dc3'></script>"#)))
}
+ body data-callback-url=(callback_url) {
(PreEscaped(format!("<div id='widget-container'></div>
<script>
var widget = showPaymentIframe('widget-container', {{
token: '{initialization_token}',
complete: function() {{
var f = document.createElement('form');
- f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/response/mifinity\");
+ f.action = document.body.getAttribute('data-callback-url');
f.method='GET';
document.body.appendChild(f);
f.submit();
@@ -1557,6 +1576,7 @@ pub fn build_redirection_form(
}});
</script>")))
+ }
}
}
RedirectForm::WorldpayDDCForm {
@@ -1583,7 +1603,7 @@ pub fn build_redirection_form(
"##))
}
- body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
+ body data-callback-url=(callback_url) style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
@@ -1605,21 +1625,21 @@ pub fn build_redirection_form(
r#"
var ddcProcessed = false;
var timeoutHandle = null;
-
+
function submitCollectionReference(collectionReference) {{
if (ddcProcessed) {{
console.log("DDC already processed, ignoring duplicate submission");
return;
}}
ddcProcessed = true;
-
+
if (timeoutHandle) {{
clearTimeout(timeoutHandle);
timeoutHandle = null;
}}
-
- var redirectPathname = window.location.pathname.replace(/payments\/redirect\/([^\/]+)\/([^\/]+)\/[^\/]+/, "payments/$1/$2/redirect/complete/worldpay");
- var redirectUrl = window.location.origin + redirectPathname;
+
+ var redirectPathname = document.body.getAttribute('data-callback-url');
+ var redirectUrl = redirectPathname;
try {{
if (typeof collectionReference === "string" && collectionReference.length > 0) {{
var form = document.createElement("form");
@@ -1720,7 +1740,7 @@ pub fn build_redirection_form(
head {
meta name="viewport" content="width=device-width, initial-scale=1";
}
- body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
+ body data-callback-url=(callback_url) style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" }
h3 style="text-align: center;" { "Please wait while we perform Device Data Collection ..." }
@@ -1751,10 +1771,7 @@ pub fn build_redirection_form(
try {{
var data = JSON.parse(event.data);
var responseForm = document.createElement('form');
- responseForm.action=window.location.pathname.replace(
- new RegExp("payments/redirect/([^/]+)/([^/]+)/[^/]+"),
- "payments/$1/$2/redirect/complete/worldpayxml"
- );
+ responseForm.action = document.body.getAttribute('data-callback-url');
responseForm.method='POST';
var item1=document.createElement('input');
@@ -1773,10 +1790,7 @@ pub fn build_redirection_form(
responseForm.submit();
}} catch (e) {{
var responseForm = document.createElement('form');
- responseForm.action=window.location.pathname.replace(
- new RegExp("payments/redirect/([^/]+)/([^/]+)/[^/]+"),
- "payments/$1/$2/redirect/complete/worldpayxml"
- );
+ responseForm.action = document.body.getAttribute('data-callback-url');
responseForm.method='POST';
var item1=document.createElement('input');
@@ -1976,9 +1990,4 @@ pub fn extract_field_by_dot_path(
}
#[cfg(test)]
-mod tests {
- #[test]
- fn test_mime_essence() {
- assert_eq!(mime::APPLICATION_JSON.essence_str(), "application/json");
- }
-}
+mod tests;
diff --git a/crates/router/src/services/api/tests.rs b/crates/router/src/services/api/tests.rs
new file mode 100644
index 0000000000..daafe090f3
--- /dev/null
+++ b/crates/router/src/services/api/tests.rs
@@ -0,0 +1,94 @@
+use hyperswitch_masking::Secret;
+
+fn callback_forms() -> [super::RedirectForm; 9] {
+ [
+ super::RedirectForm::BarclaycardAuthSetup {
+ access_token: "token".to_string(),
+ ddc_url: "https://connector.test/ddc".to_string(),
+ reference_id: "reference".to_string(),
+ },
+ super::RedirectForm::BlueSnap {
+ payment_fields_token: "fields".to_string(),
+ },
+ super::RedirectForm::CybersourceAuthSetup {
+ access_token: "token".to_string(),
+ ddc_url: "https://connector.test/ddc".to_string(),
+ reference_id: "reference".to_string(),
+ },
+ super::RedirectForm::Payme,
+ super::RedirectForm::Braintree {
+ client_token: "client".to_string(),
+ card_token: "card".to_string(),
+ bin: "123456".to_string(),
+ acs_url: Secret::new("https://connector.test/acs".to_string()),
+ },
+ super::RedirectForm::Nmi {
+ amount: "100".to_string(),
+ currency: common_enums::Currency::USD,
+ public_key: Secret::new("public".to_string()),
+ customer_vault_id: "vault".to_string(),
+ order_id: "order".to_string(),
+ },
+ super::RedirectForm::Mifinity {
+ initialization_token: "initialization".to_string(),
+ },
+ super::RedirectForm::WorldpayDDCForm {
+ endpoint: url::Url::parse("https://connector.test/ddc").expect("connector URL"),
+ method: common_utils::request::Method::Post,
+ form_fields: Default::default(),
+ collection_id: None,
+ },
+ super::RedirectForm::WorldpayxmlDDCForm {
+ bin: "123456".to_string(),
+ jwt: "jwt".to_string(),
+ },
+ ]
+}
+
+fn render_form(form: &super::RedirectForm, callback: &str) -> String {
+ super::build_redirection_form(
+ form,
+ Some(&Secret::new(callback.to_string())),
+ None,
+ "100".to_string(),
+ "USD".to_string(),
+ super::Settings::default(),
+ )
+ .into_string()
+}
+
+#[test]
+fn callback_url_attribute_escapes_html_without_inserting_the_url_into_scripts() {
+ let callback = "https://router.test/payments/</script>/callback/token?value=\"quoted\"&next=\u{2028}\u{2029}";
+ let attribute = "data-callback-url=\"https://router.test/payments/&lt;/script&gt;/callback/token?value=&quot;quoted&quot;&amp;next=\u{2028}\u{2029}\"";
+ for form in callback_forms() {
+ let html = render_form(&form, callback);
+ assert_eq!(html.matches(attribute).count(), 1);
+ assert!(!html.contains(callback));
+ assert!(html.contains("document.body.getAttribute('data-callback-url')"));
+ }
+}
+
+#[test]
+fn braintree_exposes_distinct_success_and_error_callbacks() {
+ let complete = "https://router.test/redirect/complete/braintree?value=\"quoted\"&next=1";
+ let response = "https://router.test/redirect/response/braintree";
+ let form = super::RedirectForm::Braintree {
+ client_token: "client".to_string(),
+ card_token: "card".to_string(),
+ bin: "123456".to_string(),
+ acs_url: Secret::new(complete.to_string()),
+ };
+ let html = render_form(&form, response);
+ assert!(html.contains(&format!("data-callback-url=\"{response}\"")));
+ assert!(html.contains(
+ "data-complete-callback-url=\"https://router.test/redirect/complete/braintree?value=&quot;quoted&quot;&amp;next=1\""
+ ));
+ assert!(!html.contains(complete));
+ assert!(html.contains("document.body.getAttribute('data-complete-callback-url')"));
+}
+
+#[test]
+fn test_mime_essence() {
+ assert_eq!(mime::APPLICATION_JSON.essence_str(), "application/json");
+}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 2bb507aa97..66eb0c589b 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -1394,6 +1394,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {
setup_future_usage: data.request.setup_future_usage,
off_session: data.request.off_session,
setup_mandate_details: data.request.setup_mandate_details.clone(),
+ router_notification_url: None,
router_return_url: data.request.router_return_url.clone(),
email: data.request.email.clone(),
customer_name: data.request.customer_name.clone(),
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 462ec17fda..f088ba332e 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -23,6 +23,7 @@ pub struct VerifyConnectorData {
impl VerifyConnectorData {
fn get_payment_authorize_data(&self) -> types::PaymentsAuthorizeData {
types::PaymentsAuthorizeData {
+ router_notification_url: None,
payment_method_data: domain::PaymentMethodData::Card(self.card_details.clone()),
email: None,
customer_name: None,
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 9bd8068f68..2551bd7cde 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -1271,11 +1271,14 @@ where
let payment_id = payment_data.get_payment_intent().get_id().to_owned();
let payment_attempt = payment_data.get_payment_attempt().clone();
let created_by = payment_attempt.created_by.clone();
+ let mut sdk_callback_urls =
+ crate::core::payments::callback_urls::SdkCallbackUrls::default();
let payments_response = crate::core::payments::transformers::payments_to_payments_response(
payment_data,
captures,
services::AuthFlow::Merchant,
&state.base_url,
+ state.payment_callback_config().await?.mode,
&operation,
&state.conf.connector_request_reference_id_config,
None,
@@ -1283,7 +1286,9 @@ where
None,
platform.get_processor(),
platform.get_initiator(),
+ &mut sdk_callback_urls,
)?;
+ sdk_callback_urls.persist(state).await?;
let event_type = status.into();
diff --git a/crates/router/src/utils/oidc.rs b/crates/router/src/utils/oidc.rs
index cddfd60d31..fb64fb305e 100644
--- a/crates/router/src/utils/oidc.rs
+++ b/crates/router/src/utils/oidc.rs
@@ -110,7 +110,7 @@ pub fn build_redirection_response(redirect_url: String) -> ApplicationResponse<(
return_url: String::new(),
http_method: String::new(),
params: Vec::new(),
- return_url_with_query_params: redirect_url,
+ return_url_with_query_params: redirect_url.into(),
})
}
@@ -118,7 +118,7 @@ pub fn build_redirection_response(redirect_url: String) -> ApplicationResponse<(
pub fn build_redirection_response(redirect_url: String) -> ApplicationResponse<()> {
use api_models::payments::RedirectionResponse;
ApplicationResponse::JsonForRedirection(RedirectionResponse {
- return_url_with_query_params: redirect_url,
+ return_url_with_query_params: redirect_url.into(),
})
}
diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs
index 7d2c14e8ee..d971609411 100644
--- a/crates/router/tests/connectors/adyen.rs
+++ b/crates/router/tests/connectors/adyen.rs
@@ -189,7 +189,7 @@ impl AdyenTest {
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
- router_return_url: Some(String::from("http://localhost:8080")),
+ router_return_url: Some(String::from("http://localhost:8080").into()),
webhook_url: None,
complete_authorize_url: None,
customer_id: None,
@@ -471,7 +471,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- router_return_url: Some(String::from("http://localhost:8080")),
+ router_return_url: Some(String::from("http://localhost:8080").into()),
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str("4024007134364842").unwrap(),
..utils::CCardType::default().0
@@ -491,7 +491,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- router_return_url: Some(String::from("http://localhost:8080")),
+ router_return_url: Some(String::from("http://localhost:8080").into()),
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
@@ -514,7 +514,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- router_return_url: Some(String::from("http://localhost:8080")),
+ router_return_url: Some(String::from("http://localhost:8080").into()),
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
@@ -535,7 +535,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- router_return_url: Some(String::from("http://localhost:8080")),
+ router_return_url: Some(String::from("http://localhost:8080").into()),
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs
index 324aadcac9..e7eefa9834 100644
--- a/crates/router/tests/connectors/airwallex.rs
+++ b/crates/router/tests/connectors/airwallex.rs
@@ -90,8 +90,8 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
co_badged_card_data: None,
}),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
- router_return_url: Some("https://google.com".to_string()),
- complete_authorize_url: Some("https://google.com".to_string()),
+ router_return_url: Some("https://google.com".to_string().into()),
+ complete_authorize_url: Some("https://google.com".to_string().into()),
..utils::PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs
index f68aa3ed09..d800dee664 100644
--- a/crates/router/tests/connectors/bitpay.rs
+++ b/crates/router/tests/connectors/bitpay.rs
@@ -89,7 +89,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
- router_return_url: Some(String::from("https://google.com/")),
+ router_return_url: Some(String::from("https://google.com/").into()),
webhook_url: Some(String::from("https://google.com/")),
complete_authorize_url: None,
capture_method: None,
diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs
index 61d2bef797..5ad39ab1a9 100644
--- a/crates/router/tests/connectors/cashtocode.rs
+++ b/crates/router/tests/connectors/cashtocode.rs
@@ -63,7 +63,7 @@ impl CashtocodeTest {
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
- router_return_url: Some(String::from("https://google.com")),
+ router_return_url: Some(String::from("https://google.com").into()),
webhook_url: None,
complete_authorize_url: None,
customer_id: cust_id.ok(),
diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs
index 7ae2b5c2aa..3fd19dc3b1 100644
--- a/crates/router/tests/connectors/coinbase.rs
+++ b/crates/router/tests/connectors/coinbase.rs
@@ -91,7 +91,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
- router_return_url: Some(String::from("https://google.com/")),
+ router_return_url: Some(String::from("https://google.com/").into()),
webhook_url: None,
complete_authorize_url: None,
capture_method: None,
diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs
index 466a2a9cc4..98f7cacd4c 100644
--- a/crates/router/tests/connectors/cryptopay.rs
+++ b/crates/router/tests/connectors/cryptopay.rs
@@ -88,7 +88,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
- router_return_url: Some(String::from("https://google.com/")),
+ router_return_url: Some(String::from("https://google.com/").into()),
webhook_url: None,
complete_authorize_url: None,
capture_method: None,
diff --git a/crates/router/tests/connectors/iatapay.rs b/crates/router/tests/connectors/iatapay.rs
index 3b0bfeb54a..93a002a1bf 100644
--- a/crates/router/tests/connectors/iatapay.rs
+++ b/crates/router/tests/connectors/iatapay.rs
@@ -85,7 +85,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> {
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- router_return_url: Some("https://hyperswitch.io".to_string()),
+ router_return_url: Some("https://hyperswitch.io".to_string().into()),
webhook_url: Some("https://hyperswitch.io".to_string()),
currency: enums::Currency::EUR,
..PaymentAuthorizeType::default().0
diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs
index cb62f8184e..e9c03c6b87 100644
--- a/crates/router/tests/connectors/nexinets.rs
+++ b/crates/router/tests/connectors/nexinets.rs
@@ -46,7 +46,7 @@ fn payment_method_details() -> Option<PaymentsAuthorizeData> {
card_number: CardNumber::from_str("374111111111111").unwrap(),
..utils::CCardType::default().0
}),
- router_return_url: Some("https://google.com".to_string()),
+ router_return_url: Some("https://google.com".to_string().into()),
..utils::PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs
index 76fdffda3f..220e6c8c6e 100644
--- a/crates/router/tests/connectors/opennode.rs
+++ b/crates/router/tests/connectors/opennode.rs
@@ -89,7 +89,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
- router_return_url: Some(String::from("https://google.com/")),
+ router_return_url: Some(String::from("https://google.com/").into()),
webhook_url: Some(String::from("https://google.com/")),
complete_authorize_url: None,
capture_method: None,
diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs
index 2ee4ea8afb..f01b26e134 100644
--- a/crates/router/tests/connectors/payme.rs
+++ b/crates/router/tests/connectors/payme.rs
@@ -103,7 +103,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
discount_percentage: None,
discount_type: None,
}]),
- router_return_url: Some("https://hyperswitch.io".to_string()),
+ router_return_url: Some("https://hyperswitch.io".to_string().into()),
webhook_url: Some("https://hyperswitch.io".to_string()),
email: Some(Email::from_str("[email protected]").unwrap()),
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
@@ -416,7 +416,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
discount_percentage: None,
discount_type: None,
}]),
- router_return_url: Some("https://hyperswitch.io".to_string()),
+ router_return_url: Some("https://hyperswitch.io".to_string().into()),
webhook_url: Some("https://hyperswitch.io".to_string()),
email: Some(Email::from_str("[email protected]").unwrap()),
..PaymentAuthorizeType::default().0
@@ -468,7 +468,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
discount_percentage: None,
discount_type: None,
}]),
- router_return_url: Some("https://hyperswitch.io".to_string()),
+ router_return_url: Some("https://hyperswitch.io".to_string().into()),
webhook_url: Some("https://hyperswitch.io".to_string()),
email: Some(Email::from_str("[email protected]").unwrap()),
..PaymentAuthorizeType::default().0
@@ -520,7 +520,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
discount_percentage: None,
discount_type: None,
}]),
- router_return_url: Some("https://hyperswitch.io".to_string()),
+ router_return_url: Some("https://hyperswitch.io".to_string().into()),
webhook_url: Some("https://hyperswitch.io".to_string()),
email: Some(Email::from_str("[email protected]").unwrap()),
..PaymentAuthorizeType::default().0
diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs
index 6eea9aa7e1..70761552af 100644
--- a/crates/router/tests/connectors/trustpay.rs
+++ b/crates/router/tests/connectors/trustpay.rs
@@ -66,7 +66,7 @@ fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData>
..utils::CCardType::default().0
}),
browser_info: Some(get_default_browser_info()),
- router_return_url: Some(String::from("http://localhost:8080")),
+ router_return_url: Some(String::from("http://localhost:8080").into()),
..utils::PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index cae88525df..b098b9f0f0 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -994,6 +994,7 @@ impl Default for CCardType {
impl Default for PaymentAuthorizeType {
fn default() -> Self {
let data = types::PaymentsAuthorizeData {
+ router_notification_url: None,
payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0),
amount: 100,
minor_amount: MinorUnit::new(100),
diff --git a/crates/router/tests/payment_callback_urls.rs b/crates/router/tests/payment_callback_urls.rs
new file mode 100644
index 0000000000..56ed9bc7ed
--- /dev/null
+++ b/crates/router/tests/payment_callback_urls.rs
@@ -0,0 +1,5 @@
+#![cfg(feature = "v1")]
+
+#[cfg(test)]
+#[path = "payment_callback_urls/tests/mod.rs"]
+mod tests;
diff --git a/crates/router/tests/payment_callback_urls/tests/connector_callback_urls.rs b/crates/router/tests/payment_callback_urls/tests/connector_callback_urls.rs
new file mode 100644
index 0000000000..8f3f7d1413
--- /dev/null
+++ b/crates/router/tests/payment_callback_urls/tests/connector_callback_urls.rs
@@ -0,0 +1,248 @@
+use common_utils::id_type::PaymentId;
+use hyperswitch_domain_models::router_response_types::RedirectCallback;
+use hyperswitch_interfaces::api::ConnectorRedirectResponse;
+use hyperswitch_masking::PeekInterface;
+use router::{
+ core::{
+ configs::payment_callback::PaymentCallbackMode,
+ payments::callback_urls::ConnectorCallbackUrls,
+ },
+ routes::payments::{
+ callback_routes::ConnectorCallbackPath, callback_tokens::PaymentCallbackUrl,
+ },
+ types::api::ConnectorData,
+};
+
+use super::callback_path_and_token;
+
+#[test]
+fn browser_and_notification_callbacks_have_independent_tokens() {
+ let payment_id = PaymentId::wrap("pay_1".to_string()).expect("payment ID");
+ let merchant_id =
+ common_utils::id_type::MerchantId::wrap("merchant_1".to_string()).expect("merchant ID");
+ for mode in [
+ PaymentCallbackMode::Legacy,
+ PaymentCallbackMode::Migration,
+ PaymentCallbackMode::Enforced,
+ ] {
+ for creds in [None, Some("creds_1")] {
+ for (connector, action) in [("hipay", "response"), ("paybox", "complete")] {
+ let selected_callback = ConnectorData::convert_connector(connector)
+ .expect("connector")
+ .get_notification_callback();
+ let expected_callback = if action == "response" {
+ RedirectCallback::Response
+ } else {
+ RedirectCallback::Complete
+ };
+ assert_eq!(selected_callback, Some(expected_callback));
+ let path = ConnectorCallbackPath {
+ payment_id: payment_id.clone(),
+ merchant_id: merchant_id.clone(),
+ connector: connector.to_string(),
+ };
+ let mut callbacks = ConnectorCallbackUrls::default();
+ let notification = callbacks
+ .notification_url(selected_callback, "https://router.test", mode, &path, creds)
+ .expect("notification callback");
+ let browser = match expected_callback {
+ RedirectCallback::Response => callbacks.redirect_response_url(
+ "https://router.test",
+ mode,
+ &payment_id,
+ &merchant_id,
+ connector,
+ creds,
+ ),
+ RedirectCallback::Complete => callbacks.redirect_complete_url(
+ "https://router.test",
+ mode,
+ &payment_id,
+ &merchant_id,
+ connector,
+ creds,
+ ),
+ }
+ .clone();
+ let creds_path = creds.map(|value| format!("/{value}")).unwrap_or_default();
+ let expected = format!(
+ "https://router.test/payments/pay_1/merchant_1/redirect/{action}/{connector}{creds_path}"
+ );
+ if mode.issues_tokens() {
+ let (browser_path, browser_token) = callback_path_and_token(browser.peek());
+ let (notification_path, notification_token) =
+ callback_path_and_token(notification.peek());
+ let expected = format!(
+ "https://router.test/payments/pay_1/merchant_1/redirect/token/{{callback_token}}/{action}/{connector}{creds_path}"
+ );
+ assert_eq!(browser_path, expected);
+ assert_eq!(notification_path, expected);
+ assert_ne!(browser_token, notification_token);
+ } else {
+ assert_eq!(browser.peek(), &expected);
+ assert_eq!(notification.peek(), &expected);
+ }
+ assert_eq!(
+ callbacks.notification.as_ref().map(PaymentCallbackUrl::url),
+ Some(&notification)
+ );
+ assert_eq!(
+ callbacks.notification_url(
+ selected_callback,
+ "https://router.test",
+ mode,
+ &path,
+ creds,
+ ),
+ Some(notification)
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn connectors_without_notifications_do_not_allocate_callback_urls() {
+ for connector in ["stripe", "recurly"] {
+ let selected_callback = ConnectorData::convert_connector(connector)
+ .expect("connector")
+ .get_notification_callback();
+ assert_eq!(selected_callback, None);
+ let mut callbacks = ConnectorCallbackUrls::default();
+ assert!(callbacks
+ .notification_url(
+ selected_callback,
+ "https://router.test",
+ PaymentCallbackMode::Enforced,
+ &ConnectorCallbackPath {
+ payment_id: PaymentId::wrap("pay_1".to_string()).expect("payment ID"),
+ merchant_id: common_utils::id_type::MerchantId::wrap("merchant_1".to_string())
+ .expect("merchant ID"),
+ connector: connector.to_string(),
+ },
+ None,
+ )
+ .is_none());
+ assert!(callbacks.notification.is_none());
+ assert!(callbacks.redirect_response.is_none());
+ assert!(callbacks.redirect_complete.is_none());
+ }
+}
+
+#[test]
+fn notification_endpoint_selection_does_not_depend_on_connector_name() {
+ let path = ConnectorCallbackPath {
+ payment_id: PaymentId::wrap("pay_1".to_string()).expect("payment ID"),
+ merchant_id: common_utils::id_type::MerchantId::wrap("merchant_1".to_string())
+ .expect("merchant ID"),
+ connector: "custom_processor".to_string(),
+ };
+ for (callback, action) in [
+ (RedirectCallback::Response, "response"),
+ (RedirectCallback::Complete, "complete"),
+ ] {
+ let mut callbacks = ConnectorCallbackUrls::default();
+ let url = callbacks
+ .notification_url(
+ Some(callback),
+ "https://router.test",
+ PaymentCallbackMode::Enforced,
+ &path,
+ None,
+ )
+ .expect("notification callback");
+ assert_eq!(callback_path_and_token(url.peek()).0, format!(
+ "https://router.test/payments/pay_1/merchant_1/redirect/token/{{callback_token}}/{action}/custom_processor"
+ ));
+ }
+}
+
+#[test]
+fn connector_urls_are_lazy_cached_and_preserve_route_variants() {
+ let payment_id = PaymentId::wrap("pay_1".to_string()).expect("payment ID");
+ let merchant_id =
+ common_utils::id_type::MerchantId::wrap("merchant_1".to_string()).expect("merchant ID");
+ for mode in [
+ PaymentCallbackMode::Legacy,
+ PaymentCallbackMode::Migration,
+ PaymentCallbackMode::Enforced,
+ ] {
+ for creds in [None, Some("creds_1")] {
+ let mut callbacks = ConnectorCallbackUrls::default();
+ assert!(callbacks.redirect_response.is_none());
+ assert!(callbacks.redirect_complete.is_none());
+ let response = callbacks
+ .redirect_response_url(
+ "https://router.test",
+ mode,
+ &payment_id,
+ &merchant_id,
+ "stripe",
+ creds,
+ )
+ .clone();
+ assert!(callbacks.redirect_response.is_some());
+ assert!(callbacks.redirect_complete.is_none());
+ assert_eq!(
+ callbacks.redirect_response_url(
+ "https://other-router.test",
+ mode,
+ &payment_id,
+ &merchant_id,
+ "adyen",
+ None,
+ ),
+ &response
+ );
+ let complete = callbacks
+ .redirect_complete_url(
+ "https://router.test",
+ mode,
+ &payment_id,
+ &merchant_id,
+ "stripe",
+ creds,
+ )
+ .clone();
+ assert_eq!(
+ callbacks.redirect_complete_url(
+ "https://other-router.test",
+ mode,
+ &payment_id,
+ &merchant_id,
+ "adyen",
+ None,
+ ),
+ &complete
+ );
+ assert_eq!(
+ callbacks
+ .redirect_response
+ .as_ref()
+ .map(PaymentCallbackUrl::url),
+ Some(&response)
+ );
+ for (action, callback) in [("response", response), ("complete", complete)] {
+ let url = url::Url::parse(callback.peek()).expect("callback URL");
+ let creds_path = creds.map(|value| format!("/{value}")).unwrap_or_default();
+ let expected =
+ format!("/payments/pay_1/merchant_1/redirect/{action}/stripe{creds_path}");
+ if mode == PaymentCallbackMode::Legacy {
+ assert_eq!(url.path(), expected);
+ } else {
+ let (path, token) = callback_path_and_token(url.path());
+ assert_eq!(path, format!(
+ "/payments/pay_1/merchant_1/redirect/token/{{callback_token}}/{action}/stripe{creds_path}"
+ ));
+ assert_eq!(
+ uuid::Uuid::parse_str(token)
+ .expect("UUID")
+ .get_version_num(),
+ 4
+ );
+ }
+ assert!(url.query().is_none());
+ }
+ }
+ }
+}
diff --git a/crates/router/tests/payment_callback_urls/tests/mod.rs b/crates/router/tests/payment_callback_urls/tests/mod.rs
new file mode 100644
index 0000000000..dcc0db4b83
--- /dev/null
+++ b/crates/router/tests/payment_callback_urls/tests/mod.rs
@@ -0,0 +1,11 @@
+mod connector_callback_urls;
+mod sdk_callback_urls;
+
+fn callback_path_and_token(path: &str) -> (String, &str) {
+ let (prefix, remaining) = path.split_once("/redirect/token/").expect("token path");
+ let (token, suffix) = remaining.split_once('/').expect("callback action");
+ (
+ format!("{prefix}/redirect/token/{{callback_token}}/{suffix}"),
+ token,
+ )
+}
diff --git a/crates/router/tests/payment_callback_urls/tests/sdk_callback_urls.rs b/crates/router/tests/payment_callback_urls/tests/sdk_callback_urls.rs
new file mode 100644
index 0000000000..b7464e6cd0
--- /dev/null
+++ b/crates/router/tests/payment_callback_urls/tests/sdk_callback_urls.rs
@@ -0,0 +1,328 @@
+use common_enums::Currency;
+use common_utils::id_type::PaymentId;
+use hyperswitch_domain_models::router_response_types::{RedirectCallback, RedirectForm};
+use hyperswitch_interfaces::api::{ConnectorCommon, ConnectorRedirectResponse};
+use hyperswitch_masking::PeekInterface;
+use router::{
+ core::{
+ configs::payment_callback::PaymentCallbackMode,
+ payments::{callback_urls::SdkCallbackUrls, transformers::next_action_invoke_ddc_iframe},
+ },
+ routes::payments::callback_routes::{ConnectorCallbackPath, StartCallbackPath},
+ types::api::ConnectorData,
+};
+
+use super::callback_path_and_token;
+
+fn payment_id(value: &str) -> PaymentId {
+ PaymentId::wrap(value.to_string()).expect("payment ID")
+}
+fn merchant_id(value: &str) -> common_utils::id_type::MerchantId {
+ common_utils::id_type::MerchantId::wrap(value.to_string()).expect("merchant ID")
+}
+
+#[test]
+fn ddc_next_action_uses_a_collected_start_url_in_every_mode() {
+ let path = StartCallbackPath {
+ payment_id: payment_id("pay"),
+ merchant_id: merchant_id("merchant"),
+ attempt_id: "attempt".into(),
+ };
+ let metadata = serde_json::json!({
+ "iframe_url": "/payments/redirect/old_pay/old_merchant/old_attempt",
+ "timeout_ms": 1000,
+ });
+ for mode in [
+ PaymentCallbackMode::Legacy,
+ PaymentCallbackMode::Migration,
+ PaymentCallbackMode::Enforced,
+ ] {
+ let mut callbacks = SdkCallbackUrls::default();
+ let ddc = next_action_invoke_ddc_iframe(
+ Some(&metadata),
+ "https://router.test",
+ mode,
+ &path,
+ &mut callbacks,
+ )
+ .expect("next action")
+ .expect("DDC");
+ assert_eq!(ddc.timeout_ms, Some(1000));
+ assert_eq!(
+ ddc.iframe_url.as_str(),
+ callbacks
+ .start
+ .as_ref()
+ .expect("pending start URL")
+ .url()
+ .peek()
+ );
+ if mode.issues_tokens() {
+ assert_eq!(
+ callback_path_and_token(ddc.iframe_url.path()).0,
+ "/payments/pay/merchant/redirect/token/{callback_token}/start/attempt"
+ );
+ } else {
+ assert_eq!(
+ ddc.iframe_url.path(),
+ "/payments/redirect/pay/merchant/attempt"
+ );
+ }
+ }
+ for metadata in [None, Some(serde_json::json!({"unrelated": true}))] {
+ let mut callbacks = SdkCallbackUrls::default();
+ assert!(next_action_invoke_ddc_iframe(
+ metadata.as_ref(),
+ "https://router.test",
+ PaymentCallbackMode::Enforced,
+ &path,
+ &mut callbacks
+ )
+ .expect("unrelated metadata")
+ .is_none());
+ assert!(callbacks.start.is_none());
+ }
+}
+
+#[test]
+fn sdk_url_methods_reuse_cached_urls_and_populate_only_their_field() {
+ let mut callbacks = SdkCallbackUrls::default();
+ let start = callbacks
+ .start_url(
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &payment_id("pay"),
+ &merchant_id("merchant"),
+ "attempt",
+ )
+ .clone();
+ assert!(callbacks.authorize.is_none());
+ assert!(callbacks.redirect_response.is_none());
+ assert_eq!(
+ callbacks.start_url(
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &payment_id("pay"),
+ &merchant_id("merchant"),
+ "attempt"
+ ),
+ &start
+ );
+ let authorize = callbacks
+ .authorize_url(
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &payment_id("pay"),
+ &merchant_id("merchant"),
+ "stripe",
+ )
+ .clone();
+ assert!(callbacks.redirect_response.is_none());
+ assert_eq!(
+ callbacks.authorize_url(
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &payment_id("pay"),
+ &merchant_id("merchant"),
+ "stripe"
+ ),
+ &authorize
+ );
+ let redirect = callbacks
+ .redirect_response_url(
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &payment_id("pay"),
+ &merchant_id("merchant"),
+ "stripe",
+ Some("creds"),
+ )
+ .clone();
+ assert_eq!(
+ callback_path_and_token(
+ url::Url::parse(redirect.peek())
+ .expect("redirect URL")
+ .path()
+ )
+ .0,
+ "/payments/pay/merchant/redirect/token/{callback_token}/response/stripe/creds"
+ );
+ assert_eq!(
+ callbacks.redirect_response_url(
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &payment_id("pay"),
+ &merchant_id("merchant"),
+ "stripe",
+ None
+ ),
+ &redirect
+ );
+}
+
+#[test]
+fn browser_forms_construct_only_the_required_callback_endpoint() {
+ let forms = [
+ (RedirectForm::Payme, "payme", false),
+ (
+ RedirectForm::BlueSnap {
+ payment_fields_token: "fields".into(),
+ },
+ "bluesnap",
+ false,
+ ),
+ (
+ RedirectForm::BarclaycardAuthSetup {
+ access_token: "token".into(),
+ ddc_url: "https://connector.test".into(),
+ reference_id: "reference".into(),
+ },
+ "barclaycard",
+ false,
+ ),
+ (
+ RedirectForm::CybersourceAuthSetup {
+ access_token: "token".into(),
+ ddc_url: "https://connector.test".into(),
+ reference_id: "reference".into(),
+ },
+ "cybersource",
+ false,
+ ),
+ (
+ RedirectForm::Braintree {
+ client_token: "client".into(),
+ card_token: "card".into(),
+ bin: "123456".into(),
+ acs_url: "https://connector.test".to_string().into(),
+ },
+ "braintree",
+ true,
+ ),
+ (
+ RedirectForm::Mifinity {
+ initialization_token: "initialization".into(),
+ },
+ "mifinity",
+ true,
+ ),
+ (
+ RedirectForm::Nmi {
+ amount: "100".into(),
+ currency: Currency::USD,
+ public_key: "public".to_string().into(),
+ customer_vault_id: "vault".into(),
+ order_id: "order".into(),
+ },
+ "nmi",
+ false,
+ ),
+ (
+ RedirectForm::WorldpayDDCForm {
+ endpoint: url::Url::parse("https://connector.test").expect("connector URL"),
+ method: common_utils::request::Method::Post,
+ form_fields: Default::default(),
+ collection_id: None,
+ },
+ "worldpay",
+ false,
+ ),
+ (
+ RedirectForm::WorldpayxmlDDCForm {
+ bin: "123456".into(),
+ jwt: "jwt".into(),
+ },
+ "worldpayxml",
+ false,
+ ),
+ ];
+ for (form, connector, is_response) in forms {
+ let connector_instance = ConnectorData::convert_connector(connector).expect("connector");
+ let selected_callback = connector_instance.get_redirect_callback(&form);
+ assert_eq!(
+ selected_callback,
+ Some(if is_response {
+ RedirectCallback::Response
+ } else {
+ RedirectCallback::Complete
+ })
+ );
+ let path = ConnectorCallbackPath {
+ payment_id: payment_id("pay"),
+ merchant_id: merchant_id("merchant"),
+ connector: connector_instance.id().to_string(),
+ };
+ let mut callbacks = SdkCallbackUrls::default();
+ let callback = callbacks
+ .redirection_form_callback_url(
+ selected_callback,
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &path,
+ None,
+ )
+ .expect("browser callback")
+ .clone();
+ let url = url::Url::parse(callback.peek()).expect("URL");
+ let action = if is_response { "response" } else { "complete" };
+ assert_eq!(
+ callback_path_and_token(url.path()).0,
+ format!(
+ "/payments/pay/merchant/redirect/token/{{callback_token}}/{action}/{connector}"
+ )
+ );
+ assert!(url.query().is_none());
+ assert!(callbacks.start.is_none());
+ assert!(callbacks.authorize.is_none());
+ assert_eq!(callbacks.redirect_response.is_some(), is_response);
+ assert_eq!(callbacks.redirect_complete.is_some(), !is_response);
+ assert_eq!(
+ callbacks.redirection_form_callback_url(
+ selected_callback,
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &ConnectorCallbackPath {
+ payment_id: payment_id("other_pay"),
+ merchant_id: merchant_id("merchant"),
+ connector: connector.to_string(),
+ },
+ None
+ ),
+ Some(&callback)
+ );
+ let pending = if is_response {
+ callbacks.redirect_response.as_ref()
+ } else {
+ callbacks.redirect_complete.as_ref()
+ }
+ .expect("prepared browser callback");
+ assert_eq!(pending.url(), &callback);
+ }
+}
+
+#[test]
+fn html_forms_do_not_generate_unused_callback_urls() {
+ let connector = ConnectorData::convert_connector("stripe").expect("connector");
+ let callback = connector.get_redirect_callback(&RedirectForm::Html {
+ html_data: "<html></html>".to_string().into(),
+ });
+ assert_eq!(callback, None);
+ let mut callbacks = SdkCallbackUrls::default();
+ assert!(callbacks
+ .redirection_form_callback_url(
+ callback,
+ "https://router.test",
+ PaymentCallbackMode::Migration,
+ &ConnectorCallbackPath {
+ payment_id: payment_id("pay"),
+ merchant_id: merchant_id("merchant"),
+ connector: connector.id().to_string(),
+ },
+ None
+ )
+ .is_none());
+ assert!(callbacks.start.is_none());
+ assert!(callbacks.authorize.is_none());
+ assert!(callbacks.redirect_response.is_none());
+ assert!(callbacks.redirect_complete.is_none());
+}
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index 1fc93471b5..54a2529357 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -12,6 +12,8 @@ pub mod metrics;
#[cfg(feature = "actix_web")]
pub mod request_id;
#[cfg(feature = "actix_web")]
+pub mod request_path;
+#[cfg(feature = "actix_web")]
pub mod root_span;
/// `cargo` build instructions generation for obtaining information about the application
/// environment.
diff --git a/crates/router_env/src/request_id.rs b/crates/router_env/src/request_id.rs
index d5e93164dd..bede8fc1b0 100644
--- a/crates/router_env/src/request_id.rs
+++ b/crates/router_env/src/request_id.rs
@@ -162,14 +162,15 @@ pub(crate) mod boundary {
.map(ToOwned::to_owned)
}
- // `headers` and `request_body` can carry auth tokens / cardholder data / PII,
+ // Paths, queries, headers, and bodies can carry auth tokens / cardholder data / PII,
// so they are `Secret`: the derived `Debug` redacts them, and the raw value is
// exposed only at the deja recording boundary (`args`).
#[derive(Debug)]
pub(super) struct IncomingHttpRecord {
method: String,
- path: String,
- query: String,
+ path: Secret<String>,
+ logged_path: String,
+ query: Secret<String>,
request_id: String,
headers: Secret<serde_json::Value>,
content_type: Option<String>,
@@ -181,8 +182,8 @@ pub(crate) mod boundary {
fn args(&self) -> serde_json::Value {
json!({
"method": self.method.as_str(),
- "path": self.path.as_str(),
- "query": self.query.as_str(),
+ "path": self.path.peek().as_str(),
+ "query": self.query.peek().as_str(),
"request_id": self.request_id.as_str(),
"headers": self.headers.peek().clone(),
"content_type": self.content_type.as_deref(),
@@ -197,7 +198,8 @@ pub(crate) mod boundary {
request_id: &str,
) -> (ServiceRequest, IncomingHttpRecord) {
let method = request.method().as_str().to_string();
- let path = request.path().to_string();
+ let path = Secret::new(request.path().to_owned());
+ let logged_path = crate::request_path::path_for_telemetry(request.request()).into_owned();
let query = request.query_string().to_string();
let headers = headers_json(request.headers());
let content_type = request
@@ -226,7 +228,8 @@ pub(crate) mod boundary {
let record = IncomingHttpRecord {
method,
path,
- query,
+ logged_path,
+ query: Secret::new(query),
request_id: request_id.to_string(),
headers: Secret::new(headers),
content_type,
@@ -480,8 +483,8 @@ pub(crate) mod boundary {
) -> serde_json::Value {
json!({
"method": record.method.as_str(),
- "path": record.path.as_str(),
- "query": record.query.as_str(),
+ "path": record.logged_path.as_str(),
+ "query": record.query.peek().as_str(),
"request_id": record.request_id.as_str(),
"status": response.status().as_u16(),
})
@@ -491,8 +494,8 @@ pub(crate) mod boundary {
let status = error.as_response_error().status_code();
json!({
"method": record.method.as_str(),
- "path": record.path.as_str(),
- "query": record.query.as_str(),
+ "path": record.logged_path.as_str(),
+ "query": record.query.peek().as_str(),
"request_id": record.request_id.as_str(),
"status": status.as_u16(),
"error": error.to_string(),
@@ -631,7 +634,7 @@ pub struct RequestRecordingFacts {
pub request_id: String,
/// HTTP method observed at ingress.
pub method: String,
- /// HTTP path observed at ingress.
+ /// HTTP path with callback tokens hidden, or "/unmatched".
pub path: String,
}
@@ -1044,7 +1047,7 @@ where
let request_facts = RequestRecordingFacts {
request_id: request_id.to_string(),
method: request.method().as_str().to_owned(),
- path: request.path().to_owned(),
+ path: crate::request_path::path_for_telemetry(request.request()).into_owned(),
};
let recording_sampler = self.recording_sampler.clone();
@@ -1217,295 +1220,4 @@ impl FromRequest for RequestId {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- /// Regression sentinel for the ingress circular-dependency bug.
- ///
- /// The opt-in recording flip made `RecordingHook::mode()` return `Record`
- /// only while a per-correlation decision is pushed. The ingress middleware
- /// is what pushes that decision, so gating ingress on `mode()` was circular:
- /// `mode()` is `Disabled` at ingress (no decision yet) → the predicate is
- /// false → the sampler never runs → no decision is ever pushed → nothing is
- /// ever recorded (the empty-tape bug).
- ///
- /// The fix routes the ingress predicates through `process_mode()`, which
- /// reflects the boot-time configuration and ignores the per-request gate.
- /// This test pins the exact pivot at the type level, with no global install
- /// and no async: a fresh recorder with no decision in scope must report
- /// `process_mode() == Record` (ingress may proceed) while `mode() ==
- /// Disabled` (the boundary gate still governs actual capture). On the old
- /// code the first assertion is what the middleware needed and never got.
- #[cfg(feature = "deja")]
- #[test]
- fn ingress_process_mode_is_record_before_any_decision_is_pushed() {
- struct NullSink;
- impl deja::RecordSink<deja::DejaRecord> for NullSink {
- fn write_batch(&mut self, _records: &[deja::DejaRecord]) -> std::io::Result<()> {
- Ok(())
- }
- fn flush(&mut self) -> std::io::Result<()> {
- Ok(())
- }
- }
-
- let hook = deja::RecordingHook::with_sink(
- NullSink,
- "ingress-sentinel".to_string(),
- deja::WriterConfig::default(),
- );
-
- // No per-correlation decision has been pushed for this thread.
- assert_eq!(
- deja::DejaHook::process_mode(&hook),
- deja::RuntimeMode::Record,
- "ingress predicate must see Record from process config alone, or the \
- middleware can never push the decision that flips the boundary gate"
- );
- assert_eq!(
- deja::DejaHook::capture_verdict(&hook),
- deja::CaptureVerdict::SkipNoDecision,
- "the per-boundary capture gate must stay closed until a decision is \
- pushed — the split is what breaks the ingress circular dependency"
- );
- }
-
- #[test]
- fn request_identifier_builder_keeps_explicit_header_and_id_reuse_without_sampler() {
- let identifier =
- RequestIdentifier::new("x-correlation-id").use_incoming_id(IdReuse::IgnoreIncoming);
-
- assert_eq!(identifier.header_name(), "x-correlation-id");
- assert_eq!(identifier.id_reuse_strategy(), IdReuse::IgnoreIncoming);
- }
-
- #[cfg(feature = "deja")]
- struct RejectAllSampler;
-
- #[cfg(feature = "deja")]
- impl RequestRecordingSampler for RejectAllSampler {
- fn should_record(
- &self,
- _facts: RequestRecordingFacts,
- ) -> RequestRecordingSamplerFuture<'_> {
- Box::pin(ready(false))
- }
- }
-
- #[cfg(feature = "deja")]
- struct EmptyLookup;
-
- #[cfg(feature = "deja")]
- impl deja::LookupTableSource for EmptyLookup {
- fn load(&mut self) -> std::io::Result<deja::LookupTable> {
- Ok(deja::LookupTable {
- recording_id: "empty".to_string(),
- policy_version: 1,
- event_schema_version: Some(deja::CURRENT_EVENT_SCHEMA_VERSION),
- entries: Vec::new(),
- identity_entries: Vec::new(),
- })
- }
- }
-
- #[cfg(feature = "deja")]
- struct ObservedRecordingHook {
- recorded: std::sync::Mutex<Vec<deja::BoundaryEvent>>,
- }
-
- #[cfg(feature = "deja")]
- impl ObservedRecordingHook {
- fn new() -> Self {
- Self {
- recorded: std::sync::Mutex::new(Vec::new()),
- }
- }
-
- fn recorded_len(&self) -> usize {
- self.recorded.lock().expect("recording hook lock").len()
- }
-
- fn recorded_events(&self) -> Vec<deja::BoundaryEvent> {
- self.recorded.lock().expect("recording hook lock").clone()
- }
- }
-
- #[cfg(feature = "deja")]
- impl deja::DejaHook for ObservedRecordingHook {
- fn process_mode(&self) -> deja::RuntimeMode {
- deja::RuntimeMode::Record
- }
-
- fn record(&self, event: deja::BoundaryEvent) {
- self.recorded
- .lock()
- .expect("recording hook lock")
- .push(event);
- }
-
- fn next_global_sequence(&self) -> u64 {
- 150
- }
-
- fn next_request_sequence(&self, _correlation_id: Option<&str>) -> u64 {
- 1
- }
- }
-
- #[cfg(feature = "deja")]
- struct ExactSizedNeverEofBody {
- chunk: Option<bytes::Bytes>,
- size: u64,
- }
-
- #[cfg(feature = "deja")]
- impl ExactSizedNeverEofBody {
- fn new(chunk: &'static [u8]) -> Self {
- Self {
- chunk: Some(bytes::Bytes::from_static(chunk)),
- size: u64::try_from(chunk.len()).unwrap_or(u64::MAX),
- }
- }
- }
-
- #[cfg(feature = "deja")]
- impl actix_web::body::MessageBody for ExactSizedNeverEofBody {
- type Error = actix_web::Error;
-
- fn size(&self) -> actix_web::body::BodySize {
- actix_web::body::BodySize::Sized(self.size)
- }
-
- fn poll_next(
- mut self: Pin<&mut Self>,
- _cx: &mut Context<'_>,
- ) -> Poll<Option<Result<bytes::Bytes, Self::Error>>> {
- match self.chunk.take() {
- Some(chunk) => Poll::Ready(Some(Ok(chunk))),
- None => Poll::Pending,
- }
- }
- }
-
- #[cfg(feature = "deja")]
- #[test]
- fn recording_body_finalizes_exact_sized_body_after_matching_chunk_without_eof() {
- let hook = Arc::new(ObservedRecordingHook::new());
- let hook_dyn: Arc<dyn deja::DejaHook> = hook.clone();
- let event = deja::EventBuilder::start_with_correlation_id(
- hook_dyn.as_ref(),
- "http_incoming",
- "RequestIdMiddleware",
- "call",
- std::panic::Location::caller(),
- Some("97cd".to_string()),
- serde_json::json!({ "path": "/payments/confirm" }),
- );
- let finalizer = deja::LazyEventFinalizer::new(
- event,
- hook_dyn,
- serde_json::json!({ "status": 200 }),
- false,
- );
- let mut body = boundary::RecordingBody::for_test_with_finalizer(
- ExactSizedNeverEofBody::new(b"{\"ok\":true}"),
- finalizer,
- );
- let waker = std::task::Waker::noop();
- let mut context = Context::from_waker(waker);
-
- let first_poll = actix_web::body::MessageBody::poll_next(Pin::new(&mut body), &mut context);
-
- let Poll::Ready(Some(Ok(chunk))) = first_poll else {
- panic!("first poll must yield the exact-sized body chunk before the body parks");
- };
- assert_eq!(&chunk[..], br#"{"ok":true}"#);
- assert_eq!(
- hook.recorded_len(),
- 1,
- "exact-sized bodies must finalize as soon as the declared bytes are captured, without waiting for EOF or drop"
- );
-
- let events = hook.recorded_events();
- let event = events.first().expect("finalized http_incoming event");
- assert_eq!(event.global_sequence, 150);
- assert_eq!(event.correlation_id.as_deref(), Some("97cd"));
- assert_eq!(event.boundary, "http_incoming");
- assert_eq!(
- event
- .result
- .get("response_body")
- .and_then(|body| body.get("text"))
- .and_then(serde_json::Value::as_str),
- Some(r#"{"ok":true}"#)
- );
- }
-
- #[cfg(feature = "deja")]
- #[tokio::test]
- async fn spawn_fork_runs_without_waiting_for_body_eof() {
- // Stamp-only model: fork work is spawned immediately with span-derived
- // lineage stamps — nothing queues, nothing drains at body EOF, and the
- // recorder never reshapes scheduling.
- let hook =
- deja::LookupTableHook::from_source(EmptyLookup, deja::InMemoryObservedSink::new())
- .expect("lookup replay hook");
- match deja::set_global_runtime_hook(Some(deja::RuntimeHook::LookupReplay(hook))) {
- Ok(()) => {}
- Err(_) if deja::runtime_mode().is_replay() => {}
- Err(err) => panic!("install replay hook: {err}"),
- }
-
- let (tx, rx) = std::sync::mpsc::channel();
- async move {
- deja::spawn_fork(async move {
- tx.send(()).expect("test receiver alive");
- });
- }
- .await;
- tokio::task::yield_now().await;
- assert!(
- rx.try_recv().is_ok(),
- "stamp-only spawn_fork must run immediately, not wait for a drain"
- );
-
- let body = boundary::RecordingBody::passthrough(actix_web::body::BoxBody::new("ok"));
- let bytes = actix_web::body::to_bytes(body).await.expect("body bytes");
- assert_eq!(&bytes[..], b"ok");
- }
-
- #[cfg(feature = "deja")]
- #[test]
- fn request_recording_facts_exposes_only_id_method_and_path_to_sampler() {
- let facts = RequestRecordingFacts {
- request_id: "req-123".to_string(),
- method: "POST".to_string(),
- path: "/payments/confirm".to_string(),
- };
-
- let RequestRecordingFacts {
- request_id,
- method,
- path,
- } = facts;
-
- assert_eq!(request_id, "req-123");
- assert_eq!(method, "POST");
- assert_eq!(path, "/payments/confirm");
- }
-
- #[cfg(feature = "deja")]
- #[test]
- fn recording_sampler_trait_object_can_be_attached_without_losing_configuration() {
- let sampler: Arc<dyn RequestRecordingSampler> = Arc::new(RejectAllSampler);
-
- let identifier = RequestIdentifier::new("x-correlation-id")
- .use_incoming_id(IdReuse::IgnoreIncoming)
- .with_recording_sampler(sampler);
-
- assert!(identifier.recording_sampler.is_some());
-
- assert_eq!(identifier.header_name(), "x-correlation-id");
- assert_eq!(identifier.id_reuse_strategy(), IdReuse::IgnoreIncoming);
- }
-}
+mod tests;
diff --git a/crates/router_env/src/request_id/tests.rs b/crates/router_env/src/request_id/tests.rs
new file mode 100644
index 0000000000..8d383627c5
--- /dev/null
+++ b/crates/router_env/src/request_id/tests.rs
@@ -0,0 +1,282 @@
+use super::*;
+
+/// Regression sentinel for the ingress circular-dependency bug.
+///
+/// The opt-in recording flip made `RecordingHook::mode()` return `Record`
+/// only while a per-correlation decision is pushed. The ingress middleware
+/// is what pushes that decision, so gating ingress on `mode()` was circular:
+/// `mode()` is `Disabled` at ingress (no decision yet) → the predicate is
+/// false → the sampler never runs → no decision is ever pushed → nothing is
+/// ever recorded (the empty-tape bug).
+///
+/// The fix routes the ingress predicates through `process_mode()`, which
+/// reflects the boot-time configuration and ignores the per-request gate.
+/// This test pins the exact pivot at the type level, with no global install
+/// and no async: a fresh recorder with no decision in scope must report
+/// `process_mode() == Record` (ingress may proceed) while `mode() ==
+/// Disabled` (the boundary gate still governs actual capture). On the old
+/// code the first assertion is what the middleware needed and never got.
+#[cfg(feature = "deja")]
+#[test]
+fn ingress_process_mode_is_record_before_any_decision_is_pushed() {
+ struct NullSink;
+ impl deja::RecordSink<deja::DejaRecord> for NullSink {
+ fn write_batch(&mut self, _records: &[deja::DejaRecord]) -> std::io::Result<()> {
+ Ok(())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ let hook = deja::RecordingHook::with_sink(
+ NullSink,
+ "ingress-sentinel".to_string(),
+ deja::WriterConfig::default(),
+ );
+
+ // No per-correlation decision has been pushed for this thread.
+ assert_eq!(
+ deja::DejaHook::process_mode(&hook),
+ deja::RuntimeMode::Record,
+ "ingress predicate must see Record from process config alone, or the \
+ middleware can never push the decision that flips the boundary gate"
+ );
+ assert_eq!(
+ deja::DejaHook::capture_verdict(&hook),
+ deja::CaptureVerdict::SkipNoDecision,
+ "the per-boundary capture gate must stay closed until a decision is \
+ pushed — the split is what breaks the ingress circular dependency"
+ );
+}
+
+#[test]
+fn request_identifier_builder_keeps_explicit_header_and_id_reuse_without_sampler() {
+ let identifier =
+ RequestIdentifier::new("x-correlation-id").use_incoming_id(IdReuse::IgnoreIncoming);
+
+ assert_eq!(identifier.header_name(), "x-correlation-id");
+ assert_eq!(identifier.id_reuse_strategy(), IdReuse::IgnoreIncoming);
+}
+
+#[cfg(feature = "deja")]
+struct RejectAllSampler;
+
+#[cfg(feature = "deja")]
+impl RequestRecordingSampler for RejectAllSampler {
+ fn should_record(&self, _facts: RequestRecordingFacts) -> RequestRecordingSamplerFuture<'_> {
+ Box::pin(ready(false))
+ }
+}
+
+#[cfg(feature = "deja")]
+struct EmptyLookup;
+
+#[cfg(feature = "deja")]
+impl deja::LookupTableSource for EmptyLookup {
+ fn load(&mut self) -> std::io::Result<deja::LookupTable> {
+ Ok(deja::LookupTable {
+ recording_id: "empty".to_string(),
+ policy_version: 1,
+ event_schema_version: Some(deja::CURRENT_EVENT_SCHEMA_VERSION),
+ entries: Vec::new(),
+ identity_entries: Vec::new(),
+ })
+ }
+}
+
+#[cfg(feature = "deja")]
+struct ObservedRecordingHook {
+ recorded: std::sync::Mutex<Vec<deja::BoundaryEvent>>,
+}
+
+#[cfg(feature = "deja")]
+impl ObservedRecordingHook {
+ fn new() -> Self {
+ Self {
+ recorded: std::sync::Mutex::new(Vec::new()),
+ }
+ }
+
+ fn recorded_len(&self) -> usize {
+ self.recorded.lock().expect("recording hook lock").len()
+ }
+
+ fn recorded_events(&self) -> Vec<deja::BoundaryEvent> {
+ self.recorded.lock().expect("recording hook lock").clone()
+ }
+}
+
+#[cfg(feature = "deja")]
+impl deja::DejaHook for ObservedRecordingHook {
+ fn process_mode(&self) -> deja::RuntimeMode {
+ deja::RuntimeMode::Record
+ }
+
+ fn record(&self, event: deja::BoundaryEvent) {
+ self.recorded
+ .lock()
+ .expect("recording hook lock")
+ .push(event);
+ }
+
+ fn next_global_sequence(&self) -> u64 {
+ 150
+ }
+
+ fn next_request_sequence(&self, _correlation_id: Option<&str>) -> u64 {
+ 1
+ }
+}
+
+#[cfg(feature = "deja")]
+struct ExactSizedNeverEofBody {
+ chunk: Option<bytes::Bytes>,
+ size: u64,
+}
+
+#[cfg(feature = "deja")]
+impl ExactSizedNeverEofBody {
+ fn new(chunk: &'static [u8]) -> Self {
+ Self {
+ chunk: Some(bytes::Bytes::from_static(chunk)),
+ size: u64::try_from(chunk.len()).unwrap_or(u64::MAX),
+ }
+ }
+}
+
+#[cfg(feature = "deja")]
+impl actix_web::body::MessageBody for ExactSizedNeverEofBody {
+ type Error = actix_web::Error;
+
+ fn size(&self) -> actix_web::body::BodySize {
+ actix_web::body::BodySize::Sized(self.size)
+ }
+
+ fn poll_next(
+ mut self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ ) -> Poll<Option<Result<bytes::Bytes, Self::Error>>> {
+ match self.chunk.take() {
+ Some(chunk) => Poll::Ready(Some(Ok(chunk))),
+ None => Poll::Pending,
+ }
+ }
+}
+
+#[cfg(feature = "deja")]
+#[test]
+fn recording_body_finalizes_exact_sized_body_after_matching_chunk_without_eof() {
+ let hook = Arc::new(ObservedRecordingHook::new());
+ let hook_dyn: Arc<dyn deja::DejaHook> = hook.clone();
+ let event = deja::EventBuilder::start_with_correlation_id(
+ hook_dyn.as_ref(),
+ "http_incoming",
+ "RequestIdMiddleware",
+ "call",
+ std::panic::Location::caller(),
+ Some("97cd".to_string()),
+ serde_json::json!({ "path": "/payments/confirm" }),
+ );
+ let finalizer =
+ deja::LazyEventFinalizer::new(event, hook_dyn, serde_json::json!({ "status": 200 }), false);
+ let mut body = boundary::RecordingBody::for_test_with_finalizer(
+ ExactSizedNeverEofBody::new(b"{\"ok\":true}"),
+ finalizer,
+ );
+ let waker = std::task::Waker::noop();
+ let mut context = Context::from_waker(waker);
+
+ let first_poll = actix_web::body::MessageBody::poll_next(Pin::new(&mut body), &mut context);
+
+ let Poll::Ready(Some(Ok(chunk))) = first_poll else {
+ panic!("first poll must yield the exact-sized body chunk before the body parks");
+ };
+ assert_eq!(&chunk[..], br#"{"ok":true}"#);
+ assert_eq!(
+ hook.recorded_len(),
+ 1,
+ "exact-sized bodies must finalize as soon as the declared bytes are captured, without waiting for EOF or drop"
+ );
+
+ let events = hook.recorded_events();
+ let event = events.first().expect("finalized http_incoming event");
+ assert_eq!(event.global_sequence, 150);
+ assert_eq!(event.correlation_id.as_deref(), Some("97cd"));
+ assert_eq!(event.boundary, "http_incoming");
+ assert_eq!(
+ event
+ .result
+ .get("response_body")
+ .and_then(|body| body.get("text"))
+ .and_then(serde_json::Value::as_str),
+ Some(r#"{"ok":true}"#)
+ );
+}
+
+#[cfg(feature = "deja")]
+#[tokio::test]
+async fn spawn_fork_runs_without_waiting_for_body_eof() {
+ // Stamp-only model: fork work is spawned immediately with span-derived
+ // lineage stamps — nothing queues, nothing drains at body EOF, and the
+ // recorder never reshapes scheduling.
+ let hook = deja::LookupTableHook::from_source(EmptyLookup, deja::InMemoryObservedSink::new())
+ .expect("lookup replay hook");
+ match deja::set_global_runtime_hook(Some(deja::RuntimeHook::LookupReplay(hook))) {
+ Ok(()) => {}
+ Err(_) if deja::runtime_mode().is_replay() => {}
+ Err(err) => panic!("install replay hook: {err}"),
+ }
+
+ let (tx, rx) = std::sync::mpsc::channel();
+ async move {
+ deja::spawn_fork(async move {
+ tx.send(()).expect("test receiver alive");
+ });
+ }
+ .await;
+ tokio::task::yield_now().await;
+ assert!(
+ rx.try_recv().is_ok(),
+ "stamp-only spawn_fork must run immediately, not wait for a drain"
+ );
+
+ let body = boundary::RecordingBody::passthrough(actix_web::body::BoxBody::new("ok"));
+ let bytes = actix_web::body::to_bytes(body).await.expect("body bytes");
+ assert_eq!(&bytes[..], b"ok");
+}
+
+#[cfg(feature = "deja")]
+#[test]
+fn request_recording_facts_exposes_only_id_method_and_path_to_sampler() {
+ let facts = RequestRecordingFacts {
+ request_id: "req-123".to_string(),
+ method: "POST".to_string(),
+ path: "/payments/confirm".to_string(),
+ };
+
+ let RequestRecordingFacts {
+ request_id,
+ method,
+ path,
+ } = facts;
+
+ assert_eq!(request_id, "req-123");
+ assert_eq!(method, "POST");
+ assert_eq!(path, "/payments/confirm");
+}
+
+#[cfg(feature = "deja")]
+#[test]
+fn recording_sampler_trait_object_can_be_attached_without_losing_configuration() {
+ let sampler: Arc<dyn RequestRecordingSampler> = Arc::new(RejectAllSampler);
+
+ let identifier = RequestIdentifier::new("x-correlation-id")
+ .use_incoming_id(IdReuse::IgnoreIncoming)
+ .with_recording_sampler(sampler);
+
+ assert!(identifier.recording_sampler.is_some());
+
+ assert_eq!(identifier.header_name(), "x-correlation-id");
+ assert_eq!(identifier.id_reuse_strategy(), IdReuse::IgnoreIncoming);
+}
diff --git a/crates/router_env/src/request_path.rs b/crates/router_env/src/request_path.rs
new file mode 100644
index 0000000000..0950da8eef
--- /dev/null
+++ b/crates/router_env/src/request_path.rs
@@ -0,0 +1,30 @@
+//! Request paths for telemetry. Keep resource IDs while hiding callback tokens.
+
+use std::borrow::Cow;
+
+use actix_web::HttpRequest;
+
+/// Use the concrete path except for a matched callback token. An unmatched path
+/// has no trustworthy token position, so its path is omitted from telemetry.
+pub fn path_for_telemetry(request: &HttpRequest) -> Cow<'_, str> {
+ match request.match_pattern() {
+ Some(pattern) if pattern.contains("{callback_token}") => {
+ let pattern_segments = pattern.split('/').collect::<Vec<_>>();
+ let mut path_segments = request.path().split('/').collect::<Vec<_>>();
+ if pattern_segments.len() != path_segments.len() {
+ return Cow::Owned(pattern);
+ }
+ for (segment, pattern_segment) in path_segments.iter_mut().zip(pattern_segments) {
+ if pattern_segment.contains("{callback_token}") {
+ *segment = pattern_segment;
+ }
+ }
+ Cow::Owned(path_segments.join("/"))
+ }
+ Some(_) => Cow::Borrowed(request.path()),
+ None => Cow::Borrowed("/unmatched"),
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/router_env/src/request_path/tests.rs b/crates/router_env/src/request_path/tests.rs
new file mode 100644
index 0000000000..18bd951c3d
--- /dev/null
+++ b/crates/router_env/src/request_path/tests.rs
@@ -0,0 +1,97 @@
+use actix_web::{test, web, App, HttpResponse};
+
+use super::*;
+
+async fn return_telemetry_path(request: HttpRequest) -> HttpResponse {
+ HttpResponse::Ok().body(path_for_telemetry(&request).into_owned())
+}
+
+#[actix_web::test]
+async fn callback_routes_hide_only_the_token() {
+ const TOKEN: &str = "d9dc53cc-d1a1-4f57-9077-d20c2d614daa";
+ let cases = [
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/token/{callback_token}/start/{attempt_id}",
+ "/payments/pay_123/merchant_456/redirect/token/{callback_token}/start/attempt_789",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/token/{callback_token}/response/{connector}",
+ "/payments/pay_123/merchant_456/redirect/token/{callback_token}/response/stripe",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/token/{callback_token}/response/{connector}/{creds_identifier}",
+ "/payments/pay_123/merchant_456/redirect/token/{callback_token}/response/stripe/creds_012",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/token/{callback_token}/complete/{connector}",
+ "/payments/pay_123/merchant_456/redirect/token/{callback_token}/complete/stripe",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/token/{callback_token}/complete/{connector}/{creds_identifier}",
+ "/payments/pay_123/merchant_456/redirect/token/{callback_token}/complete/stripe/creds_012",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/token/{callback_token}/authorize/{connector}",
+ "/payments/pay_123/merchant_456/redirect/token/{callback_token}/authorize/stripe",
+ ),
+ (
+ "/payments/redirect/{payment_id}/{merchant_id}/{attempt_id}/callback/{callback_token}",
+ "/payments/redirect/pay_123/merchant_456/attempt_789/callback/{callback_token}",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/response/{connector}/callback/{callback_token}",
+ "/payments/pay_123/merchant_456/redirect/response/stripe/callback/{callback_token}",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/response/{connector}/{creds_identifier}/callback/{callback_token}",
+ "/payments/pay_123/merchant_456/redirect/response/stripe/creds_012/callback/{callback_token}",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/complete/{connector}/callback/{callback_token}",
+ "/payments/pay_123/merchant_456/redirect/complete/stripe/callback/{callback_token}",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/redirect/complete/{connector}/{creds_identifier}/callback/{callback_token}",
+ "/payments/pay_123/merchant_456/redirect/complete/stripe/creds_012/callback/{callback_token}",
+ ),
+ (
+ "/payments/{payment_id}/{merchant_id}/authorize/{connector}/callback/{callback_token}",
+ "/payments/pay_123/merchant_456/authorize/stripe/callback/{callback_token}",
+ ),
+ ];
+ let app = test::init_service(App::new().configure(|config| {
+ for (pattern, _) in cases {
+ config.service(web::resource(pattern).route(web::get().to(return_telemetry_path)));
+ }
+ }))
+ .await;
+
+ for (_, expected) in cases {
+ let request = test::TestRequest::get()
+ .uri(&expected.replace("{callback_token}", TOKEN))
+ .to_request();
+ let response = test::call_service(&app, request).await;
+ assert!(response.status().is_success(), "{expected}");
+ let body = test::read_body(response).await;
+ assert_eq!(
+ std::str::from_utf8(&body).expect("telemetry path"),
+ expected
+ );
+ }
+}
+
+#[actix_web::test]
+async fn callback_paths_with_variable_segments_use_the_route_pattern() {
+ let pattern = "/payments/{prefix:.*}/redirect/token/{callback_token}/response/{connector}";
+ let app = test::init_service(
+ App::new().service(web::resource(pattern).route(web::get().to(return_telemetry_path))),
+ )
+ .await;
+ let request = test::TestRequest::get()
+ .uri("/payments/pay_123/merchant_456/redirect/token/d9dc53cc-d1a1-4f57-9077-d20c2d614daa/response/stripe")
+ .to_request();
+ let response = test::call_service(&app, request).await;
+ assert!(response.status().is_success());
+ let body = test::read_body(response).await;
+ assert_eq!(std::str::from_utf8(&body).expect("telemetry path"), pattern);
+}
diff --git a/crates/router_env/src/root_span.rs b/crates/router_env/src/root_span.rs
index 62ab4fa9b4..e6f76b3f5c 100644
--- a/crates/router_env/src/root_span.rs
+++ b/crates/router_env/src/root_span.rs
@@ -15,6 +15,27 @@ use crate::request_id::RequestId;
#[derive(Debug)]
pub struct CustomRootSpanBuilder;
+// Override only the URI observed by the tracing macro. The actual request,
+// including its body, headers, and routing data, remains untouched.
+struct RouteTargetRequest<'a> {
+ request: &'a ServiceRequest,
+ uri: actix_web::http::Uri,
+}
+
+impl std::ops::Deref for RouteTargetRequest<'_> {
+ type Target = ServiceRequest;
+
+ fn deref(&self) -> &Self::Target {
+ self.request
+ }
+}
+
+impl RouteTargetRequest<'_> {
+ fn uri(&self) -> &actix_web::http::Uri {
+ &self.uri
+ }
+}
+
impl RootSpanBuilder for CustomRootSpanBuilder {
fn on_request_start(request: &ServiceRequest) -> Span {
// Extract the RequestId from extensions (set by RequestIdentifier middleware)
@@ -25,6 +46,22 @@ impl RootSpanBuilder for CustomRootSpanBuilder {
.map(|id| id.to_string())
.unwrap_or_default();
+ // root_span! records http.target as soon as the span is created.
+ let target = crate::request_path::path_for_telemetry(request.request());
+ if target.as_ref() == request.path() {
+ return root_span!(
+ level = crate::Level::INFO,
+ request,
+ request_id = request_id.as_str()
+ );
+ }
+ let route_request = RouteTargetRequest {
+ request,
+ uri: target
+ .parse()
+ .unwrap_or_else(|_| actix_web::http::Uri::from_static("/unmatched")),
+ };
+ let request = &route_request;
root_span!(
level = crate::Level::INFO,
request,
@@ -68,3 +105,6 @@ fn handle_error(span: Span, status_code: StatusCode, response_error: &dyn Respon
span.record("otel.status_code", "ERROR");
}
}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/router_env/src/root_span/tests.rs b/crates/router_env/src/root_span/tests.rs
new file mode 100644
index 0000000000..0e813d46fe
--- /dev/null
+++ b/crates/router_env/src/root_span/tests.rs
@@ -0,0 +1,86 @@
+use std::sync::{Arc, Mutex};
+
+use tracing::field::{Field, Visit};
+use tracing_subscriber::{layer::Context, prelude::*, Layer, Registry};
+
+use super::*;
+
+#[derive(Clone)]
+struct CaptureTarget(Arc<Mutex<Vec<String>>>);
+
+impl Visit for CaptureTarget {
+ fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
+ if field.name() == "http.target" {
+ self.0.lock().expect("targets").push(format!("{value:?}"));
+ }
+ }
+}
+
+impl Layer<Registry> for CaptureTarget {
+ fn on_new_span(
+ &self,
+ attributes: &tracing::span::Attributes<'_>,
+ _: &tracing::Id,
+ _: Context<'_, Registry>,
+ ) {
+ attributes.record(&mut self.clone());
+ }
+}
+
+#[test]
+fn unmatched_callback_target_is_generic_before_subscribers_observe_the_span() {
+ let capture = CaptureTarget(Arc::new(Mutex::new(Vec::new())));
+ let subscriber = Registry::default().with(capture.clone());
+ tracing::subscriber::with_default(subscriber, || {
+ let request = actix_web::test::TestRequest::get()
+ .uri("/payments/pay/merchant/redirect/token/d9dc53cc-d1a1-4f57-9077-d20c2d614daa/complete/paybox/extra?connector_param=value")
+ .to_srv_request();
+ request
+ .extensions_mut()
+ .insert(tracing_actix_web::root_span_macro::private::generate_request_id());
+ let _span = CustomRootSpanBuilder::on_request_start(&request);
+ assert!(request
+ .path()
+ .contains("d9dc53cc-d1a1-4f57-9077-d20c2d614daa"));
+ assert_eq!(request.query_string(), "connector_param=value");
+ });
+ let targets = capture.0.lock().expect("targets");
+ assert_eq!(targets.len(), 1);
+ let target = targets.first().expect("root span target");
+ assert!(!target.contains("d9dc53cc"));
+ assert!(target.contains("/unmatched"));
+ assert!(!target.contains("connector_param"));
+}
+
+#[actix_web::test]
+async fn matched_callback_target_keeps_ids_and_masks_only_the_token() {
+ use actix_web::{test, web, App, HttpResponse};
+
+ let capture = CaptureTarget(Arc::new(Mutex::new(Vec::new())));
+ let subscriber = Registry::default().with(capture.clone());
+ let _guard = tracing::subscriber::set_default(subscriber);
+ let app = test::init_service(
+ App::new()
+ .wrap(tracing_actix_web::TracingLogger::<CustomRootSpanBuilder>::new())
+ .service(web::scope("/payments").service(
+ web::resource("/{payment_id}/{merchant_id}/redirect/token/{callback_token}/complete/{connector}")
+ .route(web::get().to(|| async { HttpResponse::Ok().finish() })),
+ )),
+ )
+ .await;
+
+ let request = test::TestRequest::get()
+ .uri("/payments/pay/merchant/redirect/token/d9dc53cc-d1a1-4f57-9077-d20c2d614daa/complete/paybox?connector_param=value")
+ .to_request();
+ let response = test::call_service(&app, request).await;
+ assert!(response.status().is_success());
+
+ let targets = capture.0.lock().expect("targets");
+ assert_eq!(targets.len(), 1);
+ let target = targets.first().expect("root span target");
+ assert!(!target.contains("d9dc53cc"));
+ assert!(
+ target.contains("/payments/pay/merchant/redirect/token/{callback_token}/complete/paybox")
+ );
+ assert!(!target.contains("connector_param"));
+}
diff --git a/cypress-tests/cypress/e2e/configs/Payment/Commons.js b/cypress-tests/cypress/e2e/configs/Payment/Commons.js
index fcd2265635..6512a5d0d0 100644
--- a/cypress-tests/cypress/e2e/configs/Payment/Commons.js
+++ b/cypress-tests/cypress/e2e/configs/Payment/Commons.js
@@ -3798,21 +3798,9 @@ export const connectorDetails = {
},
},
DDCConfig: {
- completeUrlPath: "/redirect/complete/default",
collectionReferenceParam: "collectionReference",
firstSubmissionValue: "",
secondSubmissionValue: "race_condition_test_ddc_123",
- expectedError: {
- status: 400,
- body: {
- error: {
- code: "IR_07",
- type: "invalid_request",
- message:
- "Invalid value provided: collection_reference not allowed in AuthenticationPending state",
- },
- },
- },
},
}),
DDCRaceConditionClientSide: getCustomExchange({
@@ -3833,7 +3821,6 @@ export const connectorDetails = {
},
},
DDCConfig: {
- redirectUrlPath: "/payments/redirect",
collectionReferenceParam: "collectionReference",
delayBeforeSubmission: 2000,
raceConditionScript: `
diff --git a/cypress-tests/cypress/e2e/configs/Payment/WorldPay.js b/cypress-tests/cypress/e2e/configs/Payment/WorldPay.js
index 89b6605f58..c110178f87 100644
--- a/cypress-tests/cypress/e2e/configs/Payment/WorldPay.js
+++ b/cypress-tests/cypress/e2e/configs/Payment/WorldPay.js
@@ -799,21 +799,9 @@ export const connectorDetails = {
},
}),
DDCConfig: {
- completeUrlPath: "/redirect/complete/worldpay",
collectionReferenceParam: "collectionReference",
firstSubmissionValue: "",
secondSubmissionValue: "race_condition_test_ddc_123",
- expectedError: {
- status: 400,
- body: {
- error: {
- code: "IR_07",
- type: "invalid_request",
- message:
- "Invalid value provided: collection_reference not allowed in AuthenticationPending state",
- },
- },
- },
},
},
DDCRaceConditionClientSide: {
@@ -837,7 +825,6 @@ export const connectorDetails = {
},
}),
DDCConfig: {
- redirectUrlPath: "/payments/redirect",
collectionReferenceParam: "collectionReference",
delayBeforeSubmission: 2000,
raceConditionScript: `
diff --git a/cypress-tests/cypress/e2e/spec/Payment/52-PaymentResponseHash.cy.js b/cypress-tests/cypress/e2e/spec/Payment/52-PaymentResponseHash.cy.js
index edad3b2146..05122fe47a 100644
--- a/cypress-tests/cypress/e2e/spec/Payment/52-PaymentResponseHash.cy.js
+++ b/cypress-tests/cypress/e2e/spec/Payment/52-PaymentResponseHash.cy.js
@@ -119,11 +119,8 @@ describe("Card - Payment Response Hash flow test", () => {
context("3DS Auto-Capture - Verify Redirect Signature", () => {
it("setup 3DS -> verify redirect signature", () => {
- // Setup 3DS payment flow without redirection to test signature verification
- // globalState: shared state object for test data persistence
- // includeRedirection: false - skips the actual browser redirection to focus on signature validation
- // fixtures: test data fixtures for payment setup
- setup3DSPayment(globalState, { includeRedirection: false, fixtures });
+ // Complete 3DS and capture the signed merchant redirect.
+ setup3DSPayment(globalState, { fixtures });
cy.step("verify redirect signature", () => {
// Assert that redirect URL was captured before attempting signature verification
@@ -140,11 +137,8 @@ describe("Card - Payment Response Hash flow test", () => {
context("3DS Auto-Capture - Compute and Verify Redirect Signature", () => {
it("setup 3DS -> compute HMAC and compare with redirect signature", () => {
- // Setup 3DS payment flow to test HMAC computation and signature comparison
- // globalState: shared state object for test data persistence
- // includeRedirection: false - skips browser redirection to focus on HMAC computation logic
- // fixtures: test data fixtures for payment setup
- setup3DSPayment(globalState, { includeRedirection: false, fixtures });
+ // Complete 3DS before comparing the merchant redirect signature.
+ setup3DSPayment(globalState, { fixtures });
cy.step("compute and verify redirect signature", () => {
if (!globalState.get("_setup3DSContinue")) {
@@ -162,11 +156,8 @@ describe("Card - Payment Response Hash flow test", () => {
context("3DS Auto-Capture - Failure Scenarios for Invalid Signatures", () => {
it("setup 3DS -> compute HMAC -> verify tampered and wrong-key signatures fail", () => {
- // Setup 3DS payment flow for testing tampered and wrong-key signature scenarios
- // globalState: shared state object for test data persistence
- // includeRedirection: false - skips browser redirection to test signature validation failures
- // fixtures: test data fixtures for payment setup
- setup3DSPayment(globalState, { includeRedirection: false, fixtures });
+ // Capture a real merchant redirect for signature failure checks.
+ setup3DSPayment(globalState, { fixtures });
cy.step("compute and verify redirect signature", () => {
if (!globalState.get("_setup3DSContinue")) {
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index 42c8e11de5..6fad0b905b 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -9607,46 +9607,66 @@ Cypress.Commands.add(
"ddcServerSideRaceConditionTest",
(confirmData, globalState) => {
const ddcConfig = confirmData.DDCConfig;
- const paymentId = globalState.get("paymentID");
- const merchantId = globalState.get("merchantId");
- const completeUrl = `${Cypress.env("BASEURL")}/payments/${paymentId}/${merchantId}${ddcConfig.completeUrlPath}`;
+ const nextActionUrl = globalState.get("nextActionUrl");
+ expect(nextActionUrl, "router-issued DDC page URL").to.be.a("string").and
+ .not.be.empty;
cy.request({
- method: "GET",
- url: completeUrl,
- qs: {
- [ddcConfig.collectionReferenceParam]: ddcConfig.firstSubmissionValue,
- },
- failOnStatusCode: false,
- }).then((firstResponse) => {
- if (
- firstResponse.status === 400 &&
- firstResponse.body?.error?.message?.includes("No eligible connector")
- ) {
- throw new Error(
- `Connector configuration issue detected. Response: ${JSON.stringify(firstResponse.body)}`
- );
- }
-
- expect(firstResponse.status).to.be.oneOf([200, 302]);
- cy.log(`First request status: ${firstResponse.status}`);
+ url: nextActionUrl,
+ followRedirect: false,
+ retryOnNetworkFailure: false,
+ log: false,
+ }).then((page) => {
+ const document = new DOMParser().parseFromString(page.body, "text/html");
+ const completeUrl = document.body.getAttribute("data-callback-url");
+ expect(completeUrl, "router-issued DDC callback URL").to.be.a("string")
+ .and.not.be.empty;
cy.request({
method: "GET",
url: completeUrl,
qs: {
- [ddcConfig.collectionReferenceParam]: ddcConfig.secondSubmissionValue,
+ [ddcConfig.collectionReferenceParam]: ddcConfig.firstSubmissionValue,
},
failOnStatusCode: false,
- }).then((secondResponse) => {
- cy.log(`Second request status: ${secondResponse.status}`);
+ followRedirect: false,
+ retryOnNetworkFailure: false,
+ log: false,
+ }).then((firstResponse) => {
+ if (
+ firstResponse.status === 400 &&
+ firstResponse.body?.error?.message?.includes("No eligible connector")
+ ) {
+ throw new Error(
+ `Connector configuration issue detected. Response: ${JSON.stringify(firstResponse.body)}`
+ );
+ }
- expect(secondResponse.status).to.eq(ddcConfig.expectedError.status);
- expect(secondResponse.body).to.deep.equal(ddcConfig.expectedError.body);
+ expect(firstResponse.status).to.be.oneOf([200, 302]);
+ cy.log(`First request status: ${firstResponse.status}`);
- cy.log(
- "✅ Server-side race condition protection verified - second submission properly rejected"
- );
+ cy.request({
+ method: "GET",
+ url: completeUrl,
+ qs: {
+ [ddcConfig.collectionReferenceParam]:
+ ddcConfig.secondSubmissionValue,
+ },
+ failOnStatusCode: false,
+ followRedirect: false,
+ retryOnNetworkFailure: false,
+ log: false,
+ }).then((secondResponse) => {
+ cy.log(`Second request status: ${secondResponse.status}`);
+
+ expect(secondResponse.status, "DDC token cannot be reused").to.eq(
+ 401
+ );
+
+ cy.log(
+ "✅ Server-side race condition protection verified - second submission properly rejected"
+ );
+ });
});
});
}
@@ -9656,9 +9676,9 @@ Cypress.Commands.add(
"ddcClientSideRaceConditionTest",
(confirmData, globalState) => {
const ddcConfig = confirmData.DDCConfig;
- const paymentId = globalState.get("paymentID");
- const merchantId = globalState.get("merchantId");
- const nextActionUrl = `${Cypress.env("BASEURL")}${ddcConfig.redirectUrlPath}/${paymentId}/${merchantId}/${paymentId}_1`;
+ const nextActionUrl = globalState.get("nextActionUrl");
+ expect(nextActionUrl, "router-issued DDC page URL").to.be.a("string").and
+ .not.be.empty;
cy.intercept("GET", nextActionUrl, (req) => {
req.reply((res) => {
@@ -9671,7 +9691,9 @@ Cypress.Commands.add(
});
}).as("ddcPageWithRaceCondition");
- cy.intercept("GET", "**/redirect/complete/**").as("ddcSubmission");
+ cy.intercept("GET", /\/redirect\/(?:token\/[^/]+\/)?complete\//).as(
+ "ddcSubmission"
+ );
const delayBeforeSubmission = ddcConfig.delayBeforeSubmission || 2000;
cy.visit(nextActionUrl);
@@ -12752,57 +12774,24 @@ Cypress.Commands.add("verifyWrongKeySignatureFails", (globalState) => {
});
Cypress.Commands.add("captureRedirectReturnUrl", (globalState) => {
- const baseUrl = globalState.get("baseUrl");
+ globalState.set("redirectReturnUrl", null);
const paymentId = globalState.get("paymentID");
- const merchantId = globalState.get("merchantId");
- const connectorId = getOriginalConnectorName(globalState.get("connectorId"));
- const url = `${baseUrl}/payments/${paymentId}/${merchantId}/redirect/response/${connectorId}`;
-
- /**
- * Attempt to capture the redirect return URL with polling retry.
- * The payment may not immediately be in redirect-ready state,
- * so we retry up to MAX_RETRIES with DELAY_MS between attempts.
- */
- const MAX_RETRIES = 5;
- const DELAY_MS = 2000;
-
- function attemptCapture(remainingAttempts) {
- return cy
- .request({
- method: "GET",
- url,
- followRedirect: false,
- failOnStatusCode: false,
- })
- .then((response) => {
- if (response.status === 302 && response.headers.location) {
- globalState.set("redirectReturnUrl", response.headers.location);
- cy.task(
- "cli_log",
- "captureRedirectReturnUrl: captured redirect return URL with signature"
- );
- return;
- }
-
- if (remainingAttempts > 1) {
- cy.task(
- "cli_log",
- `captureRedirectReturnUrl: got status ${response.status}, retrying in ${DELAY_MS}ms (${MAX_RETRIES - remainingAttempts + 1}/${MAX_RETRIES})`
- );
- return cy
- .wait(DELAY_MS)
- .then(() => attemptCapture(remainingAttempts - 1));
+ cy.intercept(
+ /\/redirect\/(?:token\/[^/]+\/)?(?:response|complete)\//,
+ (req) => {
+ if (!new URL(req.url).pathname.startsWith(`/payments/${paymentId}/`))
+ return;
+ req.on("response", (response) => {
+ const location = response.headers.location;
+ if (
+ typeof location === "string" &&
+ new URL(location, req.url).searchParams.has("signature")
+ ) {
+ globalState.set("redirectReturnUrl", new URL(location, req.url).href);
}
-
- // Final attempt failed — throw so the test fails loudly
- throw new Error(
- `captureRedirectReturnUrl: expected 302 with Location header, got ${response.status}. ` +
- `Headers: ${JSON.stringify(response.headers)}`
- );
});
- }
-
- attemptCapture(MAX_RETRIES);
+ }
+ );
});
// ============================================
diff --git a/cypress-tests/cypress/support/mitmProxy.js b/cypress-tests/cypress/support/mitmProxy.js
index 448be3c94a..5bdac0d3b8 100644
--- a/cypress-tests/cypress/support/mitmProxy.js
+++ b/cypress-tests/cypress/support/mitmProxy.js
@@ -16,14 +16,14 @@
const JS_IFRAME_CONNECTORS = {
stripe: {
- path: "redirect/response",
+ path: "redirect/response/stripe",
params: (gs) => ({
payment_intent: gs.get("connectorTransactionID"),
redirect_status: "succeeded",
}),
},
stripeconnect: {
- path: "redirect/response",
+ path: "redirect/response/stripe",
params: (gs) => ({
payment_intent: gs.get("connectorTransactionID"),
redirect_status: "succeeded",
@@ -135,134 +135,147 @@ export function mockRecordBankRedirect(
// ── Replay helpers ───────────────────────────────────────────────────────────
-function replayRedirectBody(saved, paymentId, merchantId, notificationUrl) {
- const hyperswitchUrl =
- Cypress.env("HYPERSWITCH_URL") || "http://localhost:8080";
- if (saved && saved.__redirect_method === "GET") {
- const qs = new URLSearchParams(saved.__query || {}).toString();
- const base = saved.__redirect_segment
- ? `${hyperswitchUrl}/payments/${paymentId}/${merchantId}/${saved.__redirect_segment}`
- : notificationUrl;
- cy.request({
- method: "GET",
- url: qs ? `${base}?${qs}` : base,
- failOnStatusCode: false,
- followRedirect: false,
- });
- } else if (saved) {
- const postBody =
- saved.__redirect_method === "POST" && saved.__body ? saved.__body : saved;
- const postUrl = saved.__redirect_segment
- ? `${hyperswitchUrl}/payments/${paymentId}/${merchantId}/${saved.__redirect_segment}`
- : notificationUrl;
- cy.request({
- method: "POST",
- url: postUrl,
- form: true,
- body: postBody,
- failOnStatusCode: false,
- followRedirect: false,
- });
- } else {
- cy.then(() => {
- if (Cypress._buildRequestId) Cypress._buildRequestId();
- });
- }
+function callbackSegment(url) {
+ return new URL(url).pathname
+ .replace(/\/redirect\/token\/[^/]+\//, "/redirect/")
+ .split("/redirect/")[1]
+ ?.split("/callback/")[0];
}
-function replayJsConnectorRedirect(
- jsConnector,
- saved,
- paymentId,
- merchantId,
- globalState
-) {
- const hyperswitchUrl =
- Cypress.env("HYPERSWITCH_URL") || "http://localhost:8080";
- if (saved && saved.__redirect_method === "GET" && saved.__redirect_segment) {
- const url = `${hyperswitchUrl}/payments/${paymentId}/${merchantId}/${saved.__redirect_segment}`;
- const qs = new URLSearchParams(saved.__query || {}).toString();
- cy.request({
- method: "GET",
- url: qs ? `${url}?${qs}` : url,
- failOnStatusCode: false,
- followRedirect: false,
+function resolveCallbackUrl(globalState, saved, pageCallbacks = []) {
+ const segment = saved?.__redirect_segment
+ ?.replace(/^redirect\/(?:token\/[^/]+\/)?/, "")
+ .split("/callback/")[0];
+ const paymentId = globalState.get("paymentID");
+ const merchantId = globalState.get("merchantId");
+ const selectUrl = (urls) => {
+ const matches = [...new Set(urls)].filter((url) => {
+ const path = new URL(url).pathname;
+ return (
+ path.startsWith(
+ `/payments/${paymentId}/${merchantId}/redirect/token/`
+ ) &&
+ (!segment || callbackSegment(url) === segment)
+ );
});
- } else {
- const returnUrl = `${hyperswitchUrl}/payments/${paymentId}/${merchantId}/${jsConnector.path}/${globalState.get("connectorId")}`;
- const params = jsConnector.params(globalState);
- const hasValues = Object.values(params).every(
- (v) => v !== undefined && v !== null
- );
- if (hasValues) {
- const qs = new URLSearchParams(params).toString();
- cy.request({
- method: "GET",
- url: `${returnUrl}?${qs}`,
- failOnStatusCode: false,
- followRedirect: false,
- });
- } else {
- cy.then(() => {
- if (Cypress._buildRequestId) Cypress._buildRequestId();
- });
- }
+ expect(
+ matches,
+ "one fresh router-issued callback for this payment"
+ ).to.have.length(1);
+ return matches[0];
+ };
+
+ const matchingPageCallbacks = pageCallbacks.filter(
+ (url) => !segment || callbackSegment(url) === segment
+ );
+ if (matchingPageCallbacks.length) {
+ return cy.wrap(selectUrl(matchingPageCallbacks), { log: false });
}
+
+ const adminUrl = Cypress.env("PROXY_ADMIN_URL");
+ expect(adminUrl, "replay proxy admin URL").to.be.a("string").and.not.be.empty;
+ return cy
+ .request({
+ url: `${adminUrl}/callbacks`,
+ qs: { payment_id: paymentId, merchant_id: merchantId },
+ log: false,
+ })
+ .then((response) => selectUrl(response.body.urls));
}
function replayRedirect(
connectorId,
globalState,
redirectBodyFile,
- notificationUrl
+ pageCallbacks
) {
- const paymentId = globalState.get("paymentID");
- const merchantId = globalState.get("merchantId");
const jsConnector = JS_IFRAME_CONNECTORS[connectorId];
+ return cy.task("readFileOrNull", redirectBodyFile).then((saved) => {
+ if (!saved && !jsConnector) {
+ if (Cypress._buildRequestId) Cypress._buildRequestId();
+ return;
+ }
+ const params = jsConnector?.params(globalState);
+ if (!saved && params && Object.values(params).some((v) => v == null)) {
+ if (Cypress._buildRequestId) Cypress._buildRequestId();
+ return;
+ }
- if (jsConnector) {
- cy.task("readFileOrNull", redirectBodyFile).then((saved) => {
- replayJsConnectorRedirect(
- jsConnector,
- saved,
- paymentId,
- merchantId,
- globalState
- );
+ // Cassette metadata identifies the route and connector payload only. The
+ // token must come from this run's redirect page or outbound connector call.
+ const route = saved?.__redirect_segment
+ ? saved
+ : {
+ __redirect_segment:
+ jsConnector?.path || `redirect/complete/${connectorId}`,
+ };
+ return resolveCallbackUrl(globalState, route, pageCallbacks).then((url) => {
+ const method = saved?.__redirect_method || (jsConnector ? "GET" : "POST");
+ const callback = new URL(url);
+ if (method === "GET") {
+ const query = { ...(saved?.__query || {}), ...params };
+ Object.entries(query).forEach(([key, value]) => {
+ callback.searchParams.set(key, value);
+ });
+ }
+ return cy
+ .request({
+ method,
+ url: callback.toString(),
+ ...(method === "POST" && {
+ form: true,
+ body: saved?.__body || saved,
+ }),
+ followRedirect: false,
+ failOnStatusCode: false,
+ retryOnNetworkFailure: false,
+ log: false,
+ })
+ .then((response) => {
+ expect(
+ response.status,
+ "fresh callback must authenticate"
+ ).to.be.within(200, 399);
+ if (response.headers.location) {
+ globalState.set("redirectReturnUrl", response.headers.location);
+ }
+ });
});
- return;
- }
-
- cy.task("readFileOrNull", redirectBodyFile).then((saved) => {
- replayRedirectBody(saved, paymentId, merchantId, notificationUrl);
});
}
export function mockReplay3ds(globalState, connectorId, nextActionUrl) {
- const baseUrl = globalState.get("baseUrl");
- const paymentId = globalState.get("paymentID");
- const merchantId = globalState.get("merchantId");
const testIdHash = Cypress.env("currentTestIdHash") || "unknown";
const seq = nextRedirectSeq(testIdHash);
const redirectBodyFile = getRedirectBodyFile(connectorId, testIdHash, seq);
- const notificationUrl = `${baseUrl}/payments/${paymentId}/${merchantId}/redirect/complete/${connectorId}`;
- cy.request({
- url: nextActionUrl,
- failOnStatusCode: false,
- followRedirect: false,
- });
- replayRedirect(connectorId, globalState, redirectBodyFile, notificationUrl);
+ return cy
+ .request({
+ url: nextActionUrl,
+ failOnStatusCode: false,
+ followRedirect: false,
+ retryOnNetworkFailure: false,
+ log: false,
+ })
+ .then((page) => {
+ const document = new DOMParser().parseFromString(page.body, "text/html");
+ const callbacks = [
+ document.body.getAttribute("data-callback-url"),
+ document.body.getAttribute("data-complete-callback-url"),
+ ].filter(Boolean);
+ return replayRedirect(
+ connectorId,
+ globalState,
+ redirectBodyFile,
+ callbacks
+ );
+ });
}
export function mockReplayBankRedirect(globalState, connectorId) {
- const baseUrl = globalState.get("baseUrl");
- const paymentId = globalState.get("paymentID");
- const merchantId = globalState.get("merchantId");
const testIdHash = Cypress.env("currentTestIdHash") || "unknown";
const seq = nextRedirectSeq(testIdHash);
const redirectBodyFile = getRedirectBodyFile(connectorId, testIdHash, seq);
- const notificationUrl = `${baseUrl}/payments/${paymentId}/${merchantId}/redirect/complete/${connectorId}`;
- replayRedirect(connectorId, globalState, redirectBodyFile, notificationUrl);
+ return replayRedirect(connectorId, globalState, redirectBodyFile);
}
diff --git a/cypress-tests/cypress/support/redirectionHandler.js b/cypress-tests/cypress/support/redirectionHandler.js
index 837010f7ee..3c4d71b5dd 100644
--- a/cypress-tests/cypress/support/redirectionHandler.js
+++ b/cypress-tests/cypress/support/redirectionHandler.js
@@ -3329,36 +3329,11 @@ function threeDsRedirection(
connectorId,
paymentMethodType
) {
- let responseContentType = null;
-
- // First check what type of response we get from the redirect URL
- cy.request({
- url: redirectionUrl.href,
+ // Callback URLs are single-use: navigate directly without a probe or retries.
+ cy.visit(redirectionUrl.href, {
failOnStatusCode: false,
- }).then((response) => {
- responseContentType = response.headers["content-type"];
-
- // Check if the response is JSON
- if (response.headers["content-type"]?.includes("application/json")) {
- // For JSON responses, check if it contains useful info
- if (response.body && typeof response.body === "object") {
- // If the JSON contains redirect info, use it
- if (response.body.redirect_url) {
- cy.visit(response.body.redirect_url, { failOnStatusCode: false });
- } else {
- cy.visit(expectedUrl.href);
- // Verify return URL and exit completely
- verifyReturnUrl(redirectionUrl, expectedUrl, true);
- return;
- }
- } else {
- cy.visit(expectedUrl.href);
- verifyReturnUrl(redirectionUrl, expectedUrl, true);
- return;
- }
- } else {
- cy.visit(redirectionUrl.href, { failOnStatusCode: false });
- }
+ retryOnNetworkFailure: false,
+ retryOnStatusCodeFailure: false,
});
if (connectorId === "paysafe") {
@@ -3480,8 +3455,6 @@ function threeDsRedirection(
}
// Nuvei 3DS: 2-step flow (auth button + redirect button)
if (connectorId === "nuvei") {
- cy.visit(redirectionUrl.href, { failOnStatusCode: false });
-
cy.document()
.should("have.property", "readyState")
.and("equal", "complete");
@@ -3550,7 +3523,6 @@ function threeDsRedirection(
// Using cy.origin() here causes a cross-origin crash because the sandbox
// auto-redirect fires before the origin block can execute.
if (connectorId === "paypal") {
- cy.visit(redirectionUrl.href, { failOnStatusCode: false });
cy.url({ timeout: CONSTANTS.TIMEOUT }).should("include", expectedUrl.host);
verifyReturnUrl(redirectionUrl, expectedUrl, true);
return;
@@ -3562,7 +3534,6 @@ function threeDsRedirection(
// that's fixed on the router side, just visit the redirection URL and
// confirm it loads, without waiting for the auto-submit/host change.
if (connectorId === "paybox") {
- cy.visit(redirectionUrl.href, { failOnStatusCode: false });
cy.get("body", { timeout: CONSTANTS.TIMEOUT }).should("exist");
return;
}
@@ -3903,12 +3874,7 @@ function threeDsRedirection(
);
cy.then(() => {
- if (
- responseContentType &&
- !responseContentType.includes("application/json")
- ) {
- verifyReturnUrl(redirectionUrl, expectedUrl, true);
- }
+ verifyReturnUrl(redirectionUrl, expectedUrl, true);
});
}
diff --git a/cypress-tests/cypress/utils/paymentHelpers.js b/cypress-tests/cypress/utils/paymentHelpers.js
index 6e9ca58375..6737999454 100644
--- a/cypress-tests/cypress/utils/paymentHelpers.js
+++ b/cypress-tests/cypress/utils/paymentHelpers.js
@@ -4,12 +4,10 @@ import getConnectorDetails, * as utils from "../e2e/configs/Payment/Utils";
* Helper function to setup a 3DS payment flow
* @param {Object} globalState - globalState object for managing test state and persisting data across test steps
* @param {Object} options - Configuration options for customizing 3DS payment setup behavior
- * @param {boolean} options.includeRedirection - Controls whether to handle browser redirection after 3DS authentication (default: true). Set to false when testing signature/HMAC verification without full redirect flow.
* @param {Object} options.fixtures - Test fixtures object containing createPaymentBody and confirmBody for payment setup
*/
export function setup3DSPayment(globalState, options = {}) {
- // Destructure options with defaults: includeRedirection controls redirect handling, fixtures provides test data
- const { includeRedirection = true, fixtures } = options;
+ const { fixtures } = options;
let shouldContinue = true;
// Fetch PaymentIntent configuration for card payment method from the connector's config
@@ -50,12 +48,16 @@ export function setup3DSPayment(globalState, options = {}) {
}
if (shouldContinue) {
+ // Observe the real redirect; callback tokens cannot be polled or reused.
cy.captureRedirectReturnUrl(globalState);
- }
-
- if (includeRedirection && shouldContinue) {
const expected_redirection = fixtures.confirmBody["return_url"];
cy.handleRedirection(globalState, expected_redirection);
+ cy.then(() => {
+ expect(
+ globalState.get("redirectReturnUrl"),
+ "signed merchant return URL"
+ ).to.be.a("string").and.not.be.empty;
+ });
}
globalState.set("_setup3DSContinue", shouldContinue);
diff --git a/cypress-tests/mitm-proxy/callback_urls.py b/cypress-tests/mitm-proxy/callback_urls.py
new file mode 100644
index 0000000000..96bacaf321
--- /dev/null
+++ b/cypress-tests/mitm-proxy/callback_urls.py
@@ -0,0 +1,121 @@
+"""Keep callback URLs from the current replay run, never from a cassette."""
+
+import base64
+import html
+import json
+import re
+import threading
+from urllib.parse import parse_qsl, unquote, urlsplit
+from xml.etree import ElementTree
+
+
+_URL = re.compile(r"https?://[^\s\"'<>\\]+")
+_CALLBACK = re.compile(
+ r"/payments/([^/]+)/([^/]+)/redirect/token/"
+ r"[0-9a-fA-F-]{36}/(?:response|complete)/[^/]+(?:/[^/]+)?$"
+)
+_NOTIFICATION = re.compile(r"notify|notification|webhook|http_?direct", re.I)
+
+
+def _redsys_callback_urls(value):
+ try:
+ parameters = json.loads(base64.b64decode(value, validate=True))
+ except (ValueError, TypeError):
+ return
+ if isinstance(parameters, dict):
+ emv3ds = parameters.get("DS_MERCHANT_EMV3DS")
+ if isinstance(emv3ds, dict):
+ # Redsys uses notificationURL for the browser's 3DS completion,
+ # distinct from its DS_MERCHANT_MERCHANTURL webhook.
+ yield from callback_urls(emv3ds.get("notificationURL"))
+
+
+def callback_urls(value):
+ """Read JSON, form and XML callback fields, excluding notification URLs."""
+ if isinstance(value, dict):
+ for key, item in value.items():
+ if key == "Ds_MerchantParameters":
+ yield from _redsys_callback_urls(item)
+ elif not _NOTIFICATION.search(key):
+ yield from callback_urls(item)
+ return
+ if isinstance(value, list):
+ for item in value:
+ yield from callback_urls(item)
+ return
+ if not isinstance(value, str):
+ return
+
+ value = value.strip()
+ if value.startswith(("http://", "https://")):
+ parts = urlsplit(html.unescape(value))
+ if _CALLBACK.fullmatch(parts.path):
+ yield html.unescape(value)
+ for key, item in parse_qsl(parts.query):
+ yield from callback_urls({key: item})
+ return
+ try:
+ parsed = json.loads(value)
+ except (ValueError, TypeError):
+ parsed = None
+ if isinstance(parsed, (dict, list)):
+ yield from callback_urls(parsed)
+ return
+ if value.startswith("<"):
+ try:
+ root = ElementTree.fromstring(value)
+ except ElementTree.ParseError:
+ pass
+ else:
+ def visit(element):
+ if not _NOTIFICATION.search(element.tag):
+ yield from callback_urls(element.text)
+ for child in element:
+ yield from visit(child)
+ yield from visit(root)
+ return
+ if "=" in value:
+ for key, item in parse_qsl(value):
+ yield from callback_urls({key: item})
+ return
+
+ # Connector payloads can nest percent-encoded URLs (e.g. return_url).
+ for _ in range(3):
+ decoded = unquote(value)
+ if decoded == value:
+ break
+ value = decoded
+ value = html.unescape(value).replace(r"\/", "/")
+ for match in _URL.finditer(value):
+ url = match.group()
+ if _CALLBACK.fullmatch(urlsplit(url).path):
+ yield url
+
+
+class CallbackUrlStore:
+ def __init__(self):
+ self._urls = {}
+ self._lock = threading.Lock()
+
+ def capture(self, request_url, request_body, test_hash):
+ urls = set(callback_urls(request_url)) | set(callback_urls(request_body))
+ with self._lock:
+ for url in urls:
+ # Later connector calls may issue a new token for the same route.
+ path = re.sub(r"/token/[^/]+/", "/", urlsplit(url).path)
+ self._urls[path] = (url, test_hash)
+
+ def for_payment(self, payment_id, merchant_id):
+ with self._lock:
+ return [
+ url for url, _ in self._urls.values()
+ if _CALLBACK.fullmatch(urlsplit(url).path).groups() == (payment_id, merchant_id)
+ ]
+
+ def reset_for_hash(self, test_hash):
+ with self._lock:
+ # Confirm and redirect can be separate tests; keep other tests' URLs.
+ self._urls = {
+ path: entry for path, entry in self._urls.items()
+ if entry[1] != test_hash
+ }
diff --git a/cypress-tests/mitm-proxy/mitm_replay.py b/cypress-tests/mitm-proxy/mitm_replay.py
index 101704185d..77746da8da 100644
--- a/cypress-tests/mitm-proxy/mitm_replay.py
+++ b/cypress-tests/mitm-proxy/mitm_replay.py
@@ -19,8 +19,10 @@ import os
import threading
from collections import defaultdict
from http.server import BaseHTTPRequestHandler, HTTPServer
+from urllib.parse import parse_qs, urlsplit
from mitmproxy import http
+from callback_urls import CallbackUrlStore
# ───── config ─────
@@ -104,6 +106,7 @@ class CassetteStore:
_store = CassetteStore(CAPTURE_DIR)
+_callbacks = CallbackUrlStore()
# ───── response materialisation ─────
@@ -140,14 +143,25 @@ def _strict_block(reason: str, tag: str) -> http.Response:
# ───── admin server ─────
class AdminHandler(BaseHTTPRequestHandler):
- """Cypress /test/start resets cursors for that test's rids; /test/end is a no-op."""
+ """Expose current callbacks and reset a test's replay state on retries."""
def _send(self, code, payload):
self.send_response(code)
self.send_header("Content-Type", "application/json")
+ self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(json.dumps(payload).encode())
+ def do_GET(self):
+ path = urlsplit(self.path)
+ if path.path != "/callbacks":
+ self._send(404, {"error": "unknown admin endpoint"})
+ return
+ query = parse_qs(path.query)
+ payment_id = query.get("payment_id", [""])[0]
+ merchant_id = query.get("merchant_id", [""])[0]
+ self._send(200, {"urls": _callbacks.for_payment(payment_id, merchant_id)})
+
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
try:
@@ -161,6 +175,8 @@ class AdminHandler(BaseHTTPRequestHandler):
connector = (body.get("connector") or "").strip()
tag = f"[{connector}] " if connector else ""
reset = _store.reset_for_hash(test_id_hash) if test_id_hash else 0
+ if test_id_hash:
+ _callbacks.reset_for_hash(test_id_hash)
suffix = f" (reset {reset} rid cursors)" if reset else ""
print(f"[replay] ▶ {tag}{title}{suffix}")
@@ -195,6 +211,9 @@ def request(flow: http.HTTPFlow) -> None:
return
rid = flow.request.headers.get("x-request-id", "").strip()
+ _callbacks.capture(
+ flow.request.url, flow.request.get_text(strict=False), hash_from_rid(rid),
+ )
method = flow.request.method
path = flow.request.path.split("?", 1)[0]
diff --git a/cypress-tests/mitm-proxy/redirect_proxy.py b/cypress-tests/mitm-proxy/redirect_proxy.py
index 8e380a6507..81198f31b4 100644
--- a/cypress-tests/mitm-proxy/redirect_proxy.py
+++ b/cypress-tests/mitm-proxy/redirect_proxy.py
@@ -36,7 +36,7 @@ _redirect_count: dict[str, int] = {}
# ── Path helpers ──────────────────────────────────────────────────────────────
def _is_redirect_complete(path: str) -> bool:
- return "/redirect/complete/" in path or "/redirect/response/" in path
+ return re.search(r"/redirect/(?:token/[^/]+/)?(?:complete|response)/", path) is not None
def _extract_payment_id(path: str) -> str:
@@ -45,12 +45,11 @@ def _extract_payment_id(path: str) -> str:
def _extract_redirect_segment(path: str) -> str | None:
- parts = path.split("/")
- try:
- idx = parts.index("redirect")
- return "/".join(parts[idx:])
- except ValueError:
- return None
+ match = re.search(r"/redirect/(?:token/[^/]+/)?((?:complete|response)/.+)", path)
+ if match:
+ # Captured tokens are single-use and must not be saved for replay.
+ return "redirect/" + match.group(1).split("/callback/", 1)[0]
+ return None
# ── Body parsing ──────────────────────────────────────────────────────────────
@@ -101,7 +100,10 @@ def _write_to_captures(data: dict, filename: str) -> None:
if not redirect_segment:
return
- raw_connector = redirect_segment.split("/")[-1]
+ parts = redirect_segment.split("/")
+ if len(parts) < 3:
+ return
+ raw_connector = parts[2]
connector = re.sub(r"[^a-zA-Z0-9\-]", "", raw_connector)
if not connector:
return
@@ -175,7 +177,10 @@ class ProxyHandler(BaseHTTPRequestHandler):
self.headers.get("Content-Type", ""),
)
else:
- print(f"[redirect-proxy] WARNING: no reserved RID for paymentId={payment_id} path={self.path}")
+ print(
+ f"[redirect-proxy] WARNING: no reserved RID for paymentId={payment_id} "
+ f"path={_extract_redirect_segment(path_only)}"
+ )
def _call_upstream(self, headers: dict, body: bytes):
conn = http.client.HTTPConnection(UPSTREAM_HOST, UPSTREAM_PORT, timeout=30)
diff --git a/cypress-tests/mitm-proxy/test_callback_urls.py b/cypress-tests/mitm-proxy/test_callback_urls.py
new file mode 100644
index 0000000000..c224a4532a
--- /dev/null
+++ b/cypress-tests/mitm-proxy/test_callback_urls.py
@@ -0,0 +1,104 @@
+import base64
+import json
+import unittest
+from urllib.parse import urlencode
+
+from callback_urls import CallbackUrlStore, callback_urls
+
+
+TOKEN = "d9dc53cc-d1a1-4f57-9077-d20c2d614daa"
+NEW_TOKEN = "d9dc53cc-d1a1-4f57-9077-d20c2d614dab"
+CALLBACK = f"http://localhost:8080/payments/pay_1/merchant_1/redirect/token/{TOKEN}/complete/paybox"
+NOTIFY = CALLBACK.replace(TOKEN, NEW_TOKEN)
+
+
+class CallbackUrlTests(unittest.TestCase):
+ def test_redsys_encoded_3ds_callback_excludes_webhooks(self):
+ callback = CALLBACK.replace("/paybox", "/redsys")
+ parameters = {
+ "DS_MERCHANT_EMV3DS": {"notificationURL": callback, "notify_url": NOTIFY},
+ "DS_MERCHANT_MERCHANTURL": NOTIFY,
+ }
+ payload = {
+ "Ds_MerchantParameters": base64.b64encode(
+ json.dumps(parameters).encode()
+ ).decode(),
+ "Ds_SignatureVersion": "HMAC_SHA256_V1",
+ "Ds_Signature": "signature",
+ }
+ for body in [json.dumps(payload), urlencode(payload)]:
+ with self.subTest(body=body):
+ store = CallbackUrlStore()
+ store.capture("https://redsys.example/authorize", body, "confirm")
+ self.assertEqual(store.for_payment("pay_1", "merchant_1"), [callback])
+
+ def test_redsys_malformed_or_non_callback_parameters_are_ignored(self):
+ for parameters in [
+ "not base64!",
+ "",
+ None,
+ 123,
+ base64.b64encode(b"not json").decode(),
+ base64.b64encode(b"\xff").decode(),
+ *[
+ base64.b64encode(json.dumps(value).encode()).decode()
+ for value in [
+ [],
+ {"DS_MERCHANT_EMV3DS": None},
+ {"DS_MERCHANT_EMV3DS": {"notificationURL": "https://merchant.example"}},
+ {"DS_MERCHANT_MERCHANTURL": NOTIFY},
+ ]
+ ],
+ ]:
+ with self.subTest(parameters=parameters):
+ self.assertEqual(
+ list(callback_urls({"Ds_MerchantParameters": parameters})), []
+ )
+
+ def test_connector_payload_formats_exclude_notification_tokens(self):
+ payload = {"URLRetour": CALLBACK, "URLHttpDirect": NOTIFY}
+ for body in [
+ json.dumps(payload),
+ urlencode(payload),
+ f"<request><URLRetour>{CALLBACK}</URLRetour>"
+ f"<URLHttpDirect>{NOTIFY}</URLHttpDirect></request>",
+ json.dumps({"request": [payload]}),
+ json.dumps({"accept_url": CALLBACK, "notify_url": NOTIFY}),
+ json.dumps({"return_url": CALLBACK, "notificationURL": NOTIFY}),
+ ]:
+ with self.subTest(body=body):
+ self.assertEqual(list(callback_urls(body)), [CALLBACK])
+
+ def test_url_query_and_json_escaped_urls(self):
+ for value in [
+ "https://connector.example/authorize?" + urlencode({"return_url": CALLBACK}),
+ json.dumps({"return_url": CALLBACK}).replace("/", r"\/"),
+ ]:
+ self.assertEqual(list(callback_urls(value)), [CALLBACK])
+
+ def test_legacy_and_non_callback_urls_are_not_replayed(self):
+ for value in [
+ "http://localhost:8080/payments/pay_1/merchant_1/redirect/complete/paybox",
+ CALLBACK.replace("/complete/", "/start/"),
+ "https://merchant.example/return",
+ ]:
+ self.assertEqual(list(callback_urls(value)), [])
+
+ def test_current_tokens_are_scoped_to_payment_and_retries(self):
+ store = CallbackUrlStore()
+ store.capture("https://connector.example", json.dumps({"return_url": CALLBACK}), "confirm")
+ self.assertEqual(store.for_payment("pay_1", "merchant_1"), [CALLBACK])
+ self.assertEqual(store.for_payment("pay_2", "merchant_1"), [])
+ self.assertEqual(store.for_payment("pay_1", "merchant_2"), [])
+
+ # Cypress often confirms in one test and handles the redirect in another.
+ store.reset_for_hash("redirect")
+ self.assertEqual(store.for_payment("pay_1", "merchant_1"), [CALLBACK])
+ store.capture("https://connector.example", json.dumps({"return_url": NOTIFY}), "confirm")
+ self.assertEqual(store.for_payment("pay_1", "merchant_1"), [NOTIFY])
+ store.reset_for_hash("confirm")
+ self.assertEqual(store.for_payment("pay_1", "merchant_1"), [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/cypress-tests/mitm-proxy/test_redirect_proxy.py b/cypress-tests/mitm-proxy/test_redirect_proxy.py
new file mode 100644
index 0000000000..2b6f50524d
--- /dev/null
+++ b/cypress-tests/mitm-proxy/test_redirect_proxy.py
@@ -0,0 +1,66 @@
+import contextlib
+import io
+import json
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import redirect_proxy
+
+
+TOKEN = "d9dc53cc-d1a1-4f57-9077-d20c2d614daa"
+
+
+class RedirectPathTests(unittest.TestCase):
+ def test_redirect_detection_supports_legacy_and_token_paths(self):
+ for action in ["response", "complete"]:
+ for tail in ["stripe", "stripe/creds_1"]:
+ for path in [
+ f"/payments/pay_1/merchant_1/redirect/{action}/{tail}",
+ f"/payments/pay_1/merchant_1/redirect/{action}/{tail}/callback/{TOKEN}",
+ f"/payments/pay_1/merchant_1/redirect/token/{TOKEN}/{action}/{tail}",
+ ]:
+ with self.subTest(path=path):
+ self.assertTrue(redirect_proxy._is_redirect_complete(path))
+ self.assertEqual(redirect_proxy._extract_payment_id(path), "pay_1")
+ self.assertEqual(
+ redirect_proxy._extract_redirect_segment(path),
+ f"redirect/{action}/{tail}",
+ )
+ for action in ["start", "authorize"]:
+ self.assertFalse(redirect_proxy._is_redirect_complete(
+ f"/payments/pay_1/merchant_1/redirect/token/{TOKEN}/{action}/stripe"
+ ))
+
+ def test_saved_redirect_body_keeps_connector_data_without_the_token(self):
+ for method, body, content_type in [
+ ("GET", b"", ""),
+ ("POST", b"status=success", "application/x-www-form-urlencoded"),
+ ]:
+ data = redirect_proxy._build_redirect_data(
+ method,
+ f"/payments/pay_1/merchant_1/redirect/token/{TOKEN}/complete/paybox/creds_1",
+ "result=ok",
+ body,
+ content_type,
+ )
+ self.assertEqual(data["__redirect_segment"], "redirect/complete/paybox/creds_1")
+ self.assertNotIn(TOKEN, json.dumps(data))
+ if method == "GET":
+ self.assertEqual(data["__query"], {"result": "ok"})
+ else:
+ self.assertEqual(data["__body"], {"status": "success"})
+
+ def test_capture_directory_uses_connector_even_with_credentials(self):
+ data = {"__redirect_segment": "redirect/complete/paybox/creds_1"}
+ with tempfile.TemporaryDirectory() as directory:
+ with patch.object(redirect_proxy, "CAPTURE_DIR", directory):
+ with contextlib.redirect_stdout(io.StringIO()):
+ redirect_proxy._write_to_captures(data, "redirect.json")
+ capture = Path(directory) / "paybox" / "Payment" / "redirect-bodies" / "redirect.json"
+ self.assertEqual(json.loads(capture.read_text()), data)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/cypress-tests/mitm-proxy/test_replay_callbacks.mjs b/cypress-tests/mitm-proxy/test_replay_callbacks.mjs
new file mode 100644
index 0000000000..3d96d29d37
--- /dev/null
+++ b/cypress-tests/mitm-proxy/test_replay_callbacks.mjs
@@ -0,0 +1,131 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { mockReplay3ds } from "../cypress/support/mitmProxy.js";
+
+const responseUrl =
+ "http://localhost:8080/payments/pay_1/merchant_1/redirect/token/d9dc53cc-d1a1-4f57-9077-d20c2d614daa/response/braintree";
+const completeUrl = responseUrl
+ .replace("614daa", "614dab")
+ .replace("/response/", "/complete/");
+
+// Exercise the replay chain without a running browser, router or proxy.
+function replay(attributes, saved, adminCallbacks = []) {
+ const requests = [];
+ const state = { paymentID: "pay_1", merchantId: "merchant_1" };
+ globalThis.Cypress = {
+ env: (key) =>
+ ({
+ currentTestIdHash: "test",
+ CAPTURE_DIR: "/captures",
+ PROXY_ADMIN_URL: "http://localhost:8001",
+ })[key],
+ };
+ globalThis.DOMParser = class {
+ parseFromString() {
+ return { body: { getAttribute: (key) => attributes[key] || null } };
+ }
+ };
+ globalThis.expect = (value, message) => ({
+ to: {
+ have: {
+ length: (expected) => assert.equal(value.length, expected, message),
+ },
+ be: {
+ within: (min, max) => assert.ok(value >= min && value <= max, message),
+ a: (type) => {
+ assert.equal(typeof value, type, message);
+ return {
+ and: {
+ not: { be: { empty: assert.notEqual(value, "", message) } },
+ },
+ };
+ },
+ },
+ },
+ });
+ globalThis.cy = {
+ request: (options) => {
+ requests.push(options);
+ if (new URL(options.url).pathname === "/callbacks") {
+ assert.deepEqual(options.qs, {
+ payment_id: state.paymentID,
+ merchant_id: state.merchantId,
+ });
+ return Promise.resolve({ body: { urls: adminCallbacks } });
+ }
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ body: "redirect page",
+ });
+ },
+ task: (name) => {
+ assert.equal(name, "readFileOrNull");
+ return Promise.resolve(saved);
+ },
+ wrap: (value) => Promise.resolve(value),
+ };
+ return mockReplay3ds(
+ { get: (key) => state[key] },
+ "braintree",
+ "http://localhost:8080/start"
+ ).then(() => requests);
+}
+
+test("replay still accepts a page with a single callback", () => {
+ return replay(
+ { "data-callback-url": completeUrl },
+ { __redirect_segment: "redirect/complete/braintree", __body: {} }
+ ).then((requests) => {
+ assert.equal(requests.length, 2);
+ assert.equal(requests[1].url, completeUrl);
+ });
+});
+
+test("replay falls back to the proxy for callbacks absent from the page", () => {
+ return replay(
+ {},
+ { __redirect_segment: "redirect/complete/braintree", __body: {} },
+ [responseUrl, completeUrl]
+ ).then((requests) => {
+ assert.equal(requests.length, 3);
+ assert.equal(requests[2].url, completeUrl);
+ });
+});
+
+test("replay rejects a page callback for another payment", () => {
+ return assert.rejects(
+ replay(
+ { "data-complete-callback-url": completeUrl.replace("pay_1", "pay_2") },
+ { __redirect_segment: "redirect/complete/braintree", __body: {} }
+ ),
+ /one fresh router-issued callback for this payment/
+ );
+});
+
+for (const [route, url] of [
+ ["complete", completeUrl],
+ ["response", responseUrl],
+]) {
+ test(`Braintree replays the current ${route} callback from the page`, () => {
+ const saved = {
+ __redirect_segment: `redirect/${route}/braintree`,
+ __redirect_method: "POST",
+ __body: { authentication_response: "recorded connector payload" },
+ };
+ return replay(
+ {
+ "data-callback-url": responseUrl,
+ "data-complete-callback-url": completeUrl,
+ },
+ saved
+ ).then((requests) => {
+ assert.equal(requests.length, 2);
+ assert.equal(requests[1].url, url);
+ assert.equal(requests[1].method, "POST");
+ assert.deepEqual(requests[1].body, saved.__body);
+ assert.equal(requests[1].retryOnNetworkFailure, false);
+ });
+ });
+}