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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(authentication): added authentication sync api (#8596)
Sahkal Poddar794dce168e6b
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 4dfec0daef..3a84df8141 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -7081,19 +7081,19 @@"AcquirerDetails": {"type": "object","properties": {- "bin": {+ "acquirer_bin": {"type": "string","description": "The bin of the card.","example": "123456","nullable": true},- "merchant_id": {+ "acquirer_merchant_id": {"type": "string","description": "The merchant id of the card.","example": "merchant_abc","nullable": true},- "country_code": {+ "merchant_country_code": {"type": "string","description": "The country code of the card.","example": "US/34456",@@ -7884,8 +7884,7 @@"type": "object","required": ["amount",- "currency",- "profile_acquirer_id"+ "currency"],"properties": {"authentication_id": {@@ -7927,14 +7926,6 @@"example": "https://example.com/redirect","nullable": true},- "acquirer_details": {- "allOf": [- {- "$ref": "#/components/schemas/AcquirerDetails"- }- ],- "nullable": true- },"force_3ds_challenge": {"type": "boolean","description": "Force 3DS challenge.",@@ -7950,7 +7941,16 @@},"profile_acquirer_id": {"type": "string",- "description": "Profile Acquirer ID get from profile acquirer configuration"+ "description": "Profile Acquirer ID get from profile acquirer configuration",+ "nullable": true+ },+ "acquirer_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AcquirerDetails"+ }+ ],+ "nullable": true}}},@@ -8090,6 +8090,14 @@"type": "string","description": "Email","nullable": true+ },+ "acquirer_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AcquirerDetails"+ }+ ],+ "nullable": true}}},@@ -8100,8 +8108,7 @@"merchant_id","status","amount",- "currency",- "profile_acquirer_id"+ "currency"],"properties": {"authentication_id": {@@ -8187,7 +8194,8 @@},"profile_acquirer_id": {"type": "string",- "description": "Profile Acquirer ID get from profile acquirer configuration"+ "description": "Profile Acquirer ID get from profile acquirer configuration",+ "nullable": true}}},@@ -8200,6 +8208,235 @@"failed"]},+ "AuthenticationSyncRequest": {+ "type": "object",+ "required": [+ "client_secret"+ ],+ "properties": {+ "client_secret": {+ "type": "string",+ "description": "The client secret for this authentication."+ }+ }+ },+ "AuthenticationSyncResponse": {+ "type": "object",+ "required": [+ "authentication_id",+ "merchant_id",+ "status",+ "amount",+ "currency",+ "created_at",+ "profile_id"+ ],+ "properties": {+ "authentication_id": {+ "type": "string",+ "description": "The unique identifier for this authentication.",+ "example": "auth_mbabizu24mvu3mela5njyhpit4"+ },+ "merchant_id": {+ "type": "string",+ "description": "This is an identifier for the merchant account.",+ "example": "merchant_abc"+ },+ "status": {+ "$ref": "#/components/schemas/AuthenticationStatus"+ },+ "client_secret": {+ "type": "string",+ "description": "The client secret for this authentication.",+ "nullable": true+ },+ "amount": {+ "$ref": "#/components/schemas/MinorUnit"+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ },+ "authentication_connector": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AuthenticationConnectors"+ }+ ],+ "nullable": true+ },+ "force_3ds_challenge": {+ "type": "boolean",+ "description": "Whether 3DS challenge was forced.",+ "nullable": true+ },+ "return_url": {+ "type": "string",+ "description": "The URL to which the user should be redirected after authentication.",+ "nullable": true+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "example": "2022-09-10T10:11:12Z"+ },+ "profile_id": {+ "type": "string",+ "description": "The business profile that is associated with this authentication."+ },+ "psd2_sca_exemption_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/ScaExemptionType"+ }+ ],+ "nullable": true+ },+ "acquirer_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AcquirerDetails"+ }+ ],+ "nullable": true+ },+ "threeds_server_transaction_id": {+ "type": "string",+ "description": "The unique identifier from the 3DS server.",+ "nullable": true+ },+ "maximum_supported_3ds_version": {+ "type": "string",+ "description": "The maximum supported 3DS version.",+ "nullable": true+ },+ "connector_authentication_id": {+ "type": "string",+ "description": "The unique identifier from the connector.",+ "nullable": true+ },+ "three_ds_method_data": {+ "type": "string",+ "description": "The data required to perform the 3DS method.",+ "nullable": true+ },+ "three_ds_method_url": {+ "type": "string",+ "description": "The URL for the 3DS method.",+ "nullable": true+ },+ "message_version": {+ "type": "string",+ "description": "The version of the message.",+ "nullable": true+ },+ "connector_metadata": {+ "description": "The metadata for this authentication.",+ "nullable": true+ },+ "directory_server_id": {+ "type": "string",+ "description": "The unique identifier for the directory server.",+ "nullable": true+ },+ "billing": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Address"+ }+ ],+ "nullable": true+ },+ "shipping": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Address"+ }+ ],+ "nullable": true+ },+ "browser_information": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BrowserInformation"+ }+ ],+ "nullable": true+ },+ "email": {+ "type": "string",+ "description": "Email.",+ "nullable": true+ },+ "trans_status": {+ "allOf": [+ {+ "$ref": "#/components/schemas/TransactionStatus"+ }+ ],+ "nullable": true+ },+ "acs_url": {+ "type": "string",+ "description": "Access Server URL for challenge submission.",+ "nullable": true+ },+ "challenge_request": {+ "type": "string",+ "description": "Challenge request to be sent to acs_url.",+ "nullable": true+ },+ "acs_reference_number": {+ "type": "string",+ "description": "Unique identifier assigned by EMVCo.",+ "nullable": true+ },+ "acs_trans_id": {+ "type": "string",+ "description": "Unique identifier assigned by the ACS.",+ "nullable": true+ },+ "acs_signed_content": {+ "type": "string",+ "description": "JWS object created by the ACS for the ARes message.",+ "nullable": true+ },+ "three_ds_requestor_url": {+ "type": "string",+ "description": "Three DS Requestor URL.",+ "nullable": true+ },+ "three_ds_requestor_app_url": {+ "type": "string",+ "description": "Merchant app URL for OOB authentication.",+ "nullable": true+ },+ "authentication_value": {+ "type": "string",+ "description": "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.",+ "nullable": true+ },+ "eci": {+ "type": "string",+ "description": "ECI value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.",+ "nullable": true+ },+ "error_message": {+ "type": "string",+ "description": "Error message if any.",+ "nullable": true+ },+ "error_code": {+ "type": "string",+ "description": "Error code if any.",+ "nullable": true+ },+ "profile_acquirer_id": {+ "type": "string",+ "description": "Profile Acquirer ID",+ "nullable": true+ }+ }+ },"AuthenticationType": {"type": "string","description": "Specifies the type of cardholder authentication to be applied for a payment.\n\n- `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer.\n- `NoThreeDs`: Indicates that 3D Secure authentication should not be performed. The liability for chargebacks typically remains with the merchant. This is often the default if not specified.\n\nNote: The actual authentication behavior can also be influenced by merchant configuration and specific connector defaults. Some connectors might still enforce 3DS or bypass it regardless of this parameter.",diff --git a/crates/api_models/src/authentication.rs b/crates/api_models/src/authentication.rsindex 514de8e011..6704920c4d 100644--- a/crates/api_models/src/authentication.rs+++ b/crates/api_models/src/authentication.rs@@ -45,10 +45,6 @@ pub struct AuthenticationCreateRequest {#[schema(value_type = Option<String>, example = "https://example.com/redirect")]pub return_url: Option<String>,- /// Acquirer details information- #[schema(value_type = Option<AcquirerDetails>)]- pub acquirer_details: Option<AcquirerDetails>,-/// Force 3DS challenge.#[serde(default)]pub force_3ds_challenge: Option<bool>,@@ -58,21 +54,25 @@ pub struct AuthenticationCreateRequest {pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,/// Profile Acquirer ID get from profile acquirer configuration- #[schema(value_type = String)]- pub profile_acquirer_id: id_type::ProfileAcquirerId,+ #[schema(value_type = Option<String>)]+ pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,++ /// Acquirer details information+ #[schema(value_type = Option<AcquirerDetails>)]+ pub acquirer_details: Option<AcquirerDetails>,}#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct AcquirerDetails {/// The bin of the card.#[schema(value_type = Option<String>, example = "123456")]- pub bin: Option<String>,+ pub acquirer_bin: Option<String>,/// The merchant id of the card.#[schema(value_type = Option<String>, example = "merchant_abc")]- pub merchant_id: Option<String>,+ pub acquirer_merchant_id: Option<String>,/// The country code of the card.#[schema(value_type = Option<String>, example = "US/34456")]- pub country_code: Option<String>,+ pub merchant_country_code: Option<String>,}#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]@@ -136,8 +136,8 @@ pub struct AuthenticationResponse {pub acquirer_details: Option<AcquirerDetails>,/// Profile Acquirer ID get from profile acquirer configuration- #[schema(value_type = String)]- pub profile_acquirer_id: id_type::ProfileAcquirerId,+ #[schema(value_type = Option<String>)]+ pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,}impl ApiEventMetric for AuthenticationCreateRequest {@@ -271,6 +271,9 @@ pub struct AuthenticationEligibilityResponse {#[schema(value_type = Option<String>)]pub email: common_utils::crypto::OptionalEncryptableEmail,+ /// Acquirer details information.+ #[schema(value_type = Option<AcquirerDetails>)]+ pub acquirer_details: Option<AcquirerDetails>,}#[derive(Debug, Serialize, ToSchema)]@@ -385,17 +388,26 @@ pub struct AuthenticationAuthenticateResponse {/// 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<masking::Secret<String>>,- /// ECI indicator of the card, only available in case of server to server request. Unavailable in case of client request due to security concern.- pub eci: Option<String>,+/// The current status of the authentication (e.g., Started).#[schema(value_type = AuthenticationStatus)]pub status: common_enums::AuthenticationStatus,+/// The connector to be used for authentication, if known.#[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")]pub authentication_connector: Option<AuthenticationConnectors>,+/// The unique identifier for this authentication.- #[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]+ #[schema(value_type = AuthenticationId, example = "auth_mbabizu24mvu3mela5njyhpit4")]pub authentication_id: id_type::AuthenticationId,++ /// The ECI value for this authentication.+ #[schema(value_type = String)]+ pub eci: Option<String>,++ /// Acquirer details information.+ #[schema(value_type = Option<AcquirerDetails>)]+ pub acquirer_details: Option<AcquirerDetails>,}impl ApiEventMetric for AuthenticationAuthenticateResponse {@@ -405,3 +417,194 @@ impl ApiEventMetric for AuthenticationAuthenticateResponse {})}}++#[cfg(feature = "v1")]+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct AuthenticationSyncResponse {+ // Core Authentication Fields (from AuthenticationResponse)+ /// The unique identifier for this authentication.+ #[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]+ pub authentication_id: id_type::AuthenticationId,++ /// This is an identifier for the merchant account.+ #[schema(value_type = String, example = "merchant_abc")]+ pub merchant_id: id_type::MerchantId,++ /// The current status of the authentication.+ #[schema(value_type = AuthenticationStatus)]+ pub status: common_enums::AuthenticationStatus,++ /// The client secret for this authentication.+ #[schema(value_type = Option<String>)]+ pub client_secret: Option<masking::Secret<String>>,++ /// The amount for the transaction.+ #[schema(value_type = MinorUnit, example = 1000)]+ pub amount: common_utils::types::MinorUnit,++ /// The currency for the transaction.+ #[schema(value_type = Currency)]+ pub currency: enums::Currency,++ /// The connector used for authentication.+ #[schema(value_type = Option<AuthenticationConnectors>)]+ pub authentication_connector: Option<AuthenticationConnectors>,++ /// Whether 3DS challenge was forced.+ pub force_3ds_challenge: Option<bool>,++ /// The URL to which the user should be redirected after authentication.+ pub return_url: Option<String>,++ #[schema(example = "2022-09-10T10:11:12Z")]+ #[serde(with = "common_utils::custom_serde::iso8601")]+ pub created_at: PrimitiveDateTime,++ /// The business profile that is associated with this authentication.+ #[schema(value_type = String)]+ pub profile_id: id_type::ProfileId,++ /// SCA exemption type for this authentication.+ #[schema(value_type = Option<ScaExemptionType>)]+ pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,++ /// Acquirer details information.+ #[schema(value_type = Option<AcquirerDetails>)]+ pub acquirer_details: Option<AcquirerDetails>,++ /// The unique identifier from the 3DS server.+ #[schema(value_type = Option<String>)]+ pub threeds_server_transaction_id: Option<String>,++ /// The maximum supported 3DS version.+ #[schema(value_type = Option<String>)]+ pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>,++ /// The unique identifier from the connector.+ #[schema(value_type = Option<String>)]+ pub connector_authentication_id: Option<String>,++ /// The data required to perform the 3DS method.+ #[schema(value_type = Option<String>)]+ pub three_ds_method_data: Option<String>,++ /// The URL for the 3DS method.+ #[schema(value_type = Option<String>)]+ pub three_ds_method_url: Option<String>,++ /// The version of the message.+ #[schema(value_type = Option<String>)]+ pub message_version: Option<common_utils::types::SemanticVersion>,++ /// The metadata for this authentication.+ #[schema(value_type = Option<serde_json::Value>)]+ pub connector_metadata: Option<serde_json::Value>,++ /// The unique identifier for the directory server.+ #[schema(value_type = Option<String>)]+ pub directory_server_id: Option<String>,++ /// Billing address.+ #[schema(value_type = Option<Address>)]+ pub billing: Option<Address>,++ /// Shipping address.+ #[schema(value_type = Option<Address>)]+ pub shipping: Option<Address>,++ /// Browser information.+ #[schema(value_type = Option<BrowserInformation>)]+ pub browser_information: Option<BrowserInformation>,++ /// Email.+ #[schema(value_type = Option<String>)]+ pub email: common_utils::crypto::OptionalEncryptableEmail,++ /// Indicates the transaction status.+ #[serde(rename = "trans_status")]+ #[schema(value_type = Option<TransactionStatus>)]+ pub transaction_status: Option<common_enums::TransactionStatus>,++ /// Access Server URL for challenge submission.+ pub acs_url: Option<String>,++ /// Challenge request to be sent to acs_url.+ pub challenge_request: Option<String>,++ /// Unique identifier assigned by EMVCo.+ pub acs_reference_number: Option<String>,++ /// Unique identifier assigned by the ACS.+ pub acs_trans_id: Option<String>,++ /// JWS object created by the ACS for the ARes message.+ pub acs_signed_content: Option<String>,++ /// Three DS Requestor URL.+ pub three_ds_requestor_url: Option<String>,++ /// Merchant app URL for OOB authentication.+ pub three_ds_requestor_app_url: 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 = Option<String>)]+ pub authentication_value: Option<masking::Secret<String>>,++ /// ECI value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.+ pub eci: Option<String>,++ // Common Error Fields (present in multiple responses)+ /// Error message if any.+ #[schema(value_type = Option<String>)]+ pub error_message: Option<String>,++ /// Error code if any.+ #[schema(value_type = Option<String>)]+ pub error_code: Option<String>,++ /// Profile Acquirer ID+ #[schema(value_type = Option<String>)]+ pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,+}++#[cfg(feature = "v1")]+impl ApiEventMetric for AuthenticationSyncResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Authentication {+ authentication_id: self.authentication_id.clone(),+ })+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct AuthenticationSyncRequest {+ /// The client secret for this authentication.+ #[schema(value_type = String)]+ pub client_secret: Option<masking::Secret<String>>,+ /// Authentication ID for the authentication+ #[serde(skip_deserializing)]+ pub authentication_id: id_type::AuthenticationId,+}++impl ApiEventMetric for AuthenticationSyncRequest {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Authentication {+ authentication_id: self.authentication_id.clone(),+ })+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct AuthenticationSyncPostUpdateRequest {+ /// Authentication ID for the authentication+ #[serde(skip_deserializing)]+ pub authentication_id: id_type::AuthenticationId,+}++impl ApiEventMetric for AuthenticationSyncPostUpdateRequest {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Authentication {+ authentication_id: self.authentication_id.clone(),+ })+ }+}diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 423677ead9..4daa373c01 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -7508,6 +7508,15 @@ pub enum TransactionStatus {InformationOnly,}+impl TransactionStatus {+ pub fn is_pending(self) -> bool {+ matches!(+ self,+ Self::ChallengeRequired | Self::ChallengeRequiredDecoupledAuthentication+ )+ }+}+#[derive(Clone,Copy,diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsindex 625f626268..933106f2bf 100644--- a/crates/common_types/src/payments.rs+++ b/crates/common_types/src/payments.rs@@ -123,6 +123,10 @@ impl MerchantCountryCode {}).attach_printable_lazy(|| format!("Invalid country code {code}"))}+ /// Creates a new `MerchantCountryCode` instance from a string.+ pub fn new(country_code: String) -> Self {+ Self(country_code)+ }}impl diesel::serialize::ToSql<Text, diesel::pg::Pg> for MerchantCountryCode {diff --git a/crates/common_utils/src/id_type/authentication.rs b/crates/common_utils/src/id_type/authentication.rsindex 68a62a5681..257331d799 100644--- a/crates/common_utils/src/id_type/authentication.rs+++ b/crates/common_utils/src/id_type/authentication.rs@@ -17,6 +17,11 @@ impl AuthenticationId {pub fn generate_authentication_id(prefix: &'static str) -> Self {Self(crate::generate_ref_id_with_default_length(prefix))}++ /// Get external authentication request poll id+ pub fn get_external_authentication_request_poll_id(&self) -> String {+ format!("external_authentication_{}", self.get_string_repr())+ }}impl crate::events::ApiEventMetric for AuthenticationId {diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rsindex 1894d51298..3837daae67 100644--- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs@@ -1,8 +1,7 @@use common_enums::{enums, MerchantCategoryCode};use common_types::payments::MerchantCountryCode;-use common_utils::types::FloatMajorUnit;+use common_utils::{ext_traits::OptionExt as _, types::FloatMajorUnit};use hyperswitch_domain_models::{- ext_traits::OptionExt,router_data::{ConnectorAuthType, RouterData},router_request_types::{authentication::{AuthNFlowType, ChallengeParams},@@ -114,8 +113,9 @@ pub struct PaymentDetails {pub card_expiry_month: Secret<String>,pub card_expiry_year: Secret<String>,pub cardholder_name: Option<Secret<String>>,- pub card_token_number: Secret<String>,+ pub card_token_number: Option<Secret<String>>,pub account_type: Option<common_enums::PaymentMethodType>,+ pub card_cvc: Option<Secret<String>>,}#[derive(Default, Clone, Debug, Serialize, Deserialize)]@@ -197,6 +197,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>,}#[derive(Default, Clone, Debug, Serialize, PartialEq, Deserialize)]@@ -363,8 +364,8 @@ impl<F, T>.and_then(|three_ds_eligibility_response| {three_ds_eligibility_response.three_ds_method_data_form- .three_ds_method_data- .clone()+ .as_ref()+ .and_then(|form| form.three_ds_method_data.clone())});let three_ds_method_url = max_acs_protocol_version.and_then(|acs_protocol_version| acs_protocol_version.three_ds_method_url);@@ -406,8 +407,9 @@ pub struct UnifiedAuthenticationServicePostAuthenticateResponse {#[derive(Serialize, Deserialize, Debug, Clone)]pub struct AuthenticationDetails {pub eci: Option<String>,- pub token_details: UasTokenDetails,+ pub token_details: Option<UasTokenDetails>,pub dynamic_data_details: Option<UasDynamicData>,+ pub trans_status: Option<common_enums::TransactionStatus>,}#[derive(Serialize, Deserialize, Debug, Clone)]@@ -465,28 +467,14 @@ impl<F, T>response: Ok(UasAuthenticationResponseData::PostAuthentication {authentication_details: PostAuthenticationDetails {eci: item.response.authentication_details.eci,- token_details: Some(TokenDetails {- payment_token: item- .response- .authentication_details- .token_details- .payment_token,- payment_account_reference: item- .response- .authentication_details- .token_details- .payment_account_reference,- token_expiration_month: item- .response- .authentication_details- .token_details- .token_expiration_month,- token_expiration_year: item- .response- .authentication_details- .token_details- .token_expiration_year,- }),+ token_details: item.response.authentication_details.token_details.map(+ |token_details| TokenDetails {+ payment_token: token_details.payment_token,+ payment_account_reference: token_details.payment_account_reference,+ token_expiration_month: token_details.token_expiration_month,+ token_expiration_year: token_details.token_expiration_year,+ },+ ),dynamic_data_details: item.response.authentication_details@@ -496,7 +484,7 @@ impl<F, T>dynamic_data_type: dynamic_data.dynamic_data_type,ds_trans_id: dynamic_data.ds_trans_id,}),- trans_status: None,+ trans_status: item.response.authentication_details.trans_status,},}),..item.data@@ -549,6 +537,7 @@ impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasAuthenticationConfirmat}}+// ThreeDs requestimpl TryFrom<&UasPreAuthenticationRouterData>for UnifiedAuthenticationServicePreAuthenticateRequest{@@ -578,6 +567,7 @@ impl TryFrom<&UasPreAuthenticationRouterData>three_ds_requestor_id: merchant_data.three_ds_requestor_id,three_ds_requestor_name: merchant_data.three_ds_requestor_name,configuration_id: None,+ notification_url: merchant_data.notification_url,};let acquirer = Acquirer {@@ -643,6 +633,7 @@ impl TryFrom<&UasPreAuthenticationRouterData>account_type: details.account_type,card_expiry_month: details.card_expiry_month,card_expiry_year: details.card_expiry_year,+ card_cvc: details.card_cvc,}),auth_creds: auth_type,transaction_details: None,@@ -662,6 +653,7 @@ pub enum UnifiedAuthenticationServiceAuthType {certificate: Secret<String>,private_key: Secret<String>,},+ NoKey,}impl TryFrom<&ConnectorAuthType> for UnifiedAuthenticationServiceAuthType {@@ -678,6 +670,7 @@ impl TryFrom<&ConnectorAuthType> for UnifiedAuthenticationServiceAuthType {certificate: certificate.clone(),private_key: private_key.clone(),}),+ ConnectorAuthType::NoKey => Ok(Self::NoKey),_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),}}@@ -737,7 +730,7 @@ pub struct ThreeDsEligibilityResponse {pub scheme_id: Option<String>,pub acs_protocol_versions: Option<Vec<AcsProtocolVersion>>,pub ds_protocol_versions: Option<Vec<String>>,- pub three_ds_method_data_form: ThreeDsMethodDataForm,+ pub three_ds_method_data_form: Option<ThreeDsMethodDataForm>,pub three_ds_method_data: Option<ThreeDsMethodData>,pub error_details: Option<String>,pub is_card_found_in_2x_ranges: bool,diff --git a/crates/hyperswitch_domain_models/src/authentication.rs b/crates/hyperswitch_domain_models/src/authentication.rsindex ef8cf2f237..5ec6f93c14 100644--- a/crates/hyperswitch_domain_models/src/authentication.rs+++ b/crates/hyperswitch_domain_models/src/authentication.rs@@ -62,3 +62,12 @@ pub struct Authentication {pub browser_info: Option<Value>,pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,}++#[derive(Debug, Clone, serde::Serialize)]+pub struct PgRedirectResponseForAuthentication {+ pub authentication_id: common_utils::id_type::AuthenticationId,+ pub status: common_enums::TransactionStatus,+ pub gateway_id: String,+ pub customer_id: Option<common_utils::id_type::CustomerId>,+ pub amount: Option<common_utils::types::MinorUnit>,+}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.rsindex e5fa975534..f37af7fa6d 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,6 +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>,}#[derive(Clone, Debug, PartialEq, serde::Serialize)]@@ -68,8 +69,9 @@ pub struct PaymentDetails {pub card_expiry_month: Secret<String>,pub card_expiry_year: Secret<String>,pub cardholder_name: Option<Secret<String>>,- pub card_token_number: Secret<String>,+ pub card_token_number: Option<Secret<String>>,pub account_type: Option<common_enums::PaymentMethodType>,+ pub card_cvc: Option<Secret<String>>,}#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex d9f525f39f..efa92af978 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -812,6 +812,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::authentication::ThreeDsData,api_models::authentication::AuthenticationEligibilityRequest,api_models::authentication::AuthenticationEligibilityResponse,+ api_models::authentication::AuthenticationSyncRequest,+ api_models::authentication::AuthenticationSyncResponse,api_models::open_router::OpenRouterDecideGatewayRequest,api_models::open_router::DecideGatewayResponse,api_models::open_router::UpdateScorePayload,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex e5f7384708..458fe4bc5b 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -3121,6 +3121,107 @@ pub fn get_handle_response_url(make_url_with_signature(&return_url, business_profile)}+#[cfg(feature = "v1")]+pub fn get_handle_response_url_for_modular_authentication(+ authentication_id: id_type::AuthenticationId,+ business_profile: &domain::Profile,+ response: &api_models::authentication::AuthenticationAuthenticateResponse,+ connector: String,+ return_url: Option<String>,+ client_secret: Option<&masking::Secret<String>>,+ amount: Option<MinorUnit>,+) -> RouterResult<api::RedirectionResponse> {+ let authentication_return_url = return_url;+ let trans_status = response+ .transaction_status+ .clone()+ .get_required_value("transaction_status")?;++ let redirection_response = make_pg_redirect_response_for_authentication(+ authentication_id,+ connector,+ amount,+ trans_status,+ );++ let return_url = make_merchant_url_with_response_for_authentication(+ business_profile,+ redirection_response,+ authentication_return_url.as_ref(),+ client_secret,+ None,+ )+ .attach_printable("Failed to make merchant url with response")?;++ make_url_with_signature(&return_url, business_profile)+}++#[cfg(feature = "v1")]+pub fn make_merchant_url_with_response_for_authentication(+ business_profile: &domain::Profile,+ redirection_response: hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication,+ request_return_url: Option<&String>,+ client_secret: Option<&masking::Secret<String>>,+ manual_retry_allowed: Option<bool>,+) -> RouterResult<String> {+ // take return url if provided in the request else use merchant return url+ let url = request_return_url+ .or(business_profile.return_url.as_ref())+ .get_required_value("return_url")?;++ let status_check = redirection_response.status;++ let authentication_client_secret = client_secret+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Expected client secret to be `Some`")?;++ let authentication_id = redirection_response+ .authentication_id+ .get_string_repr()+ .to_owned();+ let merchant_url_with_response = if business_profile.redirect_to_merchant_with_http_post {+ url::Url::parse_with_params(+ url,+ &[+ ("status", status_check.to_string()),+ ("authentication_id", authentication_id),+ (+ "authentication_client_secret",+ authentication_client_secret.peek().to_string(),+ ),+ (+ "manual_retry_allowed",+ manual_retry_allowed.unwrap_or(false).to_string(),+ ),+ ],+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to parse the url with param")?+ } else {+ let amount = redirection_response.amount.get_required_value("amount")?;+ url::Url::parse_with_params(+ url,+ &[+ ("status", status_check.to_string()),+ ("authentication_id", authentication_id),+ (+ "authentication_client_secret",+ authentication_client_secret.peek().to_string(),+ ),+ ("amount", amount.to_string()),+ (+ "manual_retry_allowed",+ manual_retry_allowed.unwrap_or(false).to_string(),+ ),+ ],+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to parse the url with param")?+ };++ Ok(merchant_url_with_response.to_string())+}+#[cfg(feature = "v1")]pub fn make_merchant_url_with_response(business_profile: &domain::Profile,@@ -3329,6 +3430,22 @@ pub fn make_pg_redirect_response(}}+#[cfg(feature = "v1")]+pub fn make_pg_redirect_response_for_authentication(+ authentication_id: id_type::AuthenticationId,+ connector: String,+ amount: Option<MinorUnit>,+ trans_status: common_enums::TransactionStatus,+) -> hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication {+ hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication {+ authentication_id,+ status: trans_status,+ gateway_id: connector,+ customer_id: None,+ amount,+ }+}+#[cfg(feature = "v1")]pub fn make_url_with_signature(redirect_url: &str,diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rsindex 486ad02728..91d56f4de1 100644--- a/crates/router/src/core/unified_authentication_service.rs+++ b/crates/router/src/core/unified_authentication_service.rs@@ -5,6 +5,7 @@ pub mod utils;#[cfg(feature = "v1")]use api_models::authentication::{AuthenticationEligibilityRequest, AuthenticationEligibilityResponse,+ AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest, AuthenticationSyncResponse,};use api_models::{authentication::{@@ -57,7 +58,6 @@ use crate::{services::AuthFlow,types::{domain::types::AsyncLift, transformers::ForeignTryFrom},};-#[cfg(feature = "v1")]#[async_trait::async_trait]impl UnifiedAuthenticationService for ClickToPay {@@ -303,8 +303,9 @@ impl UnifiedAuthenticationService for ExternalAuthentication {card_expiry_month: card.card_exp_month.clone(),card_expiry_year: card.card_exp_year.clone(),cardholder_name: card.card_holder_name.clone(),- card_token_number: card.card_cvc.clone(),+ card_token_number: None,account_type: None,+ card_cvc: Some(card.card_cvc.clone()),})} else {None@@ -497,7 +498,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {payment_id: Option<&common_utils::id_type::PaymentId>,merchant_connector_account: &MerchantConnectorAccountType,connector_name: &str,- _authentication_id: &common_utils::id_type::AuthenticationId,+ authentication_id: &common_utils::id_type::AuthenticationId,payment_method: common_enums::PaymentMethod,_merchant_id: &common_utils::id_type::MerchantId,authentication: Option<&Authentication>,@@ -514,7 +515,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {None,authentication_data,merchant_connector_account,- authentication.map(|auth| auth.authentication_id.clone()),+ Some(authentication_id.clone()),payment_id.cloned(),)?;@@ -663,6 +664,39 @@ pub async fn authentication_create_core(.unwrap_or(business_profile.force_3ds_challenge),);+ // Priority logic: First check req.acquirer_details, then fallback to profile_acquirer_id lookup+ let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) =+ if let Some(acquirer_details) = &req.acquirer_details {+ // Priority 1: Use acquirer_details from request if present+ (+ acquirer_details.acquirer_bin.clone(),+ acquirer_details.acquirer_merchant_id.clone(),+ acquirer_details.merchant_country_code.clone(),+ )+ } else {+ // Priority 2: Fallback to profile_acquirer_id lookup+ let acquirer_details = req.profile_acquirer_id.clone().and_then(|acquirer_id| {+ business_profile+ .acquirer_config_map+ .and_then(|acquirer_config_map| {+ acquirer_config_map.0.get(&acquirer_id).cloned()+ })+ });++ acquirer_details+ .as_ref()+ .map(|details| {+ (+ Some(details.acquirer_bin.clone()),+ Some(details.acquirer_assigned_merchant_id.clone()),+ business_profile+ .merchant_country_code+ .map(|code| code.get_country_code().to_owned()),+ )+ })+ .unwrap_or((None, None, None))+ };+let new_authentication = create_new_authentication(&state,merchant_id.clone(),@@ -678,26 +712,20 @@ pub async fn authentication_create_core(organization_id,force_3ds_challenge,req.psd2_sca_exemption_type,- req.acquirer_details- .clone()- .and_then(|acquirer_details| acquirer_details.bin),- req.acquirer_details- .clone()- .and_then(|acquirer_details| acquirer_details.merchant_id),- req.acquirer_details- .clone()- .and_then(|acquirer_details| acquirer_details.country_code),+ acquirer_bin,+ acquirer_merchant_id,+ acquirer_country_code,Some(req.amount),Some(req.currency),req.return_url,- Some(req.profile_acquirer_id),+ req.profile_acquirer_id.clone(),).await?;let acquirer_details = Some(AcquirerDetails {- bin: new_authentication.acquirer_bin.clone(),- merchant_id: new_authentication.acquirer_merchant_id.clone(),- country_code: new_authentication.acquirer_country_code.clone(),+ acquirer_bin: new_authentication.acquirer_bin.clone(),+ acquirer_merchant_id: new_authentication.acquirer_merchant_id.clone(),+ merchant_country_code: new_authentication.acquirer_country_code.clone(),});let amount = new_authentication@@ -709,19 +737,13 @@ pub async fn authentication_create_core(.ok_or(ApiErrorResponse::InternalServerError).attach_printable("currency failed to get currency from authentication table")?;- let profile_acquirer_id = new_authentication- .profile_acquirer_id- .clone()- .ok_or(ApiErrorResponse::InternalServerError)- .attach_printable("failed to get profile_acquirer_id from authentication table")?;-let response = AuthenticationResponse::foreign_try_from((- new_authentication,+ new_authentication.clone(),amount,currency,profile_id,acquirer_details,- profile_acquirer_id,+ new_authentication.profile_acquirer_id,))?;Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(@@ -736,7 +758,7 @@ implcommon_enums::Currency,common_utils::id_type::ProfileId,Option<AcquirerDetails>,- common_utils::id_type::ProfileAcquirerId,+ Option<common_utils::id_type::ProfileAcquirerId>,)> for AuthenticationResponse{type Error = error_stack::Report<ApiErrorResponse>;@@ -747,7 +769,7 @@ implcommon_enums::Currency,common_utils::id_type::ProfileId,Option<AcquirerDetails>,- common_utils::id_type::ProfileAcquirerId,+ Option<common_utils::id_type::ProfileAcquirerId>,),) -> Result<Self, Self::Error> {let authentication_connector = authentication@@ -826,6 +848,11 @@ implmessage_version: authentication.message_version,directory_server_id: authentication.directory_server_id,});+ let acquirer_details = AcquirerDetails {+ acquirer_bin: authentication.acquirer_bin,+ acquirer_merchant_id: authentication.acquirer_merchant_id,+ merchant_country_code: authentication.acquirer_country_code,+ };Ok(Self {authentication_id: authentication.authentication_id,next_action,@@ -841,6 +868,7 @@ implauthentication_connector,browser_information,email,+ acquirer_details: Some(acquirer_details),})}}@@ -904,6 +932,27 @@ pub async fn authentication_eligibility_core().await?;+ let notification_url = match authentication_connector {+ common_enums::AuthenticationConnectors::Juspaythreedsserver => {+ Some(url::Url::parse(&format!(+ "{base_url}/{merchant_id}/{authentication_id}/sync",+ base_url = state.base_url,+ merchant_id = merchant_id.get_string_repr(),+ authentication_id = authentication_id.get_string_repr()+ )))+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse notification url")?+ }+ _ => authentication+ .return_url+ .as_ref()+ .map(|url| url::Url::parse(url))+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse return url")?,+ };+let authentication_connector_name = authentication_connector.to_string();let payment_method_data = domain::PaymentMethodData::from(req.payment_method_data.clone());@@ -932,9 +981,7 @@ pub async fn authentication_eligibility_core(.transpose().change_context(ApiErrorResponse::InternalServerError)?;- let merchant_country_code = business_profile.merchant_country_code.or(metadata- .clone()- .and_then(|metadata| metadata.merchant_country_code.clone()));+ let merchant_country_code = authentication.acquirer_country_code.clone();let merchant_details = Some(hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails {merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()),@@ -944,7 +991,8 @@ pub async fn authentication_eligibility_core(three_ds_requestor_url: business_profile.authentication_connector_details.map(|details| details.three_ds_requestor_url),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: merchant_country_code.map(common_types::payments::MerchantCountryCode::new),+ notification_url,});let domain_address = req@@ -967,8 +1015,8 @@ pub async fn authentication_eligibility_core(None,merchant_details.as_ref(),domain_address.as_ref(),- acquirer_details.clone().map(|detail| detail.acquirer_bin),- acquirer_details.map(|detail| detail.acquirer_assigned_merchant_id),+ authentication.acquirer_bin.clone(),+ authentication.acquirer_merchant_id.clone(),).await?;@@ -1295,6 +1343,11 @@ impl.transpose().change_context(ApiErrorResponse::InternalServerError).attach_printable("Unable to parse the url with param")?;+ let acquirer_details = AcquirerDetails {+ acquirer_bin: authentication.acquirer_bin.clone(),+ acquirer_merchant_id: authentication.acquirer_merchant_id.clone(),+ merchant_country_code: authentication.acquirer_country_code.clone(),+ };Ok(Self {transaction_status: authentication.trans_status.clone(),acs_url,@@ -1312,6 +1365,365 @@ implauthentication_connector,eci,authentication_id: authentication.authentication_id.clone(),+ acquirer_details: Some(acquirer_details),})}}++#[cfg(feature = "v1")]+pub async fn authentication_sync_core(+ state: SessionState,+ merchant_context: domain::MerchantContext,+ auth_flow: AuthFlow,+ req: AuthenticationSyncRequest,+) -> RouterResponse<AuthenticationSyncResponse> {+ let authentication_id = req.authentication_id;+ let merchant_account = merchant_context.get_merchant_account();+ let merchant_id = merchant_account.get_id();+ let db = &*state.store;+ let authentication = db+ .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)+ .await+ .to_not_found_response(ApiErrorResponse::AuthenticationNotFound {+ id: authentication_id.get_string_repr().to_owned(),+ })?;++ req.client_secret+ .map(|client_secret| {+ utils::authenticate_authentication_client_secret_and_check_expiry(+ client_secret.peek(),+ &authentication,+ )+ })+ .transpose()?;++ let key_manager_state = (&state).into();++ let profile_id = authentication.profile_id.clone();++ let business_profile = db+ .find_business_profile_by_profile_id(+ &key_manager_state,+ merchant_context.get_merchant_key_store(),+ &profile_id,+ )+ .await+ .to_not_found_response(ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;++ let (authentication_value, eci) = match auth_flow {+ AuthFlow::Client => (None, None),+ AuthFlow::Merchant => {+ if let Some(common_enums::TransactionStatus::Success) = authentication.trans_status {+ let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data(+ &state,+ authentication_id.get_string_repr(),+ false,+ merchant_context.get_merchant_key_store().key.get_inner(),+ )+ .await+ .inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err))+ .attach_printable("cavv not present after authentication status is success")?;+ (+ Some(masking::Secret::new(tokenised_data.value1)),+ authentication.eci.clone(),+ )+ } else {+ (None, None)+ }+ }+ };++ let (authentication_connector, three_ds_connector_account) =+ auth_utils::get_authentication_connector_data(+ &state,+ merchant_context.get_merchant_key_store(),+ &business_profile,+ authentication.authentication_connector.clone(),+ )+ .await?;++ if let Some(trans_status) = authentication.trans_status.clone() {+ if trans_status.is_pending() {+ let post_auth_response =+ <ExternalAuthentication as UnifiedAuthenticationService>::post_authentication(+ &state,+ &business_profile,+ None,+ &three_ds_connector_account,+ &authentication_connector.to_string(),+ &authentication_id,+ common_enums::PaymentMethod::Card,+ merchant_id,+ Some(&authentication),+ )+ .await?;++ utils::external_authentication_update_trackers(+ &state,+ post_auth_response,+ authentication.clone(),+ None,+ merchant_context.get_merchant_key_store(),+ None,+ None,+ None,+ None,+ )+ .await?;+ }+ }++ let acquirer_details = Some(AcquirerDetails {+ acquirer_bin: authentication.acquirer_bin.clone(),+ acquirer_merchant_id: authentication.acquirer_merchant_id.clone(),+ merchant_country_code: authentication.acquirer_country_code.clone(),+ });++ let encrypted_data = domain::types::crypto_operation(+ &key_manager_state,+ common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication),+ domain::types::CryptoOperation::BatchDecrypt(+ hyperswitch_domain_models::authentication::EncryptedAuthentication::to_encryptable(+ hyperswitch_domain_models::authentication::EncryptedAuthentication {+ billing_address: authentication.billing_address,+ shipping_address: authentication.shipping_address,+ },+ ),+ ),+ common_utils::types::keymanager::Identifier::Merchant(+ merchant_context+ .get_merchant_key_store()+ .merchant_id+ .clone(),+ ),+ merchant_context.get_merchant_key_store().key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt authentication data".to_string())?;++ let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to get encrypted data for authentication after encryption")?;++ let email_decrypted = authentication+ .clone()+ .async_lift(|inner| async {+ domain::types::crypto_operation(+ &key_manager_state,+ common_utils::type_name!(Authentication),+ domain::types::CryptoOperation::DecryptOptional(inner),+ common_utils::types::keymanager::Identifier::Merchant(+ merchant_context+ .get_merchant_key_store()+ .merchant_id+ .clone(),+ ),+ merchant_context.get_merchant_key_store().key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt email")?;++ let browser_info = authentication+ .browser_info+ .clone()+ .map(|browser_info| {+ browser_info.parse_value::<payments::BrowserInformation>("BrowserInformation")+ })+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)?;++ let amount = authentication+ .amount+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("amount failed to get amount from authentication table")?;+ let currency = authentication+ .currency+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("currency failed to get currency from authentication table")?;++ let authentication_connector = authentication+ .authentication_connector+ .map(|connector| common_enums::AuthenticationConnectors::from_str(&connector))+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Incorrect authentication connector stored in table")?;++ let billing = encrypted_data+ .billing_address+ .map(|billing| {+ billing+ .into_inner()+ .expose()+ .parse_value::<payments::Address>("Address")+ })+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse billing address")?;++ let shipping = encrypted_data+ .shipping_address+ .map(|shipping| {+ shipping+ .into_inner()+ .expose()+ .parse_value::<payments::Address>("Address")+ })+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse shipping address")?;++ let response = AuthenticationSyncResponse {+ authentication_id: authentication_id.clone(),+ merchant_id: merchant_id.clone(),+ status: authentication.authentication_status,+ client_secret: authentication+ .authentication_client_secret+ .map(masking::Secret::new),+ amount,+ currency,+ authentication_connector,+ force_3ds_challenge: authentication.force_3ds_challenge,+ return_url: authentication.return_url.clone(),+ created_at: authentication.created_at,+ profile_id: authentication.profile_id.clone(),+ psd2_sca_exemption_type: authentication.psd2_sca_exemption_type,+ acquirer_details,+ error_message: authentication.error_message.clone(),+ error_code: authentication.error_code.clone(),+ authentication_value,+ threeds_server_transaction_id: authentication.threeds_server_transaction_id.clone(),+ maximum_supported_3ds_version: authentication.maximum_supported_version.clone(),+ connector_authentication_id: authentication.connector_authentication_id.clone(),+ three_ds_method_data: authentication.three_ds_method_data.clone(),+ three_ds_method_url: authentication.three_ds_method_url.clone(),+ message_version: authentication.message_version.clone(),+ connector_metadata: authentication.connector_metadata.clone(),+ directory_server_id: authentication.directory_server_id.clone(),+ billing,+ shipping,+ browser_information: browser_info,+ email: email_decrypted,+ transaction_status: authentication.trans_status.clone(),+ acs_url: authentication.acs_url.clone(),+ challenge_request: authentication.challenge_request.clone(),+ acs_reference_number: authentication.acs_reference_number.clone(),+ acs_trans_id: authentication.acs_trans_id.clone(),+ acs_signed_content: authentication.acs_signed_content,+ three_ds_requestor_url: business_profile+ .authentication_connector_details+ .clone()+ .map(|details| details.three_ds_requestor_url),+ three_ds_requestor_app_url: business_profile+ .authentication_connector_details+ .and_then(|details| details.three_ds_requestor_app_url),+ profile_acquirer_id: authentication.profile_acquirer_id.clone(),+ eci,+ };++ Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(+ response,+ ))+}++#[cfg(feature = "v1")]+pub async fn authentication_post_sync_core(+ state: SessionState,+ merchant_context: domain::MerchantContext,+ req: AuthenticationSyncPostUpdateRequest,+) -> RouterResponse<()> {+ let authentication_id = req.authentication_id;+ let merchant_account = merchant_context.get_merchant_account();+ let merchant_id = merchant_account.get_id();+ let db = &*state.store;+ let authentication = db+ .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)+ .await+ .to_not_found_response(ApiErrorResponse::AuthenticationNotFound {+ id: authentication_id.get_string_repr().to_owned(),+ })?;+ let key_manager_state = (&state).into();+ let business_profile = db+ .find_business_profile_by_profile_id(+ &key_manager_state,+ merchant_context.get_merchant_key_store(),+ &authentication.profile_id,+ )+ .await+ .to_not_found_response(ApiErrorResponse::ProfileNotFound {+ id: authentication.profile_id.get_string_repr().to_owned(),+ })?;++ let (authentication_connector, three_ds_connector_account) =+ auth_utils::get_authentication_connector_data(+ &state,+ merchant_context.get_merchant_key_store(),+ &business_profile,+ authentication.authentication_connector.clone(),+ )+ .await?;++ let post_auth_response =+ <ExternalAuthentication as UnifiedAuthenticationService>::post_authentication(+ &state,+ &business_profile,+ None,+ &three_ds_connector_account,+ &authentication_connector.to_string(),+ &authentication_id,+ common_enums::PaymentMethod::Card,+ merchant_id,+ Some(&authentication),+ )+ .await?;++ utils::external_authentication_update_trackers(+ &state,+ post_auth_response,+ authentication.clone(),+ None,+ merchant_context.get_merchant_key_store(),+ None,+ None,+ None,+ None,+ )+ .await?;++ let authentication_details = business_profile+ .authentication_connector_details+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("authentication_connector_details not configured by the merchant")?;++ let authentication_response = AuthenticationAuthenticateResponse::foreign_try_from((+ &authentication,+ None,+ None,+ authentication_details,+ ))?;++ let redirect_response = helpers::get_handle_response_url_for_modular_authentication(+ authentication_id,+ &business_profile,+ &authentication_response,+ authentication_connector.to_string(),+ authentication.return_url,+ authentication+ .authentication_client_secret+ .clone()+ .map(masking::Secret::new)+ .as_ref(),+ authentication.amount,+ )?;++ Ok(hyperswitch_domain_models::api::ApplicationResponse::JsonForRedirection(redirect_response))+}diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex 83642c7f62..b8d68f8f36 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -1764,6 +1764,13 @@ pub fn get_external_authentication_request_poll_id() -> String {payment_id.get_external_authentication_request_poll_id()}++pub fn get_modular_authentication_request_poll_id(+ authentication_id: &common_utils::id_type::AuthenticationId,+) -> String {+ authentication_id.get_external_authentication_request_poll_id()+}+pub fn get_html_redirect_response_popup(return_url_with_query_params: String,) -> RouterResult<String> {@@ -1880,6 +1887,89 @@ pub fn get_html_redirect_response_for_external_authentication(Ok(html)}+#[cfg(feature = "v1")]+pub fn get_html_redirect_response_for_external_modular_authentication(+ return_url_with_query_params: String,+ authentication_response: &api_models::authentication::AuthenticationResponse,+ authentication_id: common_utils::id_type::AuthenticationId,+ poll_config: &PollConfig,+) -> RouterResult<String> {+ // 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 => {+ // Request poll id sent to client for retrieve_poll_status api+ let req_poll_id = get_modular_authentication_request_poll_id(&authentication_id);+ let poll_frequency = poll_config.frequency;+ let poll_delay_in_secs = poll_config.delay_in_secs;+ html! {+ head {+ title { "Redirect Form" }+ (PreEscaped(format!(r#"+ <script>+ let return_url = "{return_url_with_query_params}";+ let poll_status_data = {{+ 'poll_id': '{req_poll_id}',+ 'frequency': '{poll_frequency}',+ 'delay_in_secs': '{poll_delay_in_secs}',+ 'return_url_with_query_params': return_url+ }};+ try {{+ // if inside iframe, send post message to parent for redirection+ if (window.self !== window.parent) {{+ window.parent.postMessage({{poll_status: poll_status_data}}, '*')+ // if parent, redirect self to return_url+ }} else {{+ window.location.href = return_url+ }}+ }}+ catch(err) {{+ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url+ window.parent.postMessage({{poll_status: poll_status_data}}, '*')+ setTimeout(function() {{+ window.location.href = return_url+ }}, 10000);+ console.log(err.message)+ }}+ </script>+ "#)))+ }+ }+ .into_string()+ },+ _ => {+ html! {+ head {+ title { "Redirect Form" }+ (PreEscaped(format!(r#"+ <script>+ let return_url = "{return_url_with_query_params}";+ try {{+ // if inside iframe, send post message to parent for redirection+ if (window.self !== window.parent) {{+ window.parent.postMessage({{openurl_if_required: return_url}}, '*')+ // if parent, redirect self to return_url+ }} else {{+ window.location.href = return_url+ }}+ }}+ catch(err) {{+ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url+ window.parent.postMessage({{openurl_if_required: return_url}}, '*')+ setTimeout(function() {{+ window.location.href = return_url+ }}, 10000);+ console.log(err.message)+ }}+ </script>+ "#)))+ }+ }+ .into_string()+ },+ };+ Ok(html)+}+#[inline]pub fn get_flow_name<F>() -> RouterResult<String> {Ok(std::any::type_name::<F>()diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex f52b0d44c8..9584a9af16 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -2821,6 +2821,11 @@ impl Authentication {web::resource("/{authentication_id}/authenticate").route(web::post().to(authentication::authentication_authenticate)),)+ .service(+ web::resource("{merchant_id}/{authentication_id}/sync")+ .route(web::post().to(authentication::authentication_sync))+ .route(web::get().to(authentication::authentication_sync_post_update)),+ )}}diff --git a/crates/router/src/routes/authentication.rs b/crates/router/src/routes/authentication.rsindex a6a64a3609..04d71b4fa4 100644--- a/crates/router/src/routes/authentication.rs+++ b/crates/router/src/routes/authentication.rs@@ -1,7 +1,10 @@use actix_web::{web, HttpRequest, Responder};-#[cfg(feature = "v1")]-use api_models::authentication::AuthenticationEligibilityRequest;use api_models::authentication::{AuthenticationAuthenticateRequest, AuthenticationCreateRequest};+#[cfg(feature = "v1")]+use api_models::authentication::{+ AuthenticationEligibilityRequest, AuthenticationSyncPostUpdateRequest,+ AuthenticationSyncRequest,+};use router_env::{instrument, tracing, Flow};use crate::{@@ -125,3 +128,84 @@ pub async fn authentication_authenticate()).await}++#[cfg(feature = "v1")]+#[instrument(skip_all, fields(flow = ?Flow::AuthenticationSync))]+pub async fn authentication_sync(+ state: web::Data<app::AppState>,+ req: HttpRequest,+ path: web::Path<(+ common_utils::id_type::MerchantId,+ common_utils::id_type::AuthenticationId,+ )>,+ json_payload: web::Query<AuthenticationSyncRequest>,+) -> impl Responder {+ let flow = Flow::AuthenticationSync;+ let api_auth = auth::ApiKeyAuth::default();+ let (_merchant_id, authentication_id) = path.into_inner();+ let payload = AuthenticationSyncRequest {+ authentication_id,+ ..json_payload.into_inner()+ };+ let (auth, auth_flow) =+ match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {+ Ok((auth, auth_flow)) => (auth, auth_flow),+ Err(e) => return api::log_and_return_error_response(e),+ };++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: auth::AuthenticationData, req, _| {+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(+ domain::Context(auth.merchant_account, auth.key_store),+ ));+ unified_authentication_service::authentication_sync_core(+ state,+ merchant_context,+ auth_flow,+ req,+ )+ },+ &*auth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++#[cfg(feature = "v1")]+#[instrument(skip_all, fields(flow = ?Flow::AuthenticationSyncPostUpdate))]+pub async fn authentication_sync_post_update(+ state: web::Data<app::AppState>,+ req: HttpRequest,+ path: web::Path<(+ common_utils::id_type::MerchantId,+ common_utils::id_type::AuthenticationId,+ )>,+) -> impl Responder {+ let flow = Flow::AuthenticationSyncPostUpdate;+ let (merchant_id, authentication_id) = path.into_inner();+ let payload = AuthenticationSyncPostUpdateRequest { authentication_id };++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: auth::AuthenticationData, req, _| {+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(+ domain::Context(auth.merchant_account, auth.key_store),+ ));+ unified_authentication_service::authentication_post_sync_core(+ state,+ merchant_context,+ req,+ )+ },+ &auth::MerchantIdAuth(merchant_id),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex bd1593d680..58865de64a 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -364,6 +364,8 @@ impl From<Flow> for ApiIdentifier {Flow::AuthenticationCreate| Flow::AuthenticationEligibility+ | Flow::AuthenticationSync+ | Flow::AuthenticationSyncPostUpdate| Flow::AuthenticationAuthenticate => Self::Authentication,Flow::Proxy => Self::Proxy,diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 339535474f..4d396394cc 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -4235,6 +4235,14 @@ impl ClientSecretFetch for api_models::authentication::AuthenticationAuthenticat}}+impl ClientSecretFetch for api_models::authentication::AuthenticationSyncRequest {+ fn get_client_secret(&self) -> Option<&String> {+ self.client_secret+ .as_ref()+ .map(|client_secret| client_secret.peek())+ }+}+pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync + Send>(headers: &HeaderMap,api_auth: ApiKeyAuth,diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex b29b3c7432..1fefce2b33 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -618,6 +618,10 @@ pub enum Flow {AuthenticationCreate,/// Authentication Eligibility flowAuthenticationEligibility,+ /// Authentication Sync flow+ AuthenticationSync,+ /// Authentication Sync Post Update flow+ AuthenticationSyncPostUpdate,/// Authentication Authenticate flowAuthenticationAuthenticate,///Proxy Flow