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

feat(authentication): add click to pay support for modular authentication (#10004)

Sahkal Poddare0538deb5566
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 31353354c4..1da9cce90e 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -6975,6 +6975,207 @@
]
}
},
+ "/authentication/{authentication_id}/eligibility": {
+ "post": {
+ "tags": [
+ "Authentication"
+ ],
+ "summary": "Authentication - Eligibility",
+ "description": "Check if an authentication is eligible for a specific merchant.\n",
+ "operationId": "Check Authentication Eligibility",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationEligibilityRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Authentication eligibility checked",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationEligibilityResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "publishable_key": []
+ }
+ ]
+ }
+ },
+ "/authentication/{authentication_id}/authenticate": {
+ "post": {
+ "tags": [
+ "Authentication"
+ ],
+ "summary": "Authentication - Authenticate",
+ "description": "Authenticate an authentication for accessing our APIs from your servers.\n",
+ "operationId": "Authenticate an Authentication",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationAuthenticateRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Authentication authenticated",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationAuthenticateResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "publishable_key": []
+ }
+ ]
+ }
+ },
+ "/authentication/{authentication_id}/redirect": {
+ "post": {
+ "tags": [
+ "Authentication"
+ ],
+ "summary": "Authentication - Redirect",
+ "description": "Redirect an authentication for accessing our APIs from your servers.\n",
+ "operationId": "Redirect an Authentication",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationSyncPostUpdateRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Authentication redirect"
+ },
+ "400": {
+ "description": "Invalid data"
+ }
+ },
+ "security": []
+ }
+ },
+ "/authentication/{authentication_id}/sync": {
+ "post": {
+ "tags": [
+ "Authentication"
+ ],
+ "summary": "Authentication - Sync",
+ "description": "Sync an authentication for accessing our APIs from your servers.\n",
+ "operationId": "Sync an Authentication",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationSyncRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Authentication sync",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationSyncResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "publishable_key": []
+ }
+ ]
+ }
+ },
+ "/authentication/{authentication_id}/enabled_authn_methods_token": {
+ "post": {
+ "tags": [
+ "Authentication"
+ ],
+ "summary": "Authentication - Enable Authn Methods Token",
+ "description": "Enable authn methods token for an authentication.\n",
+ "operationId": "Enable Authentication Authn Methods Token",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationSessionTokenRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Authentication enabled authn methods token",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuthenticationSessionResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "publishable_key": []
+ }
+ ]
+ }
+ },
"/authentication/{authentication_id}/eligibility-check": {
"post": {
"tags": [
@@ -9391,6 +9592,134 @@
"expired"
]
},
+ "AuthenticationAuthenticateRequest": {
+ "type": "object",
+ "required": [
+ "client_secret",
+ "device_channel",
+ "threeds_method_comp_ind"
+ ],
+ "properties": {
+ "client_secret": {
+ "type": "string",
+ "description": "Client secret for the authentication"
+ },
+ "sdk_information": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SdkInformation"
+ }
+ ],
+ "nullable": true
+ },
+ "device_channel": {
+ "$ref": "#/components/schemas/DeviceChannel"
+ },
+ "threeds_method_comp_ind": {
+ "$ref": "#/components/schemas/ThreeDsCompletionIndicator"
+ }
+ }
+ },
+ "AuthenticationAuthenticateResponse": {
+ "type": "object",
+ "required": [
+ "acs_url",
+ "three_ds_requestor_url",
+ "error_message",
+ "error_code",
+ "authentication_value",
+ "status",
+ "authentication_id",
+ "eci"
+ ],
+ "properties": {
+ "trans_status": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/TransactionStatus"
+ }
+ ],
+ "nullable": true
+ },
+ "acs_url": {
+ "type": "string",
+ "description": "Access Server URL to be used for challenge submission",
+ "example": "https://example.com/redirect"
+ },
+ "challenge_request": {
+ "type": "string",
+ "description": "Challenge request which should be sent to acs_url",
+ "nullable": true
+ },
+ "acs_reference_number": {
+ "type": "string",
+ "description": "Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa)",
+ "nullable": true
+ },
+ "acs_trans_id": {
+ "type": "string",
+ "description": "Unique identifier assigned by the ACS to identify a single transaction",
+ "nullable": true
+ },
+ "three_ds_server_transaction_id": {
+ "type": "string",
+ "description": "Unique identifier assigned by the 3DS Server to identify a single transaction",
+ "nullable": true
+ },
+ "acs_signed_content": {
+ "type": "string",
+ "description": "Contains the JWS object created by the ACS for the ARes(Authentication Response) message",
+ "nullable": true
+ },
+ "three_ds_requestor_url": {
+ "type": "string",
+ "description": "Three DS Requestor URL"
+ },
+ "three_ds_requestor_app_url": {
+ "type": "string",
+ "description": "Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred",
+ "nullable": true
+ },
+ "error_message": {
+ "type": "string",
+ "description": "The error message for this authentication."
+ },
+ "error_code": {
+ "type": "string",
+ "description": "The error code for this authentication."
+ },
+ "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."
+ },
+ "status": {
+ "$ref": "#/components/schemas/AuthenticationStatus"
+ },
+ "authentication_connector": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AuthenticationConnectors"
+ }
+ ],
+ "nullable": true
+ },
+ "authentication_id": {
+ "$ref": "#/components/schemas/AuthenticationId"
+ },
+ "eci": {
+ "type": "string",
+ "description": "The ECI value for this authentication."
+ },
+ "acquirer_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AcquirerDetails"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"AuthenticationConnectorDetails": {
"type": "object",
"required": [
@@ -9500,6 +9829,14 @@
}
],
"nullable": true
+ },
+ "customer_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -9721,6 +10058,23 @@
}
}
},
+ "AuthenticationId": {
+ "type": "string",
+ "description": "A type for authentication_id that can be used for authentication IDs"
+ },
+ "AuthenticationPaymentMethodData": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ClickToPayDetails"
+ }
+ ]
+ },
+ "AuthenticationPaymentMethodType": {
+ "type": "string",
+ "enum": [
+ "ctp"
+ ]
+ },
"AuthenticationResponse": {
"type": "object",
"required": [
@@ -9816,6 +10170,14 @@
"type": "string",
"description": "Profile Acquirer ID get from profile acquirer configuration",
"nullable": true
+ },
+ "customer_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -9864,6 +10226,80 @@
}
]
},
+ "AuthenticationSessionResponse": {
+ "type": "object",
+ "required": [
+ "authentication_id",
+ "session_token"
+ ],
+ "properties": {
+ "authentication_id": {
+ "type": "string",
+ "description": "The identifier for the payment"
+ },
+ "session_token": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AuthenticationSessionToken"
+ },
+ "description": "The list of session token object"
+ }
+ }
+ },
+ "AuthenticationSessionToken": {
+ "oneOf": [
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ClickToPaySessionResponse"
+ },
+ {
+ "type": "object",
+ "required": [
+ "wallet_name"
+ ],
+ "properties": {
+ "wallet_name": {
+ "type": "string",
+ "enum": [
+ "click_to_pay"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "required": [
+ "wallet_name"
+ ],
+ "properties": {
+ "wallet_name": {
+ "type": "string",
+ "enum": [
+ "no_session_token_received"
+ ]
+ }
+ }
+ }
+ ],
+ "discriminator": {
+ "propertyName": "wallet_name"
+ }
+ },
+ "AuthenticationSessionTokenRequest": {
+ "type": "object",
+ "required": [
+ "client_secret"
+ ],
+ "properties": {
+ "client_secret": {
+ "type": "string",
+ "description": "Client Secret for the authentication"
+ }
+ }
+ },
"AuthenticationStatus": {
"type": "string",
"enum": [
@@ -9873,6 +10309,9 @@
"failed"
]
},
+ "AuthenticationSyncPostUpdateRequest": {
+ "type": "object"
+ },
"AuthenticationSyncRequest": {
"type": "object",
"required": [
@@ -9882,6 +10321,14 @@
"client_secret": {
"type": "string",
"description": "The client secret for this authentication."
+ },
+ "payment_method_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PostAuthenticationRequestPaymentMethodData"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -13459,6 +13906,39 @@
"add_to_unbilled_charges"
]
},
+ "ClickToPayDetails": {
+ "type": "object",
+ "properties": {
+ "merchant_transaction_id": {
+ "type": "string",
+ "description": "merchant transaction id",
+ "nullable": true
+ },
+ "correlation_id": {
+ "type": "string",
+ "description": "network transaction correlation id",
+ "nullable": true
+ },
+ "x_src_flow_id": {
+ "type": "string",
+ "description": "session transaction flow id",
+ "nullable": true
+ },
+ "provider": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CtpServiceProvider"
+ }
+ ],
+ "nullable": true
+ },
+ "encrypted_payload": {
+ "type": "string",
+ "description": "Encrypted payload",
+ "nullable": true
+ }
+ }
+ },
"ClickToPayEligibilityCheckData": {
"type": "object",
"properties": {
@@ -31164,6 +31644,21 @@
"not_found"
]
},
+ "PostAuthenticationRequestPaymentMethodData": {
+ "type": "object",
+ "required": [
+ "payment_method_type",
+ "payment_method_data"
+ ],
+ "properties": {
+ "payment_method_type": {
+ "$ref": "#/components/schemas/AuthenticationPaymentMethodType"
+ },
+ "payment_method_data": {
+ "$ref": "#/components/schemas/AuthenticationPaymentMethodData"
+ }
+ }
+ },
"PrimaryBusinessDetails": {
"type": "object",
"required": [
diff --git a/crates/api_models/src/authentication.rs b/crates/api_models/src/authentication.rs
index b730ee8582..4e7d2abc13 100644
--- a/crates/api_models/src/authentication.rs
+++ b/crates/api_models/src/authentication.rs
@@ -13,7 +13,10 @@ use utoipa::ToSchema;
#[cfg(feature = "v1")]
use crate::payments::{Address, BrowserInformation, PaymentMethodData};
-use crate::payments::{CustomerDetails, DeviceChannel, SdkInformation, ThreeDsCompletionIndicator};
+use crate::payments::{
+ ClickToPaySessionResponse, CustomerDetails, DeviceChannel, SdkInformation,
+ ThreeDsCompletionIndicator,
+};
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationCreateRequest {
@@ -60,6 +63,10 @@ pub struct AuthenticationCreateRequest {
/// Acquirer details information
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
+
+ /// Customer details.
+ #[schema(value_type = Option<CustomerDetails>)]
+ pub customer_details: Option<CustomerDetails>,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
@@ -138,6 +145,10 @@ pub struct AuthenticationResponse {
/// Profile Acquirer ID get from profile acquirer configuration
#[schema(value_type = Option<String>)]
pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,
+
+ /// Customer details.
+ #[schema(value_type = Option<CustomerDetails>)]
+ pub customer_details: Option<CustomerDetails>,
}
impl ApiEventMetric for AuthenticationCreateRequest {
@@ -527,6 +538,7 @@ pub struct AuthenticationAuthenticateResponse {
#[schema(value_type = Option<TransactionStatus>)]
pub transaction_status: Option<common_enums::TransactionStatus>,
/// Access Server URL to be used for challenge submission
+ #[schema(value_type = String, example = "https://example.com/redirect")]
pub acs_url: Option<url::Url>,
/// Challenge request which should be sent to acs_url
pub challenge_request: Option<String>,
@@ -745,11 +757,55 @@ pub struct AuthenticationSyncRequest {
/// The client secret for this authentication.
#[schema(value_type = String)]
pub client_secret: Option<masking::Secret<String>>,
+ /// Payment method data for Post Authentication sync
+ pub payment_method_details: Option<PostAuthenticationRequestPaymentMethodData>,
/// Authentication ID for the authentication
#[serde(skip_deserializing)]
pub authentication_id: id_type::AuthenticationId,
}
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct PostAuthenticationRequestPaymentMethodData {
+ pub payment_method_type: AuthenticationPaymentMethodType,
+ pub payment_method_data: AuthenticationPaymentMethodData,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub enum AuthenticationPaymentMethodType {
+ #[serde(rename = "ctp")]
+ ClickToPay,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[serde(untagged)]
+pub enum AuthenticationPaymentMethodData {
+ ClickToPayDetails(ClickToPayDetails),
+}
+
+impl AuthenticationPaymentMethodData {
+ pub fn get_click_to_pay_details(&self) -> Option<&ClickToPayDetails> {
+ match self {
+ Self::ClickToPayDetails(details) => Some(details),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct ClickToPayDetails {
+ /// merchant transaction id
+ pub merchant_transaction_id: Option<String>,
+ /// network transaction correlation id
+ pub correlation_id: Option<String>,
+ /// session transaction flow id
+ pub x_src_flow_id: Option<String>,
+ /// provider Eg: Visa, Mastercard
+ #[schema(value_type = Option<CtpServiceProvider>)]
+ pub provider: Option<super::enums::CtpServiceProvider>,
+ /// Encrypted payload
+ #[schema(value_type = Option<String>)]
+ pub encrypted_payload: Option<masking::Secret<String>>,
+}
+
impl ApiEventMetric for AuthenticationSyncRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
@@ -772,3 +828,47 @@ impl ApiEventMetric for AuthenticationSyncPostUpdateRequest {
})
}
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+pub struct AuthenticationSessionTokenRequest {
+ /// Authentication ID for the authentication
+ #[serde(skip_deserializing)]
+ pub authentication_id: id_type::AuthenticationId,
+ /// Client Secret for the authentication
+ #[schema(value_type = String)]
+ pub client_secret: Option<masking::Secret<String>>,
+}
+
+#[derive(Debug, serde::Serialize, Clone, ToSchema)]
+pub struct AuthenticationSessionResponse {
+ /// The identifier for the payment
+ #[schema(value_type = String)]
+ pub authentication_id: id_type::AuthenticationId,
+ /// The list of session token object
+ pub session_token: Vec<AuthenticationSessionToken>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(tag = "wallet_name")]
+#[serde(rename_all = "snake_case")]
+pub enum AuthenticationSessionToken {
+ /// The sessions response structure for ClickToPay
+ ClickToPay(Box<ClickToPaySessionResponse>),
+ NoSessionTokenReceived,
+}
+
+impl ApiEventMetric for AuthenticationSessionTokenRequest {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Authentication {
+ authentication_id: self.authentication_id.clone(),
+ })
+ }
+}
+
+impl ApiEventMetric for AuthenticationSessionResponse {
+ 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.rs
index b3f845e505..1983cf5925 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2563,7 +2563,9 @@ pub enum PaymentChannel {
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CtpServiceProvider {
+ #[strum(serialize = "ctp_visa")]
Visa,
+ #[strum(serialize = "ctp_mastercard")]
Mastercard,
}
@@ -8321,6 +8323,14 @@ impl AuthenticationConnectors {
Self::Cardinal => true,
}
}
+
+ pub fn is_pre_auth_required_in_post_authn_flow(&self) -> bool {
+ matches!(self, Self::CtpMastercard | Self::CtpVisa)
+ }
+
+ pub fn is_click_to_pay(&self) -> bool {
+ matches!(self, Self::CtpMastercard | Self::CtpVisa)
+ }
}
#[derive(
diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs
index 4075612178..07de55d595 100644
--- a/crates/diesel_models/src/authentication.rs
+++ b/crates/diesel_models/src/authentication.rs
@@ -73,6 +73,7 @@ pub struct Authentication {
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
+ pub customer_details: Option<Encryption>,
}
impl Authentication {
@@ -154,6 +155,7 @@ pub struct AuthenticationNew {
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
+ pub customer_details: Option<Encryption>,
}
#[derive(Debug)]
@@ -272,6 +274,7 @@ pub struct AuthenticationUpdateInternal {
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
+ pub customer_details: Option<Encryption>,
}
impl Default for AuthenticationUpdateInternal {
@@ -317,6 +320,7 @@ impl Default for AuthenticationUpdateInternal {
challenge_code_reason: Default::default(),
message_extension: Default::default(),
challenge_request_key: Default::default(),
+ customer_details: Default::default(),
}
}
}
@@ -364,6 +368,7 @@ impl AuthenticationUpdateInternal {
challenge_code_reason,
message_extension,
challenge_request_key,
+ customer_details,
} = self;
Authentication {
connector_authentication_id: connector_authentication_id
@@ -410,6 +415,7 @@ impl AuthenticationUpdateInternal {
challenge_code_reason: challenge_code_reason.or(source.challenge_code_reason),
message_extension: message_extension.or(source.message_extension),
challenge_request_key: challenge_request_key.or(source.challenge_request_key),
+ customer_details: customer_details.or(source.customer_details),
..source
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 87b6d34cac..9b3c27f07f 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -144,6 +144,7 @@ diesel::table! {
message_extension -> Nullable<Jsonb>,
#[max_length = 255]
challenge_request_key -> Nullable<Varchar>,
+ customer_details -> Nullable<Bytea>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 0cc98a53fa..2ab6c51ef4 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -144,6 +144,7 @@ diesel::table! {
message_extension -> Nullable<Jsonb>,
#[max_length = 255]
challenge_request_key -> Nullable<Varchar>,
+ customer_details -> Nullable<Bytea>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index 99fdea17cf..0de70ddeea 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -6,7 +6,7 @@ use common_utils::{
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
- ext_traits::ValueExt,
+ ext_traits::{StringExt, ValueExt},
id_type, pii, type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
@@ -97,6 +97,26 @@ impl MerchantConnectorAccount {
pub fn get_metadata(&self) -> Option<Secret<Value>> {
self.metadata.clone()
}
+
+ pub fn get_ctp_service_provider(
+ &self,
+ ) -> error_stack::Result<
+ Option<common_enums::CtpServiceProvider>,
+ common_utils::errors::ParsingError,
+ > {
+ let provider = self
+ .connector_name
+ .clone()
+ .parse_enum("CtpServiceProvider")
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed to parse ctp service provider from connector_name: {}",
+ self.connector_name
+ )
+ })?;
+
+ Ok(Some(provider))
+ }
}
#[cfg(feature = "v2")]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 7cb0579600..ee545a8acd 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -222,6 +222,11 @@ Never share your secret api keys. Keep them guarded and secure.
// Routes for authentication
routes::authentication::authentication_create,
+ routes::authentication::authentication_eligibility,
+ routes::authentication::authentication_authenticate,
+ routes::authentication::authentication_redirect,
+ routes::authentication::authentication_sync,
+ routes::authentication::authentication_enabled_authn_methods_token,
routes::authentication::authentication_eligibility_check,
routes::authentication::authentication_retrieve_eligibility_check,
@@ -890,6 +895,16 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::authentication::AuthenticationEligibilityResponse,
api_models::authentication::AuthenticationSyncRequest,
api_models::authentication::AuthenticationSyncResponse,
+ api_models::authentication::AuthenticationSessionTokenRequest,
+ api_models::authentication::AuthenticationSessionResponse,
+ api_models::authentication::PostAuthenticationRequestPaymentMethodData,
+ api_models::authentication::AuthenticationAuthenticateRequest,
+ api_models::authentication::AuthenticationAuthenticateResponse,
+ api_models::authentication::ClickToPayDetails,
+ api_models::authentication::AuthenticationSyncPostUpdateRequest,
+ api_models::authentication::AuthenticationSessionToken,
+ api_models::authentication::AuthenticationPaymentMethodType,
+ api_models::authentication::AuthenticationPaymentMethodData,
api_models::open_router::OpenRouterDecideGatewayRequest,
api_models::open_router::DecideGatewayResponse,
api_models::open_router::UpdateScorePayload,
@@ -902,6 +917,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::open_router::PaymentInfo,
common_utils::id_type::PaymentId,
common_utils::id_type::ProfileId,
+ common_utils::id_type::AuthenticationId,
api_models::open_router::RankingAlgorithm,
api_models::open_router::TxnStatus,
api_models::open_router::PriorityLogicOutput,
diff --git a/crates/openapi/src/routes/authentication.rs b/crates/openapi/src/routes/authentication.rs
index 239321ba2f..cccb179191 100644
--- a/crates/openapi/src/routes/authentication.rs
+++ b/crates/openapi/src/routes/authentication.rs
@@ -16,6 +16,96 @@
)]
pub async fn authentication_create() {}
+/// Authentication - Eligibility
+///
+/// Check if an authentication is eligible for a specific merchant.
+///
+#[utoipa::path(
+ post,
+ path = "/authentication/{authentication_id}/eligibility",
+ request_body = AuthenticationEligibilityRequest,
+ responses(
+ (status = 200, description = "Authentication eligibility checked", body = AuthenticationEligibilityResponse),
+ (status = 400, description = "Invalid data")
+ ),
+ tag = "Authentication",
+ operation_id = "Check Authentication Eligibility",
+ security(("api_key" = []), ("publishable_key" = []))
+)]
+pub async fn authentication_eligibility() {}
+
+/// Authentication - Authenticate
+///
+/// Authenticate an authentication for accessing our APIs from your servers.
+///
+#[utoipa::path(
+ post,
+ path = "/authentication/{authentication_id}/authenticate",
+ request_body = AuthenticationAuthenticateRequest,
+ responses(
+ (status = 200, description = "Authentication authenticated", body = AuthenticationAuthenticateResponse),
+ (status = 400, description = "Invalid data")
+ ),
+ tag = "Authentication",
+ operation_id = "Authenticate an Authentication",
+ security(("api_key" = []), ("publishable_key" = []))
+)]
+pub async fn authentication_authenticate() {}
+
+/// Authentication - Redirect
+///
+/// Redirect an authentication for accessing our APIs from your servers.
+///
+#[utoipa::path(
+ post,
+ path = "/authentication/{authentication_id}/redirect",
+ request_body = AuthenticationSyncPostUpdateRequest,
+ responses(
+ (status = 200, description = "Authentication redirect"),
+ (status = 400, description = "Invalid data")
+ ),
+ tag = "Authentication",
+ operation_id = "Redirect an Authentication",
+ security()
+)]
+pub async fn authentication_redirect() {}
+
+/// Authentication - Sync
+///
+/// Sync an authentication for accessing our APIs from your servers.
+///
+#[utoipa::path(
+ post,
+ path = "/authentication/{authentication_id}/sync",
+ request_body = AuthenticationSyncRequest,
+ responses(
+ (status = 200, description = "Authentication sync", body = AuthenticationSyncResponse),
+ (status = 400, description = "Invalid data")
+ ),
+ tag = "Authentication",
+ operation_id = "Sync an Authentication",
+ security(("api_key" = []), ("publishable_key" = []))
+)]
+pub async fn authentication_sync() {}
+
+/// Authentication - Enable Authn Methods Token
+///
+/// Enable authn methods token for an authentication.
+///
+#[utoipa::path(
+ post,
+ path = "/authentication/{authentication_id}/enabled_authn_methods_token",
+ request_body = AuthenticationSessionTokenRequest,
+ responses(
+ (status = 200, description = "Authentication enabled authn methods token", body = AuthenticationSessionResponse),
+ (status = 400, description = "Invalid data")
+ ),
+ tag = "Authentication",
+ operation_id = "Enable Authentication Authn Methods Token",
+ security(("api_key" = []), ("publishable_key" = []))
+)]
+pub async fn authentication_enabled_authn_methods_token() {}
+
/// Authentication - POST Eligibility Check
///
#[utoipa::path(
diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs
index 129de31dbc..05156b8211 100644
--- a/crates/router/src/core/authentication/utils.rs
+++ b/crates/router/src/core/authentication/utils.rs
@@ -302,6 +302,7 @@ pub async fn create_new_authentication(
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
+ customer_details: None,
};
state
.store
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 37954242ab..874e4c7172 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -6481,7 +6481,9 @@ async fn get_card_brands_based_on_active_merchant_connector_account(
Ok(card_brands)
}
-fn validate_customer_details_for_click_to_pay(customer_details: &CustomerData) -> RouterResult<()> {
+pub fn validate_customer_details_for_click_to_pay(
+ customer_details: &CustomerData,
+) -> RouterResult<()> {
match (
customer_details.phone.as_ref(),
customer_details.phone_country_code.as_ref(),
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index c1145aeea5..e2db966f19 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1379,6 +1379,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
None,
None,
None,
+ None,
None
)
.await?;
@@ -1430,6 +1431,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
None,
None,
None,
+ None
)
.await?;
let acquirer_configs = authentication
diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rs
index 339ef74e3c..544a3ed584 100644
--- a/crates/router/src/core/unified_authentication_service.rs
+++ b/crates/router/src/core/unified_authentication_service.rs
@@ -10,16 +10,19 @@ use api_models::authentication::{
use api_models::{
authentication::{
AcquirerDetails, AuthenticationAuthenticateRequest, AuthenticationAuthenticateResponse,
- AuthenticationCreateRequest, AuthenticationResponse,
+ AuthenticationCreateRequest, AuthenticationResponse, AuthenticationSessionTokenRequest,
},
- payments,
+ payments::{self, CustomerDetails},
};
#[cfg(feature = "v1")]
-use common_utils::{ext_traits::ValueExt, types::keymanager::ToEncryptable};
+use common_utils::{
+ ext_traits::ValueExt, types::keymanager::ToEncryptable, types::AmountConvertor,
+};
use diesel_models::authentication::{Authentication, AuthenticationNew};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse,
+ ext_traits::OptionExt,
payment_method_data,
router_request_types::{
authentication::{MessageCategory, PreAuthenticationData},
@@ -46,7 +49,7 @@ use crate::{
core::{
authentication::utils as auth_utils,
errors::utils::StorageErrorExt,
- payments::helpers,
+ payments::{helpers, validate_customer_details_for_click_to_pay},
unified_authentication_service::types::{
ClickToPay, ExternalAuthentication, UnifiedAuthenticationService,
UNIFIED_AUTHENTICATION_SERVICE,
@@ -556,6 +559,7 @@ pub async fn create_new_authentication(
currency: Option<common_enums::Currency>,
return_url: Option<String>,
profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
+ customer_details: Option<common_utils::encryption::Encryption>,
) -> RouterResult<Authentication> {
let service_details_value = service_details
.map(serde_json::to_value)
@@ -620,6 +624,7 @@ pub async fn create_new_authentication(
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
+ customer_details,
};
state
.store
@@ -708,6 +713,40 @@ pub async fn authentication_create_core(
.unwrap_or((None, None, None))
};
+ let customer_details = req
+ .customer_details
+ .clone()
+ .async_lift(|customer_details| async {
+ domain::types::crypto_operation(
+ &key_manager_state,
+ common_utils::type_name!(Authentication),
+ domain::types::CryptoOperation::EncryptOptional(
+ customer_details
+ .map(|details| {
+ common_utils::ext_traits::Encode::encode_to_value(&details)
+ .map(masking::Secret::<serde_json::Value>::new)
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Unable to encode customer details to serde_json::Value",
+ )
+ })
+ .transpose()?,
+ ),
+ 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())
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt customer details")
+ })
+ .await?;
+
let new_authentication = create_new_authentication(
&state,
merchant_id.clone(),
@@ -730,6 +769,9 @@ pub async fn authentication_create_core(
Some(req.currency),
req.return_url,
req.profile_acquirer_id.clone(),
+ customer_details
+ .clone()
+ .map(common_utils::encryption::Encryption::from),
)
.await?;
@@ -748,6 +790,35 @@ pub async fn authentication_create_core(
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("currency failed to get currency from authentication table")?;
+ let customer_details_decrypted = new_authentication
+ .customer_details
+ .clone()
+ .async_lift(|inner| async {
+ domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
+ &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 decrypt email from authentication table")?;
+
+ let customer_details = customer_details_decrypted
+ .map(|inner| inner.parse_value("CustomerData"))
+ .transpose()
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while parsing customer data from authentication table")?;
+
let response = AuthenticationResponse::foreign_try_from((
new_authentication.clone(),
amount,
@@ -755,6 +826,8 @@ pub async fn authentication_create_core(
profile_id,
acquirer_details,
new_authentication.profile_acquirer_id,
+ customer_details,
+ req.customer_details.map(|details| details.id.clone()),
))?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
@@ -770,17 +843,30 @@ impl
common_utils::id_type::ProfileId,
Option<AcquirerDetails>,
Option<common_utils::id_type::ProfileAcquirerId>,
+ Option<hyperswitch_domain_models::payments::payment_intent::CustomerData>,
+ Option<common_utils::id_type::CustomerId>,
)> for AuthenticationResponse
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
- (authentication, amount, currency, profile_id, acquirer_details, profile_acquirer_id): (
+ (
+ authentication,
+ amount,
+ currency,
+ profile_id,
+ acquirer_details,
+ profile_acquirer_id,
+ customer_data,
+ customer_id,
+ ): (
Authentication,
common_utils::types::MinorUnit,
common_enums::Currency,
common_utils::id_type::ProfileId,
Option<AcquirerDetails>,
Option<common_utils::id_type::ProfileAcquirerId>,
+ Option<hyperswitch_domain_models::payments::payment_intent::CustomerData>,
+ Option<common_utils::id_type::CustomerId>,
),
) -> Result<Self, Self::Error> {
let authentication_connector = authentication
@@ -789,6 +875,24 @@ impl
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Incorrect authentication connector stored in table")?;
+
+ let customer_details = if let Some(details) = customer_data {
+ let customer_id = customer_id
+ .as_ref()
+ .ok_or(ApiErrorResponse::InternalServerError)
+ .attach_printable("Customer id not found in authentication create request")?;
+ Some(CustomerDetails {
+ id: customer_id.clone(),
+ name: details.name,
+ email: details.email,
+ phone: details.phone,
+ phone_country_code: details.phone_country_code,
+ tax_registration_id: details.tax_registration_id,
+ })
+ } else {
+ None
+ };
+
Ok(Self {
authentication_id: authentication.authentication_id,
client_secret: authentication
@@ -808,6 +912,7 @@ impl
psd2_sca_exemption_type: authentication.psd2_sca_exemption_type,
acquirer_details,
profile_acquirer_id,
+ customer_details,
})
}
}
@@ -1438,36 +1543,121 @@ pub async fn authentication_sync_core(
)
.await?;
- let updated_authentication = match authentication.trans_status.clone() {
- Some(trans_status) if trans_status.clone().is_pending() => {
- let post_auth_response = ExternalAuthentication::post_authentication(
+ if authentication_connector.is_pre_auth_required_in_post_authn_flow() {
+ let service_details = req.payment_method_details.and_then(|details| {
+ details
+ .payment_method_data
+ .get_click_to_pay_details()
+ .cloned()
+ });
+
+ let domain_service_details = hyperswitch_domain_models::router_request_types::unified_authentication_service::CtpServiceDetails {
+ service_session_ids: Some(ServiceSessionIds {
+ merchant_transaction_id: service_details
+ .as_ref()
+ .and_then(|details| details.merchant_transaction_id.clone()),
+ correlation_id: service_details
+ .as_ref()
+ .and_then(|details| details.correlation_id.clone()),
+ x_src_flow_id: service_details
+ .as_ref()
+ .and_then(|details| details.x_src_flow_id.clone()),
+ }),
+ payment_details: None,
+ };
+
+ let transaction_details = TransactionDetails {
+ amount: authentication.amount,
+ currency: authentication.currency,
+ device_channel: None,
+ message_category: None,
+ };
+
+ let authentication_info = Some(AuthenticationInfo {
+ authentication_type: None,
+ authentication_reasons: None,
+ consent_received: false, // This is not relevant in this flow so keeping it as false
+ is_authenticated: false, // This is not relevant in this flow so keeping it as false
+ locale: None,
+ supported_card_brands: None,
+ encrypted_payload: service_details
+ .as_ref()
+ .and_then(|details| details.encrypted_payload.clone()),
+ });
+ let pre_authentication_request_data = UasPreAuthenticationRequestData {
+ service_details: Some(domain_service_details),
+ transaction_details: Some(transaction_details),
+ payment_details: None,
+ authentication_info,
+ merchant_details: None,
+ billing_address: None,
+ acquirer_bin: None,
+ acquirer_merchant_id: None,
+ };
+ // call pre-auth
+ let pre_auth_router_data: UasPreAuthenticationRouterData =
+ utils::construct_uas_router_data(
+ &state,
+ authentication_connector.to_string(),
+ common_enums::PaymentMethod::Card,
+ authentication.merchant_id.clone(),
+ None,
+ pre_authentication_request_data,
+ &three_ds_connector_account,
+ Some(authentication.authentication_id.to_owned()),
+ None,
+ )?;
+
+ let _pre_auth_response = Box::pin(utils::do_auth_connector_call(
+ &state,
+ UNIFIED_AUTHENTICATION_SERVICE.to_string(),
+ pre_auth_router_data,
+ ))
+ .await?;
+ }
+
+ let updated_authentication = if !authentication.authentication_status.is_terminal_status() {
+ let post_auth_response = if authentication_connector.is_click_to_pay() {
+ ClickToPay::post_authentication(
&state,
&business_profile,
None,
- &three_ds_connector_account,
+ &three_ds_connector_account.clone(),
&authentication_connector.to_string(),
&authentication_id,
common_enums::PaymentMethod::Card,
merchant_id,
- Some(&authentication),
+ None,
)
- .await?;
-
- utils::external_authentication_update_trackers(
+ .await?
+ } else {
+ ExternalAuthentication::post_authentication(
&state,
- post_auth_response,
- authentication.clone(),
- None,
- merchant_context.get_merchant_key_store(),
- None,
- None,
- None,
+ &business_profile,
None,
+ &three_ds_connector_account,
+ &authentication_connector.to_string(),
+ &authentication_id,
+ common_enums::PaymentMethod::Card,
+ merchant_id,
+ Some(&authentication),
)
.await?
- }
-
- _ => authentication,
+ };
+ utils::external_authentication_update_trackers(
+ &state,
+ post_auth_response,
+ authentication.clone(),
+ None,
+ merchant_context.get_merchant_key_store(),
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?
+ } else {
+ authentication
};
let (authentication_value, eci) = match auth_flow {
@@ -1766,3 +1956,178 @@ fn ensure_not_terminal_status(
})
.unwrap_or(Ok(()))
}
+
+#[cfg(feature = "v1")]
+pub async fn authentication_session_core(
+ state: SessionState,
+ merchant_context: domain::MerchantContext,
+ req: AuthenticationSessionTokenRequest,
+) -> RouterResponse<api_models::authentication::AuthenticationSessionResponse> {
+ let merchant_account = merchant_context.get_merchant_account();
+ let merchant_id = merchant_account.get_id();
+ let key_manager_state = (&state).into();
+
+ let authentication_id = req.authentication_id;
+ let authentication = state
+ .store
+ .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 mut session_tokens = Vec::new();
+
+ let business_profile = state
+ .store
+ .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(),
+ })?;
+
+ if business_profile.is_click_to_pay_enabled {
+ if let Some(value) = business_profile.authentication_product_ids.clone() {
+ let session_token = get_session_token_for_click_to_pay(
+ &state,
+ merchant_context.get_merchant_account().get_id(),
+ &merchant_context,
+ value,
+ &authentication,
+ )
+ .await?;
+ session_tokens.push(session_token);
+ }
+ }
+
+ let response = api_models::authentication::AuthenticationSessionResponse {
+ authentication_id,
+ session_token: session_tokens,
+ };
+
+ Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
+ response,
+ ))
+}
+
+#[cfg(feature = "v1")]
+pub async fn get_session_token_for_click_to_pay(
+ state: &SessionState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_context: &domain::MerchantContext,
+ authentication_product_ids: common_types::payments::AuthenticationConnectorAccountMap,
+ authentication: &Authentication,
+) -> RouterResult<api_models::authentication::AuthenticationSessionToken> {
+ let click_to_pay_mca_id = authentication_product_ids
+ .get_click_to_pay_connector_account_id()
+ .change_context(ApiErrorResponse::MissingRequiredField {
+ field_name: "authentication_product_ids",
+ })?;
+ let key_manager_state = &(state).into();
+
+ let merchant_connector_account = state
+ .store
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ key_manager_state,
+ merchant_id,
+ &click_to_pay_mca_id,
+ merchant_context.get_merchant_key_store(),
+ )
+ .await
+ .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: click_to_pay_mca_id.get_string_repr().to_string(),
+ })?;
+
+ let click_to_pay_metadata: hyperswitch_domain_models::payments::ClickToPayMetaData =
+ merchant_connector_account
+ .metadata
+ .clone()
+ .parse_value("ClickToPayMetaData")
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while parsing ClickToPayMetaData")?;
+ let transaction_currency = authentication
+ .currency
+ .ok_or(ApiErrorResponse::InternalServerError)
+ .attach_printable("currency is not present in payment_data.payment_intent")?;
+ let required_amount_type = common_utils::types::StringMajorUnitForConnector;
+ let amount = authentication
+ .amount
+ .ok_or(ApiErrorResponse::InternalServerError)
+ .attach_printable("amount is not present in authentication")?;
+ let transaction_amount = required_amount_type
+ .convert(amount, transaction_currency)
+ .change_context(ApiErrorResponse::AmountConversionFailed {
+ amount_type: "string major unit",
+ })?;
+
+ let customer_details_decrypted = authentication
+ .customer_details
+ .clone()
+ .async_lift(|inner| async {
+ domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
+ 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 decrypt email from authentication table")?;
+
+ let customer_details = customer_details_decrypted
+ .parse_value("CustomerData")
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while parsing customer data from authentication table")?;
+
+ validate_customer_details_for_click_to_pay(&customer_details)?;
+
+ let provider = merchant_connector_account
+ .get_ctp_service_provider()
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Error while parsing ctp service provider from merchant connector account",
+ )?;
+
+ let card_brands = [
+ common_enums::CardNetwork::Mastercard,
+ common_enums::CardNetwork::Visa,
+ ]
+ .iter()
+ .cloned()
+ .collect::<std::collections::HashSet<_>>();
+
+ Ok(
+ api_models::authentication::AuthenticationSessionToken::ClickToPay(Box::new(
+ payments::ClickToPaySessionResponse {
+ dpa_id: click_to_pay_metadata.dpa_id,
+ dpa_name: click_to_pay_metadata.dpa_name,
+ locale: click_to_pay_metadata.locale,
+ card_brands,
+ acquirer_bin: click_to_pay_metadata.acquirer_bin,
+ acquirer_merchant_id: click_to_pay_metadata.acquirer_merchant_id,
+ merchant_category_code: click_to_pay_metadata.merchant_category_code,
+ merchant_country_code: click_to_pay_metadata.merchant_country_code,
+ transaction_amount,
+ transaction_currency_code: transaction_currency,
+ phone_number: customer_details.phone.clone(),
+ email: customer_details.email.clone(),
+ phone_country_code: customer_details.phone_country_code.clone(),
+ provider,
+ dpa_client_id: click_to_pay_metadata.dpa_client_id.clone(),
+ },
+ )),
+ )
+}
diff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rs
index 12b173d35a..74a309b7fb 100644
--- a/crates/router/src/db/authentication.rs
+++ b/crates/router/src/db/authentication.rs
@@ -173,6 +173,7 @@ impl AuthenticationInterface for MockDb {
challenge_cancel: authentication.challenge_cancel,
challenge_code_reason: authentication.challenge_code_reason,
message_extension: authentication.message_extension,
+ customer_details: authentication.customer_details,
};
authentications.push(authentication.clone());
Ok(authentication)
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 117c9ac15f..24522270b6 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -3108,6 +3108,10 @@ impl Authentication {
web::resource("{merchant_id}/{authentication_id}/sync")
.route(web::post().to(authentication::authentication_sync)),
)
+ .service(
+ web::resource("/{authentication_id}/enabled_authn_methods_token")
+ .route(web::post().to(authentication::authentication_session_token)),
+ )
}
}
diff --git a/crates/router/src/routes/authentication.rs b/crates/router/src/routes/authentication.rs
index 04d71b4fa4..f0a12f3fd6 100644
--- a/crates/router/src/routes/authentication.rs
+++ b/crates/router/src/routes/authentication.rs
@@ -2,8 +2,8 @@ use actix_web::{web, HttpRequest, Responder};
use api_models::authentication::{AuthenticationAuthenticateRequest, AuthenticationCreateRequest};
#[cfg(feature = "v1")]
use api_models::authentication::{
- AuthenticationEligibilityRequest, AuthenticationSyncPostUpdateRequest,
- AuthenticationSyncRequest,
+ AuthenticationEligibilityRequest, AuthenticationSessionTokenRequest,
+ AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest,
};
use router_env::{instrument, tracing, Flow};
@@ -138,7 +138,7 @@ pub async fn authentication_sync(
common_utils::id_type::MerchantId,
common_utils::id_type::AuthenticationId,
)>,
- json_payload: web::Query<AuthenticationSyncRequest>,
+ json_payload: web::Json<AuthenticationSyncRequest>,
) -> impl Responder {
let flow = Flow::AuthenticationSync;
let api_auth = auth::ApiKeyAuth::default();
@@ -209,3 +209,47 @@ pub async fn authentication_sync_post_update(
))
.await
}
+
+#[cfg(feature = "v1")]
+#[instrument(skip_all, fields(flow = ?Flow::AuthenticationSessionToken))]
+pub async fn authentication_session_token(
+ state: web::Data<app::AppState>,
+ req: HttpRequest,
+ path: web::Path<common_utils::id_type::AuthenticationId>,
+ json_payload: web::Json<AuthenticationSessionTokenRequest>,
+) -> impl Responder {
+ let flow = Flow::AuthenticationSessionToken;
+ let authentication_id = path.into_inner();
+ let api_auth = auth::ApiKeyAuth::default();
+
+ let payload = AuthenticationSessionTokenRequest {
+ authentication_id: authentication_id.clone(),
+ ..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_session_core(
+ state,
+ merchant_context,
+ req,
+ )
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9f8a5add7d..33919ab27d 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -356,6 +356,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::AuthenticationSync
| Flow::AuthenticationSyncPostUpdate
| Flow::AuthenticationAuthenticate
+ | Flow::AuthenticationSessionToken
| Flow::AuthenticationEligibilityCheck
| Flow::AuthenticationRetrieveEligibilityCheck => Self::Authentication,
Flow::Proxy => Self::Proxy,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index dc5c84f6ab..8ad4bcea26 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -4383,6 +4383,14 @@ impl ClientSecretFetch for api_models::authentication::AuthenticationSyncRequest
}
}
+impl ClientSecretFetch for api_models::authentication::AuthenticationSessionTokenRequest {
+ 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.rs
index cdb9788fce..35434728b5 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -664,6 +664,8 @@ pub enum Flow {
AuthenticationSyncPostUpdate,
/// Authentication Authenticate flow
AuthenticationAuthenticate,
+ /// Authentication Session Token flow
+ AuthenticationSessionToken,
/// Authentication Eligibility Check flow
AuthenticationEligibilityCheck,
/// Authentication Retrieve Eligibility Check flow
diff --git a/migrations/2025-10-24-082437_add-customer-details-to-authentication/down.sql b/migrations/2025-10-24-082437_add-customer-details-to-authentication/down.sql
new file mode 100644
index 0000000000..a2b66d0f53
--- /dev/null
+++ b/migrations/2025-10-24-082437_add-customer-details-to-authentication/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE authentication DROP COLUMN IF EXISTS customer_details;
\ No newline at end of file
diff --git a/migrations/2025-10-24-082437_add-customer-details-to-authentication/up.sql b/migrations/2025-10-24-082437_add-customer-details-to-authentication/up.sql
new file mode 100644
index 0000000000..0282cdc3e7
--- /dev/null
+++ b/migrations/2025-10-24-082437_add-customer-details-to-authentication/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE authentication ADD COLUMN IF NOT EXISTS customer_details BYTEA DEFAULT NULL;
\ No newline at end of file