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(router): Add payment method tokenization granular flow (#10377)

Anurag Thakur017813e3d28f
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs
index 24b7d86400..898a00d950 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -153,6 +153,37 @@ impl UnifiedConnectorServiceClient {
}
}
+ /// Performs Payment Method Token Create
+ pub async fn payment_method_token_create(
+ &self,
+ pm_token_create_request: payments_grpc::PaymentServiceCreatePaymentMethodTokenRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<
+ tonic::Response<payments_grpc::PaymentServiceCreatePaymentMethodTokenResponse>,
+ > {
+ let mut request = tonic::Request::new(pm_token_create_request);
+
+ let connector_name = connector_auth_metadata.connector_name.clone();
+ let metadata =
+ build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
+ *request.metadata_mut() = metadata;
+
+ self.client
+ .clone()
+ .create_payment_method_token(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PaymentMethodTokenCreateFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="create_payment_method_token",
+ connector_name=?connector_name,
+ "UCS create_payment_method_token gRPC call failed"
+ )
+ })
+ }
+
/// Performs Payment Granular Authorize
pub async fn payment_authorize_granular(
&self,
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 429837e68c..07ec0990ad 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -417,6 +417,7 @@ impl TryFrom<&RouterData<flows::Session, PaymentsSessionData, response_types::Pa
#[derive(Debug, Clone, Serialize)]
pub struct PaymentMethodTokenizationData {
pub payment_method_data: PaymentMethodData,
+ pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub browser_info: Option<BrowserInformation>,
pub currency: storage_enums::Currency,
pub amount: Option<i64>,
@@ -441,6 +442,7 @@ impl TryFrom<SetupMandateRequestData> for PaymentMethodTokenizationData {
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
+ payment_method_type: data.payment_method_type,
})
}
}
@@ -460,6 +462,7 @@ impl<F> From<&RouterData<F, PaymentsAuthorizeData, response_types::PaymentsRespo
setup_future_usage: data.request.setup_future_usage,
setup_mandate_details: data.request.setup_mandate_details.clone(),
mandate_id: data.request.mandate_id.clone(),
+ payment_method_type: data.payment_method_type,
}
}
}
@@ -478,6 +481,7 @@ impl TryFrom<PaymentsAuthorizeData> for PaymentMethodTokenizationData {
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
+ payment_method_type: data.payment_method_type,
})
}
}
@@ -501,6 +505,7 @@ impl TryFrom<CompleteAuthorizeData> for PaymentMethodTokenizationData {
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
+ payment_method_type: data.payment_method_type,
})
}
}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 95e9d0e222..ca96fe5333 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -3722,6 +3722,7 @@ async fn create_single_use_tokenization_flow(
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
};
let payment_method_session_address = types::PaymentAddress::new(
diff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rs
index 31d45d593e..1765d26041 100644
--- a/crates/router/src/core/payments/gateway.rs
+++ b/crates/router/src/core/payments/gateway.rs
@@ -3,6 +3,7 @@ pub mod authorize_gateway;
pub mod context;
pub mod create_customer_gateway;
pub mod create_order_gateway;
+pub mod payment_method_token_create_gateway;
pub mod psync_gateway;
pub mod session_token_gateway;
use std::sync;
diff --git a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs
new file mode 100644
index 0000000000..854dcbff08
--- /dev/null
+++ b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs
@@ -0,0 +1,199 @@
+use std::str::FromStr;
+
+use async_trait::async_trait;
+use common_enums::{CallConnectorAction, ExecutionPath};
+use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};
+use hyperswitch_interfaces::{
+ api::gateway as payment_gateway,
+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
+ errors::ConnectorError,
+};
+use unified_connector_service_client::payments as payments_grpc;
+
+use crate::{
+ core::{
+ payments::gateway::context::RouterGatewayContext, unified_connector_service,
+ unified_connector_service::handle_unified_connector_service_response_for_payment_method_token_create,
+ },
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PaymentGateway Implementation for domain::PaymentMethodToken
+// =============================================================================
+
+/// Implementation of PaymentGateway for api::PaymentMethodToken flow
+#[async_trait]
+impl<RCD>
+ payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::PaymentMethodToken
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<
+ Self,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ >,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ >,
+ router_data: &RouterData<
+ Self,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ >,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PaymentMethodTokenizationData, types::PaymentsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let platform = context.platform;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let merchant_order_reference_id = header_payload.x_reference_id.clone();
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let pm_token_create_request =
+ payments_grpc::PaymentServiceCreatePaymentMethodTokenRequest::foreign_try_from(
+ router_data,
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payment Get Request")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ &platform,
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+ let merchant_reference_id = header_payload
+ .x_reference_id
+ .clone()
+ .or(merchant_order_reference_id)
+ .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
+ .transpose()
+ .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
+ .ok()
+ .flatten()
+ .map(ucs_types::UcsReferenceId::Payment);
+ let header_payload = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .lineage_ids(lineage_ids);
+ let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ router_data.clone(),
+ state,
+ pm_token_create_request,
+ header_payload,
+ |mut router_data, pm_token_create_request, grpc_headers| async move {
+ let response = Box::pin(client.payment_method_token_create(
+ pm_token_create_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to get payment")?;
+
+ let pm_token_create_response = response.into_inner();
+
+ let (router_data_response, status_code) =
+ handle_unified_connector_service_response_for_payment_method_token_create(
+ pm_token_create_response.clone(),
+ )
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = router_data_response.map(|(response, status)| {
+ router_data.status = status;
+ response
+ });
+ router_data.response = router_data_response;
+ router_data.payment_method_token = Some(
+ hyperswitch_domain_models::router_data::PaymentMethodToken::Token(
+ masking::Secret::new(pm_token_create_response.payment_method_token.clone()),
+ ),
+ );
+ router_data.connector_http_status_code = Some(status_code);
+
+ Ok((router_data, pm_token_create_response))
+ },
+ ))
+ .await
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+/// Implementation of FlowGateway for api::PaymentMethodToken
+///
+/// This allows the flow to provide its specific gateway based on execution path
+impl<RCD>
+ payment_gateway::FlowGateway<
+ SessionState,
+ RCD,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::PaymentMethodToken
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<
+ Self,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ >,
+{
+ fn get_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 066b443c07..ab67ab4630 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -1191,6 +1191,17 @@ pub fn handle_unified_connector_service_response_for_payment_post_authenticate(
Ok((router_data_response, status_code))
}
+pub fn handle_unified_connector_service_response_for_payment_method_token_create(
+ response: payments_grpc::PaymentServiceCreatePaymentMethodTokenResponse,
+) -> UnifiedConnectorServiceResult {
+ let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response =
+ Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
+
+ Ok((router_data_response, status_code))
+}
+
pub fn handle_unified_connector_service_response_for_payment_authenticate(
response: payments_grpc::PaymentServiceAuthenticateResponse,
) -> UnifiedConnectorServiceResult {
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index a591b9b04c..b7a1634a14 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -66,6 +66,78 @@ impl ForeignFrom<&AccessToken> for ConnectorState {
}
}
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ api::PaymentMethodToken,
+ router_request_types::PaymentMethodTokenizationData,
+ PaymentsResponseData,
+ >,
+ > for payments_grpc::PaymentServiceCreatePaymentMethodTokenRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+ fn foreign_try_from(
+ router_data: &RouterData<
+ api::PaymentMethodToken,
+ router_request_types::PaymentMethodTokenizationData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let connector_ref_id = Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.connector_request_reference_id.clone(),
+ )),
+ };
+
+ let merchant_account_metadata = router_data
+ .connector_meta_data
+ .as_ref()
+ .and_then(|val| val.peek().as_object())
+ .map(|map| {
+ map.iter()
+ .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
+ .collect::<HashMap<String, String>>()
+ })
+ .unwrap_or_default();
+
+ let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
+
+ let payment_method = router_data
+ .request
+ .payment_method_type
+ .map(|payment_method_type| {
+ unified_connector_service::build_unified_connector_service_payment_method(
+ router_data.request.payment_method_data.clone(),
+ Some(payment_method_type),
+ )
+ })
+ .transpose()?;
+
+ // TODO: Fix the type of address field in UCS request and pass address
+ // let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;
+
+ let amount = router_data.request.amount.ok_or(report!(
+ UnifiedConnectorServiceError::MissingRequiredField {
+ field_name: "amount"
+ }
+ ))?;
+
+ Ok(Self {
+ request_ref_id: Some(connector_ref_id),
+ merchant_account_metadata,
+ amount,
+ currency: currency.into(),
+ minor_amount: amount,
+ payment_method,
+ customer_name: None,
+ email: None,
+ customer_id: None,
+ address: None,
+ metadata: HashMap::new(),
+ })
+ }
+}
+
impl
transformers::ForeignTryFrom<(
&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
@@ -2752,6 +2824,44 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCreateOrderRespon
}
}
+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCreatePaymentMethodTokenResponse>
+ for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ response: payments_grpc::PaymentServiceCreatePaymentMethodTokenResponse,
+ ) -> Result<Self, Self::Error> {
+ let status_code = convert_connector_service_status_code(response.status_code)?;
+
+ let response = if response.error_code.is_some() {
+ Err(ErrorResponse {
+ code: response.error_code().to_owned(),
+ message: response.error_message().to_owned(),
+ reason: Some(response.error_message().to_owned()),
+ status_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ network_decline_code: None,
+ network_advice_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ } else {
+ // For connector PM token creation, we typically return a successful response with the connector payment method
+ // Since this is not a standard payment response, we'll create a simple success response
+ Ok((
+ PaymentsResponseData::TokenizationResponse {
+ token: response.payment_method_token,
+ },
+ AttemptStatus::Charged, // Assuming successful creation
+ ))
+ };
+
+ Ok(response)
+ }
+}
+
impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthenticateResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{
diff --git a/crates/router/tests/connectors/square.rs b/crates/router/tests/connectors/square.rs
index 760e8ebdae..86bc3a3d71 100644
--- a/crates/router/tests/connectors/square.rs
+++ b/crates/router/tests/connectors/square.rs
@@ -72,6 +72,7 @@ fn token_details() -> Option<types::PaymentMethodTokenizationData> {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
})
}
@@ -450,6 +451,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
}),
get_default_payment_info(None),
)
@@ -486,6 +488,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
}),
get_default_payment_info(None),
)
@@ -522,6 +525,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
}),
get_default_payment_info(None),
)
diff --git a/crates/router/tests/connectors/stax.rs b/crates/router/tests/connectors/stax.rs
index 69e241edd3..1b57494b84 100644
--- a/crates/router/tests/connectors/stax.rs
+++ b/crates/router/tests/connectors/stax.rs
@@ -77,6 +77,7 @@ fn token_details() -> Option<types::PaymentMethodTokenizationData> {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
})
}
@@ -492,6 +493,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
}),
get_default_payment_info(connector_customer_id, None),
)
@@ -535,6 +537,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
}),
get_default_payment_info(connector_customer_id, None),
)
@@ -578,6 +581,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
}),
get_default_payment_info(connector_customer_id, None),
)
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 0205242c4b..d25baba2f9 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -1147,6 +1147,7 @@ impl Default for TokenType {
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
+ payment_method_type: None,
};
Self(data)
}