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(ucs): introduce `authentication_step` function to `authorize_flow` and bloat redsys with `authenticate` flow (#10490)

Pa1NarK4c8ad09788df
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 03f8190c8b..150cdaeb29 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -925,7 +925,7 @@ paysafe= { long_lived_token = false, payment_method = "card,wallet" ,payment_met
outgoing_enabled = true
redis_lock_expiry_seconds = 180
-[l2_l3_data_config]
+[l2_l3_data_config]
enabled = "true"
[webhook_source_verification_call]
diff --git a/config/development.toml b/config/development.toml
index 841a3159fb..3dba27c828 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -432,7 +432,7 @@ private_key = "" # RSA private key used for signing ID tokens (Generate using:
[oidc.client.c1]
client_id = "" # OIDC client identifier for the relying party (Generate using: openssl rand -hex 8)
client_secret = "" # Client secret used to authenticate the client (Generate using: openssl rand -hex 32)
-redirect_uri = "" # Redirect URI registered for the OIDC client
+redirect_uri = "" # Redirect URI registered for the OIDC client
[bank_config.eps]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 0b15cd8a42..c82e688ea1 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -6980,7 +6980,7 @@ pub struct SepaBankTransferInstructions {
pub reference: Secret<String>,
}
-#[derive(Clone, Debug, serde::Deserialize)]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaymentsConnectorThreeDsInvokeData {
pub directory_server_id: String,
pub three_ds_method_url: String,
diff --git a/crates/hyperswitch_connectors/src/connectors/redsys.rs b/crates/hyperswitch_connectors/src/connectors/redsys.rs
index 0065a46093..044f9a88ee 100644
--- a/crates/hyperswitch_connectors/src/connectors/redsys.rs
+++ b/crates/hyperswitch_connectors/src/connectors/redsys.rs
@@ -15,12 +15,12 @@ use hyperswitch_domain_models::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
- unified_authentication_service::PreAuthenticate,
+ unified_authentication_service::{Authenticate, PreAuthenticate},
CompleteAuthorize, PreProcessing,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
- PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
+ PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
@@ -29,10 +29,10 @@ use hyperswitch_domain_models::{
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
- PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
- PaymentsCompleteAuthorizeRouterData, PaymentsPreAuthenticateRouterData,
- PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundExecuteRouterData,
- RefundSyncRouterData,
+ PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
+ PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
+ PaymentsPreAuthenticateRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData,
+ RefundExecuteRouterData, RefundSyncRouterData,
},
};
use hyperswitch_interfaces::{
@@ -44,19 +44,21 @@ use hyperswitch_interfaces::{
errors,
events::connector_api_logs::ConnectorEvent,
types::{
- PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
- PaymentsPreAuthenticateType, PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType,
- RefundExecuteType, RefundSyncType, Response,
+ PaymentsAuthenticateType, PaymentsAuthorizeType, PaymentsCaptureType,
+ PaymentsCompleteAuthorizeType, PaymentsPreAuthenticateType, PaymentsPreProcessingType,
+ PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
},
webhooks,
};
+use masking::PeekInterface;
use transformers as redsys;
use crate::{
constants::headers,
types::ResponseRouterData,
- utils as connector_utils,
- utils::{PaymentsAuthorizeRequestData, PaymentsPreAuthenticateRequestData},
+ utils::{
+ self as connector_utils, PaymentsAuthorizeRequestData, PaymentsPreAuthenticateRequestData,
+ },
};
#[derive(Clone)]
@@ -86,6 +88,7 @@ impl api::RefundSync for Redsys {}
impl api::PaymentToken for Redsys {}
impl api::PaymentsPreProcessing for Redsys {}
impl api::PaymentsPreAuthenticate for Redsys {}
+impl api::PaymentsAuthenticate for Redsys {}
impl api::PaymentsCompleteAuthorize for Redsys {}
impl ConnectorCommon for Redsys {
@@ -330,6 +333,97 @@ impl ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, Payments
}
}
+impl ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData> for Redsys {
+ fn get_headers(
+ &self,
+ req: &PaymentsAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}/sis/rest/trataPeticionREST",
+ self.base_url(connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsAuthenticateRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let minor_amount =
+ req.request
+ .minor_amount
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "minor_amount",
+ })?;
+ let currency =
+ req.request
+ .currency
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "currency",
+ })?;
+ let amount =
+ connector_utils::convert_amount(self.amount_converter, minor_amount, currency)?;
+ let connector_router_data = redsys::RedsysRouterData::from((amount, req, currency));
+ let connector_req = redsys::RedsysTransaction::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthenticateType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .set_body(self.get_request_body(req, connectors)?)
+ .build();
+
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsAuthenticateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsAuthenticateRouterData, errors::ConnectorError> {
+ let response: redsys::RedsysResponse = res
+ .response
+ .parse_struct("RedsysResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Redsys {
fn get_headers(
&self,
@@ -986,6 +1080,42 @@ impl ConnectorSpecifications for Redsys {
}
}
+ fn is_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
+ match current_flow {
+ api::CurrentFlowInfo::Authorize {
+ auth_type,
+ request_data,
+ } => {
+ // For Redsys in authorize flow, if we reached authentication_step
+ // (controlled by should_continue_after_preauthenticate in pre_authentication_step),
+ // we should proceed with UCS authenticate call for 3DS flows.
+ // This handles the 3DS exempt scenario where no redirect is needed after preauthenticate.
+ auth_type.is_three_ds() && request_data.is_card()
+ }
+ api::CurrentFlowInfo::CompleteAuthorize {
+ request_data,
+ payment_method: _,
+ auth_type,
+ } => {
+ // For CompleteAuthorize flow:
+ // - If params is NOT empty: This is the first redirect return (from 3DS method/device data collection)
+ // → Run Authenticate flow
+ // - If params is empty/None: This is the second redirect return (from challenge)
+ // → Skip Authenticate, should run AuthorizeOnly instead
+ let redirection_params = request_data
+ .redirect_response
+ .as_ref()
+ .and_then(|redirect_response| redirect_response.params.as_ref());
+
+ match redirection_params {
+ Some(param) if !param.peek().is_empty() && auth_type.is_three_ds() => true,
+ Some(_) | None => false,
+ }
+ }
+ api::CurrentFlowInfo::SetupMandate { .. } => false,
+ }
+ }
+
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&REDSYS_CONNECTOR_INFO)
}
diff --git a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
index 53a9ad0ca5..02267ebe87 100644
--- a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
@@ -1,10 +1,12 @@
+use std::str::FromStr;
+
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
crypto::{EncodeMessage, SignMessage},
ext_traits::{Encode, ValueExt},
- types::StringMinorUnit,
+ types::{SemanticVersion, StringMinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
@@ -13,15 +15,15 @@ use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
- BrowserInformation, CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsSyncData,
- ResponseId,
+ self, BrowserInformation, CompleteAuthorizeData, PaymentsAuthenticateData,
+ PaymentsAuthorizeData, PaymentsSyncData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
- PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
- PaymentsCompleteAuthorizeRouterData, PaymentsPreAuthenticateRouterData,
- PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
- RefundsRouterData,
+ PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
+ PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
+ PaymentsPreAuthenticateRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
@@ -35,9 +37,10 @@ use crate::{
RefundsResponseRouterData, ResponseRouterData,
},
utils::{
- self as connector_utils, AddressDetailsData, BrowserInformationData, CardData,
- PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
- PaymentsPreAuthenticateRequestData, PaymentsPreProcessingRequestData, RouterData as _,
+ self as connector_utils, missing_field_err, AddressDetailsData, BrowserInformationData,
+ CardData, ForeignTryFrom, PaymentsAuthenticateRequestData, PaymentsAuthorizeRequestData,
+ PaymentsCompleteAuthorizeRequestData, PaymentsPreAuthenticateRequestData,
+ PaymentsPreProcessingRequestData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
@@ -102,6 +105,7 @@ pub struct EmvThreedsData {
browser_screen_width: Option<String>,
browser_t_z: Option<String>,
browser_i_p: Option<Secret<String, common_utils::pii::IpAddress>>,
+ #[serde(alias = "threeds_server_transaction_id")]
three_d_s_server_trans_i_d: Option<String>,
notification_u_r_l: Option<String>,
three_d_s_comp_ind: Option<ThreeDSCompInd>,
@@ -632,6 +636,7 @@ pub struct DsResponse(String);
#[serde(rename_all = "camelCase")]
pub struct RedsysEmv3DSData {
protocol_version: String,
+ #[serde(alias = "threeds_server_transaction_id")]
three_d_s_server_trans_i_d: Option<String>,
three_d_s_info: Option<RedsysThreeDsInfo>,
three_d_s_method_u_r_l: Option<String>,
@@ -642,6 +647,7 @@ pub struct RedsysEmv3DSData {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsInvokeRequest {
+ #[serde(alias = "threeds_server_transaction_id")]
three_d_s_server_trans_i_d: String,
three_d_s_method_notification_u_r_l: String,
}
@@ -657,6 +663,7 @@ pub struct RedsysThreeDsInvokeData {
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDsInvokeExempt {
+ #[serde(alias = "threeds_server_transaction_id")]
pub three_d_s_server_trans_i_d: String,
pub message_version: String,
}
@@ -815,6 +822,48 @@ fn handle_success_response(
}
}
+impl ForeignTryFrom<&RedsysThreeDsInvokeData> for router_request_types::UcsAuthenticationData {
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn foreign_try_from(value: &RedsysThreeDsInvokeData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ eci: None,
+ cavv: None,
+ threeds_server_transaction_id: Some(value.directory_server_id.clone()),
+ message_version: Some(
+ SemanticVersion::from_str(&value.message_version)
+ .change_context(errors::ConnectorError::ParsingFailed)?,
+ ),
+ ds_trans_id: None,
+ acs_trans_id: None,
+ trans_status: None,
+ transaction_id: None,
+ ucaf_collection_indicator: None,
+ })
+ }
+}
+
+impl ForeignTryFrom<&ThreeDsInvokeExempt> for router_request_types::UcsAuthenticationData {
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn foreign_try_from(value: &ThreeDsInvokeExempt) -> Result<Self, Self::Error> {
+ Ok(Self {
+ eci: None,
+ cavv: None,
+ threeds_server_transaction_id: Some(value.three_d_s_server_trans_i_d.clone()),
+ message_version: Some(
+ SemanticVersion::from_str(&value.message_version)
+ .change_context(errors::ConnectorError::ParsingFailed)?,
+ ),
+ ds_trans_id: None,
+ acs_trans_id: None,
+ trans_status: None,
+ transaction_id: None,
+ ucaf_collection_indicator: None,
+ })
+ }
+}
+
// Build 3DS invoke response
fn build_threeds_invoke_response(
response_data: &RedsysPaymentsResponse,
@@ -854,6 +903,11 @@ fn build_threeds_invoke_response(
.attach_printable("Failed to serialize ThreeDsData")?,
);
+ let authentication_data =
+ router_request_types::UcsAuthenticationData::foreign_try_from(&three_ds_data)
+ .ok()
+ .map(Box::new);
+
let response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response_data.ds_order.clone()),
redirection_data: Box::new(None),
@@ -862,7 +916,7 @@ fn build_threeds_invoke_response(
network_txn_id: None,
connector_response_reference_id: Some(response_data.ds_order.clone()),
incremental_authorization_allowed: None,
- authentication_data: None,
+ authentication_data,
charges: None,
});
@@ -892,6 +946,11 @@ fn build_threeds_invoke_exempt_response(
.attach_printable("Failed to serialize ThreeDsData")?,
);
+ let authentication_data =
+ router_request_types::UcsAuthenticationData::foreign_try_from(&three_ds_data)
+ .ok()
+ .map(Box::new);
+
let response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response_data.ds_order.clone()),
redirection_data: Box::new(None),
@@ -900,7 +959,7 @@ fn build_threeds_invoke_exempt_response(
network_txn_id: None,
connector_response_reference_id: Some(response_data.ds_order.clone()),
incremental_authorization_allowed: None,
- authentication_data: None,
+ authentication_data,
charges: None,
});
@@ -1088,6 +1147,70 @@ impl TryFrom<&RedsysRouterData<&PaymentsAuthorizeRouterData>> for RedsysTransact
}
}
+impl TryFrom<&RedsysRouterData<&PaymentsAuthenticateRouterData>> for RedsysTransaction {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &RedsysRouterData<&PaymentsAuthenticateRouterData>,
+ ) -> Result<Self, Self::Error> {
+ if !item.router_data.is_three_ds() {
+ Err(errors::ConnectorError::NotSupported {
+ message: "No-3DS cards".to_string(),
+ connector: "redsys",
+ })?
+ };
+
+ let auth = RedsysAuthType::try_from(&item.router_data.connector_auth_type)?;
+ let ds_merchant_transactiontype = if item.router_data.request.is_auto_capture()? {
+ RedsysTransactionType::Payment
+ } else {
+ RedsysTransactionType::Preauthorization
+ };
+ let card_data =
+ RedsysCardData::try_from(&item.router_data.request.payment_method_data.clone())?;
+
+ let authentication_data = &item.router_data.request.authentication_data;
+ let three_d_s_server_trans_i_d = authentication_data
+ .clone()
+ .and_then(|auth| auth.threeds_server_transaction_id.clone())
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "authentication_data.threeds_server_transaction_id",
+ })?;
+
+ let message_version = authentication_data
+ .clone()
+ .and_then(|auth| auth.message_version.as_ref().map(|v| v.to_string()))
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "authentication_data.message_version",
+ })?;
+
+ let ds_merchant_order = item.router_data.connector_request_reference_id.clone();
+
+ let emv3ds_data = EmvThreedsData::new(RedsysThreeDsInfo::AuthenticationData)
+ .set_three_d_s_server_trans_i_d(three_d_s_server_trans_i_d)
+ .set_protocol_version(message_version)
+ .set_notification_u_r_l(item.router_data.request.get_complete_authorize_url()?)
+ .add_browser_data(item.router_data.request.get_browser_info()?)?
+ .set_three_d_s_comp_ind(ThreeDSCompInd::N)
+ .set_billing_data(item.router_data.get_optional_billing())?
+ .set_shipping_data(item.router_data.get_optional_shipping())?;
+
+ let payment_authorize_request = PaymentsRequest {
+ ds_merchant_emv3ds: Some(emv3ds_data),
+ ds_merchant_transactiontype,
+ ds_merchant_currency: item.currency.iso_4217().to_owned(),
+ ds_merchant_pan: card_data.card_number,
+ ds_merchant_merchantcode: auth.merchant_id.clone(),
+ ds_merchant_terminal: auth.terminal_id.clone(),
+ ds_merchant_order,
+ ds_merchant_amount: item.amount.clone(),
+ ds_merchant_expirydate: card_data.expiry_date,
+ ds_merchant_cvv2: card_data.cvv2,
+ };
+ router_env::logger::info!(connector_authorize_request=?payment_authorize_request);
+ Self::try_from((&payment_authorize_request, &auth))
+ }
+}
+
fn build_threeds_form(ds_emv3ds: &RedsysEmv3DSData) -> Result<RedirectForm, Error> {
let creq = ds_emv3ds
.creq
@@ -1132,6 +1255,61 @@ impl<F> TryFrom<ResponseRouterData<F, RedsysResponse, PaymentsAuthorizeData, Pay
response_data,
item.data.request.capture_method,
connector_metadata,
+ None,
+ item.http_code,
+ )?
+ }
+ RedsysResponse::RedsysErrorResponse(response) => {
+ let response = Err(ErrorResponse {
+ code: response.error_code.clone(),
+ message: response.error_code.clone(),
+ reason: Some(response.error_code.clone()),
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ connector_response_reference_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ });
+
+ (response, enums::AttemptStatus::Failure)
+ }
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+}
+
+impl<F>
+ TryFrom<ResponseRouterData<F, RedsysResponse, PaymentsAuthenticateData, PaymentsResponseData>>
+ for RouterData<F, PaymentsAuthenticateData, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, RedsysResponse, PaymentsAuthenticateData, PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let (response, status) = match item.response.clone() {
+ RedsysResponse::RedsysResponse(transaction_response) => {
+ let connector_metadata = Some(
+ serde_json::to_value(item.data.request.authentication_data.clone())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?,
+ );
+
+ let response_data: RedsysPaymentsResponse = to_connector_response_data(
+ &transaction_response.ds_merchant_parameters.clone().expose(),
+ )?;
+
+ router_env::logger::info!(connector_authorize_response=?response_data);
+ get_payments_response(
+ response_data,
+ item.data.request.capture_method,
+ connector_metadata,
+ item.data.request.authentication_data.clone().map(Box::new),
item.http_code,
)?
}
@@ -1216,6 +1394,31 @@ impl TryFrom<&RedsysRouterData<&PaymentsCompleteAuthorizeRouterData>> for Redsys
.set_three_d_s_cres(payload.cres)
.set_billing_data(billing_data)?
.set_shipping_data(shipping_data)?
+ } else if let Some(authentication_data) = item
+ .router_data
+ .request
+ .connector_meta
+ .as_ref()
+ .and_then(|metadata| metadata.get("authentication_data"))
+ .map(|value| {
+ serde_json::from_value::<router_request_types::UcsAuthenticationData>(
+ value.clone(),
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to parse authentication_data from connector_meta")
+ })
+ .transpose()?
+ {
+ EmvThreedsData::new(RedsysThreeDsInfo::ChallengeResponse)
+ .set_protocol_version(
+ authentication_data
+ .message_version
+ .ok_or_else(missing_field_err("protocol_version"))?
+ .to_string(),
+ )
+ .set_three_d_s_cres(payload.cres)
+ .set_billing_data(billing_data)?
+ .set_shipping_data(shipping_data)?
} else {
Err(errors::ConnectorError::RequestEncodingFailed)?
}
@@ -1292,10 +1495,14 @@ impl<F> TryFrom<ResponseRouterData<F, RedsysResponse, CompleteAuthorizeData, Pay
)?;
router_env::logger::info!(connector_complete_authorize_response=?response_data);
+ let authentication_data =
+ item.data.request.authentication_data.clone().map(Box::new);
+
get_payments_response(
response_data,
item.data.request.capture_method,
None,
+ authentication_data,
item.http_code,
)?
}
@@ -1356,13 +1563,6 @@ pub struct RedsysOperationsResponse {
ds_authorisation_code: Option<String>,
}
-#[derive(Debug, Deserialize, Serialize, Clone)]
-#[serde(untagged)]
-pub enum RedsysOperationResponse {
- RedsysOperationResponse(RedsysTransaction),
- RedsysOperationsErrorResponse(RedsysErrorResponse),
-}
-
impl TryFrom<&RedsysRouterData<&PaymentsCaptureRouterData>> for RedsysTransaction {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RedsysRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
@@ -1635,6 +1835,7 @@ fn get_payments_response(
redsys_payments_response: RedsysPaymentsResponse,
capture_method: Option<enums::CaptureMethod>,
connector_metadata: Option<josekit::Value>,
+ authentication_data: Option<Box<router_request_types::UcsAuthenticationData>>,
http_code: u16,
) -> Result<
(
@@ -1670,7 +1871,7 @@ fn get_payments_response(
network_txn_id: None,
connector_response_reference_id: Some(redsys_payments_response.ds_order.clone()),
incremental_authorization_allowed: None,
- authentication_data: None,
+ authentication_data,
charges: None,
})
};
@@ -1691,7 +1892,7 @@ fn get_payments_response(
network_txn_id: None,
connector_response_reference_id: Some(redsys_payments_response.ds_order.clone()),
incremental_authorization_allowed: None,
- authentication_data: None,
+ authentication_data,
charges: None,
});
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 2b0f765947..5ca8b1bd4e 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -2351,7 +2351,6 @@ default_imp_for_authenticate_steps!(
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
- connectors::Redsys,
connectors::Riskified,
connectors::Santander,
connectors::Shift4,
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index ae59d8b3d9..7700f4acbd 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -65,11 +65,11 @@ use hyperswitch_domain_models::{
router_request_types::{
AuthenticationData, AuthoriseIntegrityObject, BrowserInformation, CaptureIntegrityObject,
CompleteAuthorizeData, ConnectorCustomerData, ExternalVaultProxyPaymentsData,
- MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
- PaymentsCancelData, PaymentsCaptureData, PaymentsPostAuthenticateData,
- PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData,
- PaymentsSyncData, RefundIntegrityObject, RefundsData, ResponseId, SetupMandateRequestData,
- SyncIntegrityObject,
+ MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthenticateData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
+ PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData,
+ PaymentsPreProcessingData, PaymentsSyncData, RefundIntegrityObject, RefundsData,
+ ResponseId, SetupMandateRequestData, SyncIntegrityObject,
},
router_response_types::{CaptureSyncResponse, PaymentsResponseData},
types::{OrderDetailsWithAmount, SetupMandateRouterData},
@@ -2900,6 +2900,46 @@ impl PaymentsPreAuthenticateRequestData for PaymentsPreAuthenticateData {
self.currency.ok_or_else(missing_field_err("currency"))
}
}
+
+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_browser_info(&self) -> Result<BrowserInformation, Error>;
+}
+
+impl PaymentsAuthenticateRequestData for PaymentsAuthenticateData {
+ fn is_auto_capture(&self) -> Result<bool, Error> {
+ match self.capture_method {
+ Some(enums::CaptureMethod::Automatic)
+ | None
+ | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
+ Some(enums::CaptureMethod::Manual) => Ok(false),
+ Some(enums::CaptureMethod::ManualMultiple) | Some(enums::CaptureMethod::Scheduled) => {
+ Err(errors::ConnectorError::CaptureMethodNotSupported.into())
+ }
+ }
+ }
+
+ fn get_payment_method_data(&self) -> Result<PaymentMethodData, Error> {
+ self.payment_method_data
+ .clone()
+ .ok_or_else(missing_field_err("payment_method_data"))
+ }
+
+ fn get_complete_authorize_url(&self) -> Result<String, Error> {
+ self.complete_authorize_url
+ .clone()
+ .ok_or_else(missing_field_err("complete_authorize_url"))
+ }
+
+ fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
+ self.browser_info
+ .clone()
+ .ok_or_else(missing_field_err("browser_info"))
+ }
+}
+
pub trait PaymentsPreProcessingRequestData {
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_email(&self) -> Result<Email, Error>;
@@ -7322,6 +7362,7 @@ pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data(
request_incremental_authorization: data.request.request_incremental_authorization,
metadata: None,
authentication_data: None,
+ ucs_authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
split_payments: None, // TODO: allow charges on mandates?
guest_customer: None,
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index cb0e758e5c..cee8e0fd38 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -14,7 +14,7 @@ use common_utils::{
use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount};
use error_stack::ResultExt;
use masking::Secret;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use super::payment_method_data::PaymentMethodData;
@@ -68,6 +68,7 @@ pub struct PaymentsAuthorizeData {
pub request_incremental_authorization: bool,
pub metadata: Option<serde_json::Value>,
pub authentication_data: Option<AuthenticationData>,
+ pub ucs_authentication_data: Option<UcsAuthenticationData>,
pub request_extended_authorization:
Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
@@ -783,6 +784,28 @@ impl TryFrom<SetupMandateRequestData> for PaymentsPreAuthenticateData {
}
}
+impl TryFrom<PaymentsAuthorizeData> for PaymentsAuthenticateData {
+ type Error = error_stack::Report<ApiErrorResponse>;
+
+ fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_data: Some(data.payment_method_data),
+ payment_method_type: data.payment_method_type,
+ amount: Some(data.amount),
+ minor_amount: Some(data.minor_amount),
+ email: data.email,
+ currency: Some(data.currency),
+ complete_authorize_url: data.complete_authorize_url,
+ browser_info: data.browser_info,
+ redirect_response: None,
+ capture_method: data.capture_method,
+ // This is hard coded to None to avoid back and forth authentication_data conversion between UcsAuthenticationData and AuthenticationData.
+ // This is handled within authentication_step function in authorize_flow.rs
+ authentication_data: None,
+ })
+ }
+}
+
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsAuthenticateData {
pub payment_method_data: Option<PaymentMethodData>,
@@ -794,6 +817,8 @@ pub struct PaymentsAuthenticateData {
pub browser_info: Option<BrowserInformation>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub minor_amount: Option<MinorUnit>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub authentication_data: Option<UcsAuthenticationData>,
}
impl TryFrom<CompleteAuthorizeData> for PaymentsAuthenticateData {
@@ -810,6 +835,8 @@ impl TryFrom<CompleteAuthorizeData> for PaymentsAuthenticateData {
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
redirect_response: data.redirect_response,
+ capture_method: data.capture_method,
+ authentication_data: data.authentication_data,
})
}
}
@@ -828,6 +855,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>,
}
impl TryFrom<CompleteAuthorizeData> for PaymentsPostAuthenticateData {
@@ -846,6 +874,7 @@ impl TryFrom<CompleteAuthorizeData> for PaymentsPostAuthenticateData {
connector_transaction_id: data.connector_transaction_id,
redirect_response: data.redirect_response,
metadata: data.connector_meta.map(Secret::new),
+ complete_authorize_url: data.complete_authorize_url,
})
}
}
@@ -1194,7 +1223,7 @@ impl
}
}
-#[derive(Debug, Clone, Serialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UcsAuthenticationData {
pub eci: Option<String>,
pub cavv: Option<Secret<String>>,
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 4b5512a8aa..073d9d761f 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -43,9 +43,7 @@ use crate::{
self, access_token, customers, flows::gateway_context, gateway as payments_gateway,
helpers, session_token, tokenization, transformers, PaymentData,
},
- unified_connector_service::{
- self, build_unified_connector_service_auth_metadata, ucs_logging_wrapper_granular,
- },
+ unified_connector_service,
},
logger,
routes::{metrics, SessionState},
@@ -464,9 +462,10 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
"Pre-authentication flow is required for connector: {}",
connector.connector_name
);
- let authorize_request_data = self.request.clone();
+ let mut authorize_request_data = self.request.clone();
let pre_authenticate_request_data =
types::PaymentsPreAuthenticateData::try_from(self.request.to_owned())?;
+
let pre_authenticate_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
@@ -493,14 +492,28 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
None,
))
.await?;
+
// Convert back to CompleteAuthorize router data while preserving pre authentication response data
let pre_authenticate_response = pre_authenticate_router_data.response.clone();
+
+ authorize_request_data.ucs_authentication_data =
+ if let Ok(types::PaymentsResponseData::TransactionResponse {
+ ref authentication_data,
+ ..
+ }) = pre_authenticate_response
+ {
+ authentication_data.clone().map(|boxed| *boxed)
+ } else {
+ None
+ };
+
let mut authorize_router_data =
helpers::router_data_type_conversion::<_, api::Authorize, _, _, _, _>(
pre_authenticate_router_data,
authorize_request_data,
pre_authenticate_response,
);
+
if let Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse {
enrolled_v2,
related_transaction_id,
@@ -511,22 +524,27 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
authorize_router_data.request.enrolled_for_3ds = enrolled_for_3ds;
authorize_router_data.request.related_transaction_id = related_transaction_id;
}
+
let should_continue_after_preauthenticate = match connector.connector_name {
// connector specific handling to decide whether to continue with authorize or not should not be done here
// this is just a temporary fix for Redsys and Shift4 connectors
api_models::enums::Connector::Redsys => match &authorize_router_data.response {
Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata,
+ redirection_data,
..
}) => {
- let three_ds_invoke_data: Option<
- api_models::payments::PaymentsConnectorThreeDsInvokeData,
- > = connector_metadata.clone().and_then(|metadata| {
- metadata
- .parse_value("PaymentsConnectorThreeDsInvokeData")
- .ok()
- });
- three_ds_invoke_data.is_none()
+ let has_ucs_redirection = redirection_data.is_some();
+
+ let has_hyperswitch_three_ds_invoke_data: bool =
+ connector_metadata.clone().and_then(|metadata| {
+ metadata
+ .parse_value::<api_models::payments::PaymentsConnectorThreeDsInvokeData>("PaymentsConnectorThreeDsInvokeData")
+ .ok()
+ }).is_some();
+
+ // Continue only if neither UCS nor hyperswitch indicates a redirect is needed
+ !has_ucs_redirection && !has_hyperswitch_three_ds_invoke_data
}
_ => false,
},
@@ -540,6 +558,145 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
}
}
+ async fn authentication_step<'a>(
+ self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ gateway_context: &gateway_context::RouterGatewayContext,
+ ) -> RouterResult<(Self, bool)>
+ where
+ Self: Sized,
+ {
+ if connector.connector.is_authentication_flow_required(
+ api_interface::CurrentFlowInfo::Authorize {
+ auth_type: &self.auth_type,
+ request_data: &self.request,
+ },
+ ) {
+ logger::info!(
+ "Authentication flow is required for connector: {}",
+ connector.connector_name
+ );
+ let mut authorize_request_data = self.request.clone();
+
+ let mut authenticate_request_data =
+ types::PaymentsAuthenticateData::try_from(self.request.to_owned())?;
+
+ authenticate_request_data.authentication_data =
+ authorize_request_data.ucs_authentication_data.clone();
+
+ let authenticate_response_data: Result<
+ types::PaymentsResponseData,
+ types::ErrorResponse,
+ > = Err(types::ErrorResponse::default());
+
+ let authenticate_router_data =
+ helpers::router_data_type_conversion::<_, api::Authenticate, _, _, _, _>(
+ self.clone(),
+ authenticate_request_data,
+ authenticate_response_data,
+ );
+
+ // Call UCS for Authenticate flow and store authentication result for next step
+ let authenticate_router_data = Box::pin(payments_gateway::handle_gateway_call::<
+ _,
+ _,
+ _,
+ PaymentFlowData,
+ _,
+ >(
+ state,
+ authenticate_router_data,
+ connector,
+ gateway_context,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ ))
+ .await?;
+
+ let authenticate_response = authenticate_router_data.response.clone();
+
+ // Extract authentication_data from authenticate response
+ let authentication_data_clone =
+ if let Ok(types::PaymentsResponseData::TransactionResponse {
+ connector_metadata,
+ authentication_data,
+ ..
+ }) = &authenticate_router_data.response
+ {
+ connector_metadata.clone_into(&mut authorize_request_data.metadata);
+ authorize_request_data.ucs_authentication_data =
+ authentication_data.clone().map(|data| *data);
+
+ authentication_data.clone()
+ } else {
+ None
+ };
+
+ let mut authorize_router_data =
+ helpers::router_data_type_conversion::<_, api::Authorize, _, _, _, _>(
+ authenticate_router_data.clone(),
+ authorize_request_data.clone(),
+ authenticate_response.clone(),
+ );
+
+ // Merge authentication_data into connector_metadata for persistence
+ // This ensures authentication_data is available in CompleteAuthorize flow
+ if let Some(auth_data) = authentication_data_clone {
+ if let Ok(types::PaymentsResponseData::TransactionResponse {
+ connector_metadata,
+ ..
+ }) = &mut authorize_router_data.response
+ {
+ *connector_metadata = Some(serde_json::json!({
+ "authentication_data": auth_data
+ }));
+ }
+ }
+
+ let should_continue_after_authenticate = match &authorize_router_data.response {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ connector_metadata,
+ redirection_data,
+ ..
+ }) => match connector.connector_name {
+ api_models::enums::Connector::Redsys => {
+ // For UCS Redsys: if redirection_data is present (3DS challenge), don't continue
+ // For hyperswitch native: check connector_metadata for PaymentsConnectorThreeDsInvokeData
+ let has_ucs_redirection = redirection_data.is_some();
+
+ let has_hyperswitch_three_ds_invoke_data: bool =
+ connector_metadata.clone().and_then(|metadata| {
+ metadata
+ .parse_value::<api_models::payments::PaymentsConnectorThreeDsInvokeData>("PaymentsConnectorThreeDsInvokeData")
+ .ok()
+ }).is_some();
+
+ let payment_status = !matches!(
+ authorize_router_data.status,
+ common_enums::AttemptStatus::AuthenticationFailed
+ | common_enums::AttemptStatus::Failure
+ | common_enums::AttemptStatus::Charged
+ | common_enums::AttemptStatus::PartialCharged
+ | common_enums::AttemptStatus::Authorized
+ );
+
+ // Continue only if neither UCS nor hyperswitch indicates a redirect is needed
+ !has_ucs_redirection
+ && !has_hyperswitch_three_ds_invoke_data
+ && payment_status
+ }
+ _ => false,
+ },
+ _ => false,
+ };
+ Ok((authorize_router_data, should_continue_after_authenticate))
+ } else {
+ Ok((self, true))
+ }
+ }
+
async fn postprocessing_steps<'a>(
self,
state: &SessionState,
@@ -1150,6 +1307,98 @@ fn transform_response_for_pre_authenticate_flow(
},
)
}
+ // TODO: Temporary solution for Redsys 3DS invoke flow via UCS
+ //
+ // Currently, UCS returns 3DS invoke data in `redirection_data.form_fields` instead of
+ // `connector_metadata`. This workaround extracts the invoke data from form_fields and
+ // constructs `PaymentsConnectorThreeDsInvokeData` to populate `connector_metadata`,
+ // enabling the `invoke_hidden_iframe` next_action to be correctly generated.
+ //
+ // For 3DS invoke: form_fields contains threeDsMethodData, threeDSServerTransID, etc.
+ // -> Extract and set as connector_metadata, clear redirection_data
+ // For 3DS exempt/challenge: No invoke data in form_fields
+ // -> Keep redirection_data as-is, connector_metadata remains None
+ //
+ // A permanent solution requires redesigning how UCS passes 3DS invoke data back to
+ // Hyperswitch, potentially through dedicated fields in the gRPC response or a unified
+ // authentication data structure that covers all 3DS scenarios.
+ (
+ enums::connector_enums::Connector::Redsys,
+ router_response_types::PaymentsResponseData::TransactionResponse {
+ resource_id,
+ redirection_data,
+ mandate_reference,
+ connector_metadata: _,
+ network_txn_id,
+ connector_response_reference_id,
+ incremental_authorization_allowed,
+ charges,
+ authentication_data,
+ },
+ ) => {
+ // Check if this is a 3DS invoke response by looking at form_fields
+ let (connector_metadata, redirection_data) =
+ if let Some(ref redirect_form) = *redirection_data {
+ if let router_response_types::RedirectForm::Form {
+ endpoint,
+ form_fields,
+ ..
+ } = redirect_form
+ {
+ // Check for 3DS invoke - has threeDsMethodData and threeDSServerTransID
+ if form_fields.contains_key("threeDsMethodData")
+ && form_fields.contains_key("threeDSServerTransID")
+ {
+ // This is 3DS invoke - construct PaymentsConnectorThreeDsInvokeData
+ let invoke_data =
+ api_models::payments::PaymentsConnectorThreeDsInvokeData {
+ directory_server_id: form_fields
+ .get("threeDSServerTransID")
+ .cloned()
+ .unwrap_or_default(),
+ three_ds_method_url: form_fields
+ .get("threeDsMethodUrl")
+ .cloned()
+ .unwrap_or_else(|| endpoint.clone()),
+ three_ds_method_data: form_fields
+ .get("threeDsMethodData")
+ .cloned()
+ .unwrap_or_default(),
+ message_version: form_fields.get("messageVersion").cloned(),
+ three_ds_method_data_submission: form_fields
+ .get("threeDsMethodDataSubmission")
+ .map(|v| v == "true")
+ .unwrap_or(true),
+ };
+ // Set connector_metadata with invoke data, clear redirection_data
+ (serde_json::to_value(&invoke_data).ok(), Box::new(None))
+ } else {
+ // 3DS exempt or challenge - keep redirection_data, no special connector_metadata
+ (None, redirection_data)
+ }
+ } else {
+ // Not a Form type redirect
+ (None, redirection_data)
+ }
+ } else {
+ // No redirection data
+ (None, redirection_data)
+ };
+
+ Ok(
+ router_response_types::PaymentsResponseData::TransactionResponse {
+ resource_id,
+ redirection_data,
+ mandate_reference,
+ connector_metadata,
+ network_txn_id,
+ connector_response_reference_id,
+ incremental_authorization_allowed,
+ charges,
+ authentication_data,
+ },
+ )
+ }
_ => Ok(response_data),
}
}
@@ -1193,13 +1442,14 @@ pub async fn call_unified_connector_service_pre_authenticate(
.change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Authorize Request")?;
- let connector_auth_metadata = build_unified_connector_service_auth_metadata(
- merchant_connector_account,
- processor,
- router_data.connector.clone(),
- )
- .change_context(interface_errors::ConnectorError::RequestEncodingFailed)
- .attach_printable("Failed to construct request metadata")?;
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ processor,
+ router_data.connector.clone(),
+ )
+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
@@ -1215,7 +1465,7 @@ pub async fn call_unified_connector_service_pre_authenticate(
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- Box::pin(ucs_logging_wrapper_granular(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_pre_authenticate_request,
@@ -1244,9 +1494,12 @@ pub async fn call_unified_connector_service_pre_authenticate(
response
});
let router_data_response = match router_data_response {
- Ok(response) => Ok(transform_response_for_pre_authenticate_flow(connector, response)?),
- Err(err) => Err(err)
+ Ok(response) => Ok(transform_response_for_pre_authenticate_flow(
+ connector, response,
+ )?),
+ Err(err) => Err(err),
};
+ // Extract authentication_data from the response to store in connector_metadata
router_data.response = router_data_response;
router_data.raw_connector_response = payment_pre_authenticate_response
.raw_connector_response
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 840b1a7026..1fef6d35cb 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -458,8 +458,10 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
);
// Convert CompleteAuthorize to PostAuthenticate for UCS call
let mut complete_authorize_request_data = router_data.request.clone();
+
let post_authenticate_request_data =
types::PaymentsPostAuthenticateData::try_from(router_data.request.to_owned())?;
+
let post_authenticate_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
@@ -700,6 +702,7 @@ pub async fn call_unified_connector_service_authenticate(
)?),
Err(err) => Err(err),
};
+
router_data.response = router_data_response;
router_data.raw_connector_response = payment_authenticate_response
.raw_connector_response
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 1405b170dd..3e0514e26a 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -456,6 +456,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(
),
metadata: payment_data.payment_intent.metadata.expose_option(),
authentication_data: None,
+ ucs_authentication_data: None,
customer_acceptance: None,
split_payments: None,
guest_customer: None,
@@ -4704,6 +4705,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.clone()
.map(|m| m.expose()),
authentication_data: None,
+ ucs_authentication_data: None,
request_extended_authorization: None,
split_payments: None,
guest_customer: None,
@@ -4745,6 +4747,8 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
+ use hyperswitch_domain_models::router_request_types::UcsAuthenticationData;
+
let payment_data = additional_data.payment_data.clone();
let router_base_url = &additional_data.router_base_url;
let connector_name = &additional_data.connector_name;
@@ -4944,6 +4948,11 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.as_ref()
.map(AuthenticationData::foreign_try_from)
.transpose()?),
+ ucs_authentication_data: payment_data
+ .authentication
+ .as_ref()
+ .map(UcsAuthenticationData::foreign_try_from)
+ .transpose()?,
customer_acceptance: payment_data.customer_acceptance,
request_extended_authorization: attempt.request_extended_authorization,
split_payments,
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index ff87aaf4e5..c24c1765b2 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -367,7 +367,7 @@ impl
.map(|payment_channel| payment_channel.into()),
connector_metadata: None,
locale: router_data.request.locale.clone(),
- continue_redirection_url: None,
+ continue_redirection_url: router_data.request.complete_authorize_url.clone(),
redirection_response: None,
threeds_completion_indicator: None,
tokenization_strategy: router_data
@@ -432,12 +432,33 @@ impl
.map(payments_grpc::CaptureMethod::foreign_try_from)
.transpose()?;
+ // First try to get authentication_data from the request
let authentication_data = router_data
.request
.authentication_data
.clone()
.map(payments_grpc::AuthenticationData::foreign_try_from)
.transpose()?;
+
+ // If not in request, try to extract from connector_meta (stored during Authorize flow)
+ let authentication_data = if authentication_data.is_none() {
+ router_data
+ .request
+ .connector_meta
+ .as_ref()
+ .and_then(|metadata| metadata.get("authentication_data"))
+ .and_then(|value| {
+ serde_json::from_value::<router_request_types::UcsAuthenticationData>(
+ value.clone(),
+ )
+ .ok()
+ })
+ .map(payments_grpc::AuthenticationData::foreign_try_from)
+ .transpose()?
+ } else {
+ authentication_data
+ };
+
let merchant_account_metadata = router_data
.connector_meta_data
.as_ref()
@@ -490,8 +511,6 @@ impl
.clone()
.map(|e| e.expose().expose().into()),
browser_info,
- locale: None,
-
session_token: router_data.session_token.clone(),
order_tax_amount: None,
customer_name: None,
@@ -537,9 +556,21 @@ impl
enable_partial_authorization: None,
payment_channel: None,
billing_descriptor: None,
- continue_redirection_url: None,
- redirection_response: None,
- threeds_completion_indicator: None,
+ locale: None,
+ continue_redirection_url: router_data.request.complete_authorize_url.clone(),
+ redirection_response: router_data
+ .request
+ .redirect_response
+ .clone()
+ .map(|redirection_response| {
+ payments_grpc::RedirectionResponse::foreign_try_from(redirection_response)
+ })
+ .transpose()?,
+ threeds_completion_indicator: router_data
+ .request
+ .threeds_method_comp_ind
+ .clone()
+ .map(|ind| payments_grpc::ThreeDsCompletionIndicator::foreign_from(ind).into()),
tokenization_strategy: router_data
.request
.tokenization
@@ -819,6 +850,11 @@ impl
})
.transpose()?;
+ let capture_method = router_data
+ .request
+ .capture_method
+ .map(payments_grpc::CaptureMethod::foreign_try_from)
+ .transpose()?;
let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;
let merchant_account_metadata = router_data
.connector_meta_data
@@ -827,6 +863,15 @@ impl
.transpose()
.change_context(UnifiedConnectorServiceError::RequestEncodingFailed)?
.map(|s| s.into());
+
+ // Convert ucs_authentication_data from PreAuthenticate response to gRPC format
+ let authentication_data = router_data
+ .request
+ .authentication_data
+ .clone()
+ .map(payments_grpc::AuthenticationData::foreign_try_from)
+ .transpose()?;
+
Ok(Self {
request_ref_id: Some(Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(
@@ -848,7 +893,7 @@ impl
.map(|e| e.expose().expose().into()),
customer_name: None,
address: Some(address),
- authentication_data: None,
+ authentication_data,
metadata: None,
return_url: None,
continue_redirection_url: router_data.request.complete_authorize_url.clone(),
@@ -869,7 +914,7 @@ impl
.map(payments_grpc::BrowserInformation::foreign_try_from)
.transpose()?,
connector_metadata: None,
- capture_method: None,
+ capture_method: capture_method.map(|capture_method| capture_method.into()),
})
}
}
@@ -990,6 +1035,12 @@ impl
)?,
);
+ let capture_method = router_data
+ .request
+ .capture_method
+ .map(payments_grpc::CaptureMethod::foreign_try_from)
+ .transpose()?;
+
let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;
let merchant_account_metadata = router_data
.connector_meta_data
@@ -1043,7 +1094,7 @@ impl
.map(payments_grpc::BrowserInformation::foreign_try_from)
.transpose()?,
connector_metadata: None,
- capture_method: None,
+ capture_method: capture_method.map(|capture_method| capture_method.into()),
})
}
}
@@ -2186,6 +2237,12 @@ impl
} else {
let status = AttemptStatus::foreign_try_from((response.status(), prev_status))?;
+ let authentication_data = response.authentication_data.and_then(|auth_data| {
+ router_request_types::UcsAuthenticationData::foreign_try_from(auth_data)
+ .ok()
+ .map(Box::new)
+ });
+
Ok((
PaymentsResponseData::TransactionResponse {
resource_id,
@@ -2195,7 +2252,7 @@ impl
network_txn_id: response.network_txn_id.clone(),
connector_response_reference_id,
incremental_authorization_allowed: None,
- authentication_data: None,
+ authentication_data,
charges: None,
},
status,
@@ -3968,6 +4025,18 @@ impl ForeignFrom<common_enums::TransactionStatus> for payments_grpc::Transaction
}
}
+impl ForeignFrom<api_models::payments::ThreeDsCompletionIndicator>
+ for payments_grpc::ThreeDsCompletionIndicator
+{
+ fn foreign_from(value: api_models::payments::ThreeDsCompletionIndicator) -> Self {
+ match value {
+ api_models::payments::ThreeDsCompletionIndicator::Success => Self::Success,
+ api_models::payments::ThreeDsCompletionIndicator::Failure => Self::Failure,
+ api_models::payments::ThreeDsCompletionIndicator::NotAvailable => Self::NotAvailable,
+ }
+ }
+}
+
impl ForeignFrom<common_enums::ExemptionIndicator> for payments_grpc::ExemptionIndicator {
fn foreign_from(value: common_enums::ExemptionIndicator) -> Self {
match value {
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index fb601f5347..a5ba943593 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -1822,6 +1822,12 @@ pub fn get_connector_request_reference_id(
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
connector_name: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
+ // If there's already a connector_request_reference_id stored in the payment_attempt,
+ // reuse it to maintain consistency across multiple connector calls
+ if let Some(existing_reference_id) = &payment_attempt.connector_request_reference_id {
+ return Ok(existing_reference_id.clone());
+ }
+
let is_config_enabled_to_send_payment_id_as_connector_request_id =
is_merchant_enabled_for_payment_id_as_connector_request_id(conf, processor);
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 3b9384eafd..9496c87345 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -1315,6 +1315,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {
metadata: None,
request_extended_authorization: None,
authentication_data: None,
+ ucs_authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
split_payments: None, // TODO: allow charges on mandates?
guest_customer: None,
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index c75b3b5aae..48d967601d 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -53,6 +53,7 @@ impl VerifyConnectorData {
request_extended_authorization: None,
request_incremental_authorization: false,
authentication_data: None,
+ ucs_authentication_data: None,
customer_acceptance: None,
split_payments: None,
guest_customer: None,
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index bfa23f4d57..283024e271 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -998,6 +998,7 @@ impl Default for PaymentAuthorizeType {
request_extended_authorization: None,
metadata: None,
authentication_data: None,
+ ucs_authentication_data: None,
customer_acceptance: None,
split_payments: None,
guest_customer: None,