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: add modular payment method client (#10960)

Kashif3df7b6e8bf75
diff --git a/Cargo.lock b/Cargo.lock
index 088bd6bef0..f364c16988 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4425,6 +4425,7 @@ dependencies = [
"thiserror 1.0.69",
"time",
"tokio 1.48.0",
+ "url",
]
[[package]]
@@ -6126,6 +6127,7 @@ dependencies = [
"serde_json",
"storage_impl",
"thiserror 1.0.69",
+ "url",
]
[[package]]
diff --git a/config/config.example.toml b/config/config.example.toml
index 095eccaf95..870b11d2bb 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -1364,3 +1364,8 @@ org_id = "your_org_id" # Organization ID in Superpositi
workspace_id = "your_workspace_id" # Workspace ID in Superposition
polling_interval = 15 # Polling interval in seconds for configuration updates
request_timeout = 60 # Request timeout in seconds for Superposition API calls (optional, default: none)
+
+[micro_services]
+# Base URLs for modular microservices
+# (e.g., payment-methods, customers, routing, etc.)
+payment_methods_base_url = "http://localhost:8082"
diff --git a/config/development.toml b/config/development.toml
index a6ee93891b..9f4aae48a4 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -1480,3 +1480,6 @@ org_id = "localorg" # Organization ID in Superposition
workspace_id = "dev" # Workspace ID in Superposition
polling_interval = 15 # Polling interval in seconds for configuration updates
# request_timeout = # Request timeout in seconds for Superposition API calls (optional, default: none)
+
+[micro_services]
+payment_methods_base_url = "http://localhost:8082"
diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml
index 38403970b8..90e7d67262 100644
--- a/crates/hyperswitch_interfaces/Cargo.toml
+++ b/crates/hyperswitch_interfaces/Cargo.toml
@@ -29,9 +29,11 @@ serde_json = "1.0.140"
strum = { version = "0.26", features = ["derive"] }
thiserror = "1.0.69"
time = "0.3.41"
+url = { version = "2.5.4", features = ["serde"] }
unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "7b0308793095fd908fae2fe9bc3fa6ee39f73693", package = "rust-grpc-client" }
unified-connector-service-masking = { git = "https://github.com/juspay/hyperswitch", tag = "2025.11.24.0", package = "masking" }
tokio = { version = "1.45.1", features = ["macros", "rt-multi-thread"] }
+
# First party crates
hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
masking = { version = "0.1.0", path = "../masking" }
diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs
index 6f7fb34eae..bc7c92f49a 100644
--- a/crates/hyperswitch_interfaces/src/lib.rs
+++ b/crates/hyperswitch_interfaces/src/lib.rs
@@ -25,6 +25,8 @@ pub mod helpers;
/// connector integrity check interface
pub mod integrity;
pub mod metrics;
+/// Microservice-specific flow modules
+pub mod micro_service;
pub mod secrets_interface;
pub mod types;
/// ucs handlers
diff --git a/crates/hyperswitch_interfaces/src/micro_service.rs b/crates/hyperswitch_interfaces/src/micro_service.rs
new file mode 100644
index 0000000000..4a9360a09b
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/micro_service.rs
@@ -0,0 +1,60 @@
+//! Generic microservice client framework (typestate pipeline + macro helpers).
+//!
+//! This module is microservice-agnostic. Domain-specific flows and lightweight clients should
+//! live in their own crates and implement [`MicroserviceClient`].
+//!
+//! # Examples
+//!
+//! ```rust,ignore
+//! use common_utils::request::Headers;
+//! use hyperswitch_interfaces::{
+//! api_client::ApiClientWrapper,
+//! micro_service::{MicroserviceClient, MicroserviceClientError},
+//! };
+//! use router_env::RequestIdentifier;
+//! use url::Url;
+//!
+//! struct ExampleClient<'a> {
+//! base_url: &'a Url,
+//! parent_headers: &'a Headers,
+//! trace: &'a RequestIdentifier,
+//! }
+//!
+//! impl<'a> MicroserviceClient for ExampleClient<'a> {
+//! fn base_url(&self) -> &Url { self.base_url }
+//! fn parent_headers(&self) -> &Headers { self.parent_headers }
+//! fn trace(&self) -> &RequestIdentifier { self.trace }
+//! }
+//!
+//! async fn call_flow(
+//! state: &dyn ApiClientWrapper,
+//! client: &ExampleClient<'_>,
+//! ) -> Result<(), MicroserviceClientError> {
+//! // ExampleFlow::call(state, client, flow).await?;
+//! Ok(())
+//! }
+//! ```
+
+mod error;
+mod executor;
+mod macros;
+mod state;
+
+use common_utils::request::Headers;
+pub use error::{MicroserviceClientError, MicroserviceClientErrorKind};
+pub use executor::execute_microservice_operation;
+use router_env::RequestIdentifier;
+pub use state::{ClientOperation, Executed, TransformedRequest, TransformedResponse, Validated};
+use url::Url;
+
+/// Minimal context required to execute a microservice flow.
+///
+/// Implement this for lightweight client wrappers that carry base URL, headers, and trace config.
+pub trait MicroserviceClient {
+ /// Base URL for the microservice.
+ fn base_url(&self) -> &Url;
+ /// Parent headers to forward to the microservice.
+ fn parent_headers(&self) -> &Headers;
+ /// Trace identifier configuration.
+ fn trace(&self) -> &RequestIdentifier;
+}
diff --git a/crates/hyperswitch_interfaces/src/micro_service/error.rs b/crates/hyperswitch_interfaces/src/micro_service/error.rs
new file mode 100644
index 0000000000..3490c1b99d
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/micro_service/error.rs
@@ -0,0 +1,48 @@
+use thiserror::Error;
+
+/// Error categories for the microservice client pipeline.
+#[derive(Debug, Error)]
+pub enum MicroserviceClientErrorKind {
+ /// Request validation or request-shape errors.
+ #[error("Invalid request: {0}")]
+ InvalidRequest(String),
+
+ /// Transport or network failures.
+ #[error("Transport error: {0}")]
+ Transport(String),
+
+ /// Non-2xx response from upstream service.
+ #[error("Upstream error: status={status}, body={body}")]
+ Upstream {
+ /// HTTP status code returned by the upstream service.
+ status: u16,
+ /// Response body for debugging.
+ body: String,
+ },
+
+ /// Request serialization failures.
+ #[error("Serialize error: {0}")]
+ Serialize(String),
+
+ /// Response deserialization failures.
+ #[error("Deserialize error: {0}")]
+ Deserialize(String),
+
+ /// Failures while transforming upstream response into v1 output.
+ #[error("Response transform error: {0}")]
+ ResponseTransform(String),
+
+ /// Client-specific errors not covered by the generic categories.
+ #[error("Client specific error: {0}")]
+ ClientSpecific(String),
+}
+
+/// Error wrapper carrying the operation name and error category.
+#[derive(Debug, Error)]
+#[error("Microservice client error for {operation}: {kind}")]
+pub struct MicroserviceClientError {
+ /// Operation name for logging and error attribution.
+ pub operation: String,
+ /// Error category for the failure.
+ pub kind: MicroserviceClientErrorKind,
+}
diff --git a/crates/hyperswitch_interfaces/src/micro_service/executor.rs b/crates/hyperswitch_interfaces/src/micro_service/executor.rs
new file mode 100644
index 0000000000..47a1f5f917
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/micro_service/executor.rs
@@ -0,0 +1,200 @@
+use common_utils::{
+ consts::TENANT_HEADER,
+ request::{Headers, Request},
+};
+use masking::Maskable;
+use router_env::{logger, RequestIdentifier};
+use url::Url;
+
+use super::{
+ error::{MicroserviceClientError, MicroserviceClientErrorKind},
+ state::{ClientOperation, Executed, TransformedRequest, TransformedResponse, Validated},
+ MicroserviceClient,
+};
+use crate::api_client::{call_connector_api, ApiClientWrapper};
+
+impl<O: ClientOperation> Validated<O> {
+ /// Validate the flow and move into the `Validated` state.
+ pub fn new(op: O, request: O::V1Request) -> Result<Self, MicroserviceClientError> {
+ let operation = std::any::type_name::<O>();
+ op.validate(&request).map_err(|err| {
+ logger::warn!(operation, error = ?err, "microservice validation failed");
+ err
+ })?;
+ Ok(Self { op, request })
+ }
+
+ /// Transform the validated flow into a request payload.
+ pub fn into_transformed_request(
+ self,
+ ) -> Result<TransformedRequest<O>, MicroserviceClientError> {
+ let operation = std::any::type_name::<O>();
+ let request = self.op.transform_request(&self.request).map_err(|err| {
+ logger::warn!(
+ operation,
+ error = ?err,
+ "microservice request transform failed"
+ );
+ err
+ })?;
+ Ok(TransformedRequest {
+ op: self.op,
+ request,
+ })
+ }
+}
+
+impl<O: ClientOperation> TransformedRequest<O> {
+ /// Execute the HTTP call for this operation and capture the raw response payload.
+ pub async fn execute(
+ self,
+ state: &dyn ApiClientWrapper,
+ base_url: &Url,
+ parent_headers: Headers,
+ trace_header: &RequestIdentifier,
+ ) -> Result<Executed<O>, MicroserviceClientError> {
+ let operation = std::any::type_name::<O>();
+ // Step 1: Build path and URL.
+ let path = {
+ let mut path = O::PATH_TEMPLATE.to_string();
+ for (key, value) in self.op.path_params(&self.request) {
+ let token = format!("{{{key}}}");
+ path = path.replace(&token, &value);
+ }
+ path
+ };
+ let url = base_url.join(&path).map_err(|e| {
+ logger::error!(operation, error = ?e, "microservice URL join failed");
+ MicroserviceClientError {
+ operation: operation.to_string(),
+ kind: MicroserviceClientErrorKind::Transport(format!(
+ "Failed to construct URL: {e}"
+ )),
+ }
+ })?;
+
+ // Step 2: Build headers and inject trace/request/tenant context.
+ let mut http_request = Request::new(O::METHOD, url.as_str());
+ http_request.headers = parent_headers;
+ {
+ let header_name = trace_header.header_name();
+ let existing_id = state.get_request_id();
+ let (trace_id, generated) = trace_header
+ .id_reuse_strategy()
+ .get_or_create_request_id(existing_id.as_ref());
+ if generated {
+ logger::debug!(
+ operation,
+ generated_id = %trace_id,
+ "trace header generated new request id"
+ );
+ }
+
+ http_request.headers.insert((
+ header_name.to_string(),
+ Maskable::Normal(trace_id.to_string()),
+ ));
+
+ let tenant_id = state.get_tenant().tenant_id.get_string_repr().to_string();
+ if !tenant_id.is_empty() {
+ http_request
+ .headers
+ .insert((TENANT_HEADER.to_string(), Maskable::Normal(tenant_id)));
+ }
+ }
+
+ // Step 3: Attach body (if any).
+ if let Some(body) = self.op.body(self.request) {
+ http_request.set_body(body);
+ }
+
+ // Step 4: Execute request and decode response.
+ let response = call_connector_api(state, http_request, operation)
+ .await
+ .map_err(|e| {
+ logger::error!(operation, error = ?e, "microservice request failed");
+ MicroserviceClientError {
+ operation: operation.to_string(),
+ kind: MicroserviceClientErrorKind::Transport(format!(
+ "Connector API error: {e}"
+ )),
+ }
+ })?;
+
+ match response {
+ Ok(success) => serde_json::from_slice(&success.response).map_err(|e| {
+ logger::error!(
+ operation,
+ error = ?e,
+ "microservice response decode failed"
+ );
+ MicroserviceClientError {
+ operation: operation.to_string(),
+ kind: MicroserviceClientErrorKind::Deserialize(format!(
+ "Failed to parse response: {e}"
+ )),
+ }
+ }),
+ Err(err_resp) => {
+ logger::warn!(
+ operation,
+ status = err_resp.status_code,
+ "microservice upstream error"
+ );
+ let body = String::from_utf8_lossy(&err_resp.response);
+ Err(MicroserviceClientError {
+ operation: operation.to_string(),
+ kind: MicroserviceClientErrorKind::Upstream {
+ status: err_resp.status_code,
+ body: body.chars().take(500).collect(),
+ },
+ })
+ }
+ }
+ .map(|response| Executed {
+ op: self.op,
+ response,
+ })
+ }
+}
+
+impl<O: ClientOperation> Executed<O> {
+ /// Transform the upstream response into the v1 response shape.
+ pub fn into_transformed_response(
+ self,
+ ) -> Result<TransformedResponse<O>, MicroserviceClientError> {
+ let operation = std::any::type_name::<O>();
+ let output = self.op.transform_response(self.response).map_err(|err| {
+ logger::error!(
+ operation,
+ error = ?err,
+ "microservice response transform failed"
+ );
+ err
+ })?;
+ Ok(TransformedResponse {
+ output,
+ _op: std::marker::PhantomData,
+ })
+ }
+}
+
+/// Execute the full pipeline: validate → transform → execute → transform.
+pub async fn execute_microservice_operation<O: ClientOperation>(
+ state: &dyn ApiClientWrapper,
+ client: &impl MicroserviceClient,
+ request: O::V1Request,
+) -> Result<O::V1Response, MicroserviceClientError> {
+ let op = O::from_request(&request);
+ let validated = Validated::new(op, request)?;
+ let transformed = validated.into_transformed_request()?;
+ let executed = transformed
+ .execute(
+ state,
+ client.base_url(),
+ client.parent_headers().clone(),
+ client.trace(),
+ )
+ .await?;
+ Ok(executed.into_transformed_response()?.output)
+}
diff --git a/crates/hyperswitch_interfaces/src/micro_service/macros.rs b/crates/hyperswitch_interfaces/src/micro_service/macros.rs
new file mode 100644
index 0000000000..c8cc52a0ef
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/micro_service/macros.rs
@@ -0,0 +1,146 @@
+/// Generate a `ClientOperation` impl and a `call` helper for a flow type.
+///
+/// # Examples
+///
+/// ```rust
+/// use common_utils::request::{Headers, Method, RequestContent};
+/// use hyperswitch_interfaces::micro_service::MicroserviceClient;
+/// use router_env::RequestIdentifier;
+/// use url::Url;
+///
+/// struct ExampleFlow;
+/// struct ExampleV1Request;
+/// struct ExampleV2Request;
+/// struct ExampleV2Response;
+/// struct ExampleResponse;
+///
+/// struct ExampleClient<'a> {
+/// base_url: &'a Url,
+/// headers: &'a Headers,
+/// trace: &'a RequestIdentifier,
+/// }
+///
+/// impl<'a> MicroserviceClient for ExampleClient<'a> {
+/// fn base_url(&self) -> &Url { self.base_url }
+/// fn parent_headers(&self) -> &Headers { self.headers }
+/// fn trace(&self) -> &RequestIdentifier { self.trace }
+/// }
+///
+/// impl TryFrom<&ExampleV1Request> for ExampleV2Request {
+/// type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;
+///
+/// fn try_from(_: &ExampleV1Request) -> Result<Self, Self::Error> {
+/// Ok(Self)
+/// }
+/// }
+///
+/// impl TryFrom<ExampleV2Response> for ExampleResponse {
+/// type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;
+///
+/// fn try_from(_: ExampleV2Response) -> Result<Self, Self::Error> {
+/// Ok(Self)
+/// }
+/// }
+///
+/// impl_microservice_flow!(
+/// ExampleFlow,
+/// method = Method::Post,
+/// path = "/v2/example",
+/// v1_request = ExampleV1Request,
+/// v2_request = ExampleV2Request,
+/// v2_response = ExampleV2Response,
+/// v1_response = ExampleResponse,
+/// client = ExampleClient<'_>,
+/// body = |_, _| Some(RequestContent::Json(Box::new(serde_json::json!({}))))
+/// );
+/// ```
+#[macro_export]
+macro_rules! impl_microservice_flow {
+ (
+ $flow:ty,
+ method = $method:expr,
+ path = $path:expr,
+ v1_request = $v1_req:ty,
+ v2_request = $v2_req:ty,
+ v2_response = $v2_resp:ty,
+ v1_response = $v1_resp:ty,
+ client = $client_ty:ty
+ $(, body = $body_fn:expr)?
+ $(, path_params = $path_params_fn:expr)?
+ $(, validate = $validate_fn:expr)?
+ ) => {
+ #[async_trait::async_trait]
+ impl $crate::micro_service::ClientOperation for $flow {
+ const METHOD: common_utils::request::Method = $method;
+ const PATH_TEMPLATE: &'static str = $path;
+
+ type V1Response = $v1_resp;
+ type V1Request = $v1_req;
+ type V2Request = $v2_req;
+ type V2Response = $v2_resp;
+
+ fn validate(
+ &self,
+ request: &Self::V1Request,
+ ) -> Result<(), $crate::micro_service::MicroserviceClientError> {
+ $($validate_fn(self, request)?;)?
+ Ok(())
+ }
+
+ fn from_request(_request: &Self::V1Request) -> Self {
+ Self
+ }
+
+ fn transform_request(
+ &self,
+ request: &Self::V1Request,
+ ) -> Result<Self::V2Request, $crate::micro_service::MicroserviceClientError> {
+ <Self::V2Request as TryFrom<&Self::V1Request>>::try_from(request)
+ }
+
+ fn transform_response(
+ &self,
+ response: Self::V2Response,
+ ) -> Result<Self::V1Response, $crate::micro_service::MicroserviceClientError> {
+ <Self::V1Response as TryFrom<Self::V2Response>>::try_from(response)
+ }
+
+ $(
+ fn body(
+ &self,
+ request: Self::V2Request,
+ ) -> Option<common_utils::request::RequestContent> {
+ $body_fn(self, request)
+ }
+ )?
+
+ $(
+ fn path_params(
+ &self,
+ request: &Self::V2Request,
+ ) -> Vec<(&'static str, String)> {
+ $path_params_fn(self, request)
+ }
+ )?
+ }
+
+ impl $flow {
+ /// Execute the flow using the generic microservice pipeline.
+ pub async fn call(
+ state: &dyn $crate::api_client::ApiClientWrapper,
+ client: &$client_ty,
+ request: <Self as $crate::micro_service::ClientOperation>::V1Request,
+ ) -> Result<
+ <Self as $crate::micro_service::ClientOperation>::V1Response,
+ $crate::micro_service::MicroserviceClientError,
+ > {
+ $crate::micro_service::execute_microservice_operation::<Self>(
+ state,
+ client,
+ request,
+ )
+ .await
+ }
+ }
+ };
+}
diff --git a/crates/hyperswitch_interfaces/src/micro_service/state.rs b/crates/hyperswitch_interfaces/src/micro_service/state.rs
new file mode 100644
index 0000000000..9e2ecb451e
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/micro_service/state.rs
@@ -0,0 +1,117 @@
+use common_utils::request::{Method, RequestContent};
+use serde::de::DeserializeOwned;
+
+use super::error::MicroserviceClientError;
+
+/// Contract for a single microservice flow.
+///
+/// This trait defines the compile-time shape of a flow: how it validates inputs, how it derives a
+/// modular service request payload, and how it maps the upstream response back into a v1 response.
+/// The
+/// executor orchestrates the pipeline and enforces the order:
+///
+/// Validated -> TransformedRequest -> Executed -> TransformedResponse
+#[async_trait::async_trait]
+pub trait ClientOperation {
+ /// HTTP method for this flow, used by the executor when building the request.
+ ///
+ /// This is a compile-time constant so the executor can remain generic.
+ const METHOD: Method;
+ /// Path template for this flow (e.g., `/v2/payment-methods/{id}`).
+ ///
+ /// Use `{token}` placeholders and provide values via `path_params`.
+ /// The executor performs string substitution for each token.
+ const PATH_TEMPLATE: &'static str;
+
+ /// V1-facing request type for the flow.
+ ///
+ /// Use `()` for flows that do not require an input payload.
+ type V1Request;
+ /// V1-facing response type returned by the flow.
+ ///
+ /// This is the final output returned by `FlowType::call`, after all transforms.
+ type V1Response;
+ /// Modular service request payload produced by request transformation.
+ ///
+ /// This is not sent automatically; it is passed into `body()` and/or `path_params()`.
+ type V2Request;
+ /// Modular service response payload returned by the upstream service.
+ ///
+ /// The executor deserializes this from the upstream HTTP response body.
+ type V2Response: DeserializeOwned;
+
+ /// Validate inputs before building a request.
+ ///
+ /// Use this to reject invalid IDs or missing required fields. Failures are classified as
+ /// client-side errors in the pipeline.
+ fn validate(&self, request: &Self::V1Request) -> Result<(), MicroserviceClientError>;
+ /// Build the flow instance from a V1 request.
+ ///
+ /// This keeps the `call` entrypoint decoupled from the flow struct layout.
+ fn from_request(request: &Self::V1Request) -> Self;
+ /// Transform flow inputs into a modular service request payload.
+ ///
+ /// Should be a pure conversion without side effects. Do not perform I/O here.
+ fn transform_request(
+ &self,
+ request: &Self::V1Request,
+ ) -> Result<Self::V2Request, MicroserviceClientError>;
+ /// Transform modular service response payload into V1 response.
+ ///
+ /// Treat failures here as server-side transform errors. Keep it deterministic.
+ fn transform_response(
+ &self,
+ response: Self::V2Response,
+ ) -> Result<Self::V1Response, MicroserviceClientError>;
+
+ /// Optional path parameters for template substitution.
+ ///
+ /// Keys should correspond to `{token}` placeholders in `PATH_TEMPLATE`.
+ /// This is typically used for resource IDs.
+ fn path_params(&self, _request: &Self::V2Request) -> Vec<(&'static str, String)> {
+ Vec::new()
+ }
+
+ /// Optional body for the outbound request.
+ ///
+ /// Return `None` for methods that do not send a body.
+ fn body(&self, _request: Self::V2Request) -> Option<RequestContent> {
+ None
+ }
+}
+
+/// State after validation succeeds.
+#[derive(Debug)]
+pub struct Validated<O: ClientOperation> {
+ /// Flow instance.
+ pub(crate) op: O,
+ /// V1 request payload.
+ pub(crate) request: O::V1Request,
+}
+
+/// State after request transformation.
+#[derive(Debug)]
+pub struct TransformedRequest<O: ClientOperation> {
+ /// Flow instance.
+ pub(crate) op: O,
+ /// Transformed request payload.
+ pub(crate) request: O::V2Request,
+}
+
+/// State after executing the HTTP request.
+#[derive(Debug)]
+pub struct Executed<O: ClientOperation> {
+ /// Flow instance.
+ pub(crate) op: O,
+ /// Upstream response payload.
+ pub(crate) response: O::V2Response,
+}
+
+/// State after transforming into the V1 response.
+#[derive(Debug)]
+pub struct TransformedResponse<O: ClientOperation> {
+ /// Final V1 response payload.
+ pub output: O::V1Response,
+ /// Marker to retain the flow type.
+ pub(crate) _op: std::marker::PhantomData<O>,
+}
diff --git a/crates/payment_methods/Cargo.toml b/crates/payment_methods/Cargo.toml
index 9e25a8375d..f147af26f0 100644
--- a/crates/payment_methods/Cargo.toml
+++ b/crates/payment_methods/Cargo.toml
@@ -18,6 +18,7 @@ rdkafka = "0.36.2"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
thiserror = "1.0.69"
+url = { version = "2.5.4", features = ["serde"] }
api_models = { version = "0.1.0", path = "../api_models", features = ["errors", "control_center_theme"] }
cards = { version = "0.1.0", path = "../cards" }
diff --git a/crates/payment_methods/src/client.rs b/crates/payment_methods/src/client.rs
new file mode 100644
index 0000000000..975dbf6c9d
--- /dev/null
+++ b/crates/payment_methods/src/client.rs
@@ -0,0 +1,60 @@
+//! Payment method microservice flows and lightweight client context.
+
+/// Create payment method flow.
+pub mod create;
+/// Delete payment method flow.
+pub mod delete;
+/// Retrieve payment method flow.
+pub mod retrieve;
+/// Update payment method flow.
+pub mod update;
+
+use common_utils::request::Headers;
+pub use create::{CreatePaymentMethod, CreatePaymentMethodV1Request};
+pub use delete::{DeletePaymentMethod, DeletePaymentMethodV1Request};
+use hyperswitch_interfaces::micro_service::MicroserviceClient;
+pub use retrieve::{RetrievePaymentMethod, RetrievePaymentMethodV1Request};
+use router_env::RequestIdentifier;
+pub use update::{UpdatePaymentMethod, UpdatePaymentMethodV1Request};
+
+use crate::configs::ModularPaymentMethodServiceUrl;
+
+#[derive(Debug)]
+/// Lightweight client context for payment method microservice calls.
+pub struct PaymentMethodClient<'a> {
+ /// Base URL for the payment method service.
+ pub base_url: &'a ModularPaymentMethodServiceUrl,
+ /// Parent headers to propagate to the microservice.
+ pub parent_headers: &'a Headers,
+ /// Trace configuration for request correlation.
+ pub trace: &'a RequestIdentifier,
+}
+
+impl<'a> PaymentMethodClient<'a> {
+ /// Create a new client with base URL, parent headers, and trace configuration.
+ pub fn new(
+ base_url: &'a ModularPaymentMethodServiceUrl,
+ parent_headers: &'a Headers,
+ trace: &'a RequestIdentifier,
+ ) -> Self {
+ Self {
+ base_url,
+ parent_headers,
+ trace,
+ }
+ }
+}
+
+impl<'a> MicroserviceClient for PaymentMethodClient<'a> {
+ fn base_url(&self) -> &url::Url {
+ self.base_url.as_ref()
+ }
+
+ fn parent_headers(&self) -> &Headers {
+ self.parent_headers
+ }
+
+ fn trace(&self) -> &RequestIdentifier {
+ self.trace
+ }
+}
diff --git a/crates/payment_methods/src/client/create.rs b/crates/payment_methods/src/client/create.rs
new file mode 100644
index 0000000000..ce321deefa
--- /dev/null
+++ b/crates/payment_methods/src/client/create.rs
@@ -0,0 +1,83 @@
+//! Create payment method flow types and dummy models.
+
+use common_utils::request::{Method, RequestContent};
+use hyperswitch_interfaces::micro_service::MicroserviceClientError;
+use serde::Deserialize;
+use serde_json::Value;
+
+/// V1-facing create flow type.
+#[derive(Debug)]
+pub struct CreatePaymentMethod;
+
+/// V1-facing create request payload.
+#[derive(Debug)]
+pub struct CreatePaymentMethodV1Request {
+ /// Raw payload forwarded to the modular service.
+ pub payload: Value,
+}
+
+const DUMMY_PM_ID: &str = "pm_dummy";
+/// Dummy modular service request payload.
+#[derive(Clone, Debug)]
+// TODO: replace dummy request types with real v1/modular models.
+pub struct CreatePaymentMethodV2Request {
+ /// Payload to send in the request body.
+ pub payload: Value,
+}
+
+/// Dummy modular service response payload.
+#[derive(Clone, Debug, Deserialize)]
+// TODO: replace dummy response types with real v1/modular models.
+pub struct CreatePaymentMethodV2Response {
+ /// Dummy identifier returned by the modular service.
+ pub id: String,
+}
+
+/// V1-facing create response (dummy for now).
+#[derive(Clone, Debug)]
+// TODO: replace dummy response types with real v1/modular models.
+pub struct CreatePaymentMethodResponse {
+ /// V1 payment method identifier.
+ pub payment_method_id: String,
+ /// Dummy delete marker (unused).
+ pub deleted: Option<bool>,
+}
+
+impl TryFrom<&CreatePaymentMethodV1Request> for CreatePaymentMethodV2Request {
+ type Error = MicroserviceClientError;
+
+ fn try_from(value: &CreatePaymentMethodV1Request) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payload: value.payload.clone(),
+ })
+ }
+}
+
+impl TryFrom<CreatePaymentMethodV2Response> for CreatePaymentMethodResponse {
+ type Error = MicroserviceClientError;
+
+ fn try_from(_: CreatePaymentMethodV2Response) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_id: DUMMY_PM_ID.to_string(),
+ deleted: None,
+ })
+ }
+}
+
+impl CreatePaymentMethod {
+ fn build_body(&self, request: CreatePaymentMethodV2Request) -> Option<RequestContent> {
+ Some(RequestContent::Json(Box::new(request.payload)))
+ }
+}
+
+hyperswitch_interfaces::impl_microservice_flow!(
+ CreatePaymentMethod,
+ method = Method::Post,
+ path = "/v2/payment-methods",
+ v1_request = CreatePaymentMethodV1Request,
+ v2_request = CreatePaymentMethodV2Request,
+ v2_response = CreatePaymentMethodV2Response,
+ v1_response = CreatePaymentMethodResponse,
+ client = crate::client::PaymentMethodClient<'_>,
+ body = CreatePaymentMethod::build_body
+);
diff --git a/crates/payment_methods/src/client/delete.rs b/crates/payment_methods/src/client/delete.rs
new file mode 100644
index 0000000000..f990e9adbc
--- /dev/null
+++ b/crates/payment_methods/src/client/delete.rs
@@ -0,0 +1,108 @@
+//! Delete payment method flow types and dummy models.
+
+use api_models::payment_methods::PaymentMethodId;
+use common_utils::request::Method;
+use hyperswitch_interfaces::micro_service::{MicroserviceClientError, MicroserviceClientErrorKind};
+use serde::Deserialize;
+
+const DUMMY_PM_ID: &str = "pm_dummy";
+
+/// V1-facing delete flow type.
+#[derive(Debug)]
+pub struct DeletePaymentMethod;
+
+/// V1-facing delete request payload.
+#[derive(Debug)]
+pub struct DeletePaymentMethodV1Request {
+ /// Identifier for the payment method to delete.
+ pub payment_method_id: PaymentMethodId,
+}
+
+/// Dummy modular service request payload.
+#[derive(Clone, Debug)]
+// TODO: replace dummy request types with real v1/modular models.
+pub struct DeletePaymentMethodV2Request {
+ /// Identifier for the payment method to delete.
+ pub payment_method_id: PaymentMethodId,
+}
+
+/// Dummy modular service response payload.
+#[derive(Clone, Debug, Deserialize)]
+// TODO: replace dummy response types with real v1/modular models.
+pub struct DeletePaymentMethodV2Response {
+ /// Dummy identifier returned by the modular service.
+ pub id: String,
+}
+
+/// V1-facing delete response (dummy for now).
+#[derive(Clone, Debug)]
+// TODO: replace dummy response types with real v1/modular models.
+pub struct DeletePaymentMethodResponse {
+ /// V1 payment method identifier.
+ pub payment_method_id: String,
+ /// Dummy delete marker.
+ pub deleted: Option<bool>,
+}
+
+impl TryFrom<&DeletePaymentMethodV1Request> for DeletePaymentMethodV2Request {
+ type Error = MicroserviceClientError;
+
+ fn try_from(value: &DeletePaymentMethodV1Request) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_id: value.payment_method_id.clone(),
+ })
+ }
+}
+
+impl TryFrom<DeletePaymentMethodV2Response> for DeletePaymentMethodResponse {
+ type Error = MicroserviceClientError;
+
+ fn try_from(_: DeletePaymentMethodV2Response) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_id: DUMMY_PM_ID.to_string(),
+ deleted: Some(true),
+ })
+ }
+}
+
+impl DeletePaymentMethod {
+ fn validate_request(
+ &self,
+ request: &DeletePaymentMethodV1Request,
+ ) -> Result<(), MicroserviceClientError> {
+ if request
+ .payment_method_id
+ .payment_method_id
+ .trim()
+ .is_empty()
+ {
+ return Err(MicroserviceClientError {
+ operation: std::any::type_name::<Self>().to_string(),
+ kind: MicroserviceClientErrorKind::InvalidRequest(
+ "Payment method ID cannot be empty".to_string(),
+ ),
+ });
+ }
+ Ok(())
+ }
+
+ fn build_path_params(
+ &self,
+ request: &DeletePaymentMethodV2Request,
+ ) -> Vec<(&'static str, String)> {
+ vec![("id", request.payment_method_id.payment_method_id.clone())]
+ }
+}
+
+hyperswitch_interfaces::impl_microservice_flow!(
+ DeletePaymentMethod,
+ method = Method::Delete,
+ path = "/v2/payment-methods/{id}",
+ v1_request = DeletePaymentMethodV1Request,
+ v2_request = DeletePaymentMethodV2Request,
+ v2_response = DeletePaymentMethodV2Response,
+ v1_response = DeletePaymentMethodResponse,
+ client = crate::client::PaymentMethodClient<'_>,
+ path_params = DeletePaymentMethod::build_path_params,
+ validate = DeletePaymentMethod::validate_request
+);
diff --git a/crates/payment_methods/src/client/retrieve.rs b/crates/payment_methods/src/client/retrieve.rs
new file mode 100644
index 0000000000..224fad3b40
--- /dev/null
+++ b/crates/payment_methods/src/client/retrieve.rs
@@ -0,0 +1,108 @@
+//! Retrieve payment method flow types and dummy models.
+
+use api_models::payment_methods::PaymentMethodId;
+use common_utils::request::Method;
+use hyperswitch_interfaces::micro_service::{MicroserviceClientError, MicroserviceClientErrorKind};
+use serde::Deserialize;
+
+const DUMMY_PM_ID: &str = "pm_dummy";
+
+/// V1-facing retrieve flow type.
+#[derive(Debug)]
+pub struct RetrievePaymentMethod;
+
+/// V1-facing retrieve request payload.
+#[derive(Debug)]
+pub struct RetrievePaymentMethodV1Request {
+ /// Identifier for the payment method to fetch.
+ pub payment_method_id: PaymentMethodId,
+}
+
+/// Dummy modular service request payload.
+#[derive(Clone, Debug)]
+// TODO: replace dummy request types with real v1/modular models.
+pub struct RetrievePaymentMethodV2Request {
+ /// Identifier for the payment method to fetch.
+ pub payment_method_id: PaymentMethodId,
+}
+
+/// Dummy modular service response payload.
+#[derive(Clone, Debug, Deserialize)]
+// TODO: replace dummy response types with real v1/modular models.
+pub struct RetrievePaymentMethodV2Response {
+ /// Dummy identifier returned by the modular service.
+ pub id: String,
+}
+
+/// V1-facing retrieve response (dummy for now).
+#[derive(Clone, Debug)]
+// TODO: replace dummy response types with real v1/modular models.
+pub struct RetrievePaymentMethodResponse {
+ /// V1 payment method identifier.
+ pub payment_method_id: String,
+ /// Dummy delete marker (unused).
+ pub deleted: Option<bool>,
+}
+
+impl TryFrom<&RetrievePaymentMethodV1Request> for RetrievePaymentMethodV2Request {
+ type Error = MicroserviceClientError;
+
+ fn try_from(value: &RetrievePaymentMethodV1Request) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_id: value.payment_method_id.clone(),
+ })
+ }
+}
+
+impl TryFrom<RetrievePaymentMethodV2Response> for RetrievePaymentMethodResponse {
+ type Error = MicroserviceClientError;
+
+ fn try_from(_: RetrievePaymentMethodV2Response) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_id: DUMMY_PM_ID.to_string(),
+ deleted: None,
+ })
+ }
+}
+
+impl RetrievePaymentMethod {
+ fn validate_request(
+ &self,
+ request: &RetrievePaymentMethodV1Request,
+ ) -> Result<(), MicroserviceClientError> {
+ if request
+ .payment_method_id
+ .payment_method_id
+ .trim()
+ .is_empty()
+ {
+ return Err(MicroserviceClientError {
+ operation: std::any::type_name::<Self>().to_string(),
+ kind: MicroserviceClientErrorKind::InvalidRequest(
+ "Payment method ID cannot be empty".to_string(),
+ ),
+ });
+ }
+ Ok(())
+ }
+
+ fn build_path_params(
+ &self,
+ request: &RetrievePaymentMethodV2Request,
+ ) -> Vec<(&'static str, String)> {
+ vec![("id", request.payment_method_id.payment_method_id.clone())]
+ }
+}
+
+hyperswitch_interfaces::impl_microservice_flow!(
+ RetrievePaymentMethod,
+ method = Method::Get,
+ path = "/v2/payment-methods/{id}",
+ v1_request = RetrievePaymentMethodV1Request,
+ v2_request = RetrievePaymentMethodV2Request,
+ v2_response = RetrievePaymentMethodV2Response,
+ v1_response = RetrievePaymentMethodResponse,
+ client = crate::client::PaymentMethodClient<'_>,
+ path_params = RetrievePaymentMethod::build_path_params,
+ validate = RetrievePaymentMethod::validate_request
+);
diff --git a/crates/payment_methods/src/client/update.rs b/crates/payment_methods/src/client/update.rs
new file mode 100644
index 0000000000..6440586881
--- /dev/null
+++ b/crates/payment_methods/src/client/update.rs
@@ -0,0 +1,119 @@
+//! Update payment method flow types and dummy models.
+
+use api_models::payment_methods::PaymentMethodId;
+use common_utils::request::{Method, RequestContent};
+use hyperswitch_interfaces::micro_service::{MicroserviceClientError, MicroserviceClientErrorKind};
+use serde::Deserialize;
+use serde_json::Value;
+
+const DUMMY_PM_ID: &str = "pm_dummy";
+
+/// V1-facing update flow type.
+#[derive(Debug)]
+pub struct UpdatePaymentMethod;
+
+/// V1-facing update request payload.
+#[derive(Debug)]
+pub struct UpdatePaymentMethodV1Request {
+ /// Identifier for the payment method to update.
+ pub payment_method_id: PaymentMethodId,
+ /// Raw payload forwarded to the modular service.
+ pub payload: Value,
+}
+
+/// Dummy modular service request payload.
+#[derive(Clone, Debug)]
+// TODO: replace dummy request types with real v1/modular models.
+pub struct UpdatePaymentMethodV2Request {
+ /// Identifier for the payment method to update.
+ pub payment_method_id: PaymentMethodId,
+ /// Payload to send in the request body.
+ pub payload: Value,
+}
+
+/// Dummy modular service response payload.
+#[derive(Clone, Debug, Deserialize)]
+// TODO: replace dummy response types with real v1/modular models.
+pub struct UpdatePaymentMethodV2Response {
+ /// Dummy identifier returned by the modular service.
+ pub id: String,
+}
+
+/// V1-facing update response (dummy for now).
+#[derive(Clone, Debug)]
+// TODO: replace dummy response types with real v1/modular models.
+pub struct UpdatePaymentMethodResponse {
+ /// V1 payment method identifier.
+ pub payment_method_id: String,
+ /// Dummy delete marker (unused).
+ pub deleted: Option<bool>,
+}
+
+impl TryFrom<&UpdatePaymentMethodV1Request> for UpdatePaymentMethodV2Request {
+ type Error = MicroserviceClientError;
+
+ fn try_from(value: &UpdatePaymentMethodV1Request) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_id: value.payment_method_id.clone(),
+ payload: value.payload.clone(),
+ })
+ }
+}
+
+impl TryFrom<UpdatePaymentMethodV2Response> for UpdatePaymentMethodResponse {
+ type Error = MicroserviceClientError;
+
+ fn try_from(_: UpdatePaymentMethodV2Response) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_id: DUMMY_PM_ID.to_string(),
+ deleted: None,
+ })
+ }
+}
+
+impl UpdatePaymentMethod {
+ fn validate_request(
+ &self,
+ request: &UpdatePaymentMethodV1Request,
+ ) -> Result<(), MicroserviceClientError> {
+ if request
+ .payment_method_id
+ .payment_method_id
+ .trim()
+ .is_empty()
+ {
+ return Err(MicroserviceClientError {
+ operation: std::any::type_name::<Self>().to_string(),
+ kind: MicroserviceClientErrorKind::InvalidRequest(
+ "Payment method ID cannot be empty".to_string(),
+ ),
+ });
+ }
+ Ok(())
+ }
+
+ fn build_path_params(
+ &self,
+ request: &UpdatePaymentMethodV2Request,
+ ) -> Vec<(&'static str, String)> {
+ vec![("id", request.payment_method_id.payment_method_id.clone())]
+ }
+
+ fn build_body(&self, request: UpdatePaymentMethodV2Request) -> Option<RequestContent> {
+ Some(RequestContent::Json(Box::new(request.payload)))
+ }
+}
+
+hyperswitch_interfaces::impl_microservice_flow!(
+ UpdatePaymentMethod,
+ method = Method::Patch,
+ path = "/v2/payment-methods/{id}/update-saved-payment-method",
+ v1_request = UpdatePaymentMethodV1Request,
+ v2_request = UpdatePaymentMethodV2Request,
+ v2_response = UpdatePaymentMethodV2Response,
+ v1_response = UpdatePaymentMethodResponse,
+ client = crate::client::PaymentMethodClient<'_>,
+ body = UpdatePaymentMethod::build_body,
+ path_params = UpdatePaymentMethod::build_path_params,
+ validate = UpdatePaymentMethod::validate_request
+);
diff --git a/crates/payment_methods/src/configs.rs b/crates/payment_methods/src/configs.rs
index 40e55c1d7b..3453e86ce5 100644
--- a/crates/payment_methods/src/configs.rs
+++ b/crates/payment_methods/src/configs.rs
@@ -1,2 +1,42 @@
pub mod payment_connector_required_fields;
pub mod settings;
+
+use serde::Deserialize;
+use url::Url;
+
+/// Microservice configuration for payment method flows.
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
+pub struct MicroServicesConfig {
+ /// Base URL for the modular payment methods service.
+ pub payment_methods_base_url: ModularPaymentMethodServiceUrl,
+}
+
+/// Base URL wrapper for the modular payment methods service.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(transparent)]
+pub struct ModularPaymentMethodServiceUrl(pub Url);
+
+impl Default for ModularPaymentMethodServiceUrl {
+ fn default() -> Self {
+ Self(
+ #[allow(clippy::expect_used)]
+ Url::parse("http://localhost:8080")
+ .expect("Failed to parse default payment_methods_base_url"),
+ )
+ }
+}
+
+impl std::ops::Deref for ModularPaymentMethodServiceUrl {
+ type Target = Url;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl AsRef<Url> for ModularPaymentMethodServiceUrl {
+ fn as_ref(&self) -> &Url {
+ &self.0
+ }
+}
diff --git a/crates/payment_methods/src/lib.rs b/crates/payment_methods/src/lib.rs
index ab3252b464..35e7c75e44 100644
--- a/crates/payment_methods/src/lib.rs
+++ b/crates/payment_methods/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod client;
pub mod configs;
pub mod controller;
pub mod core;
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 24ee93e2d2..2e71f1ee99 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -636,6 +636,7 @@ pub(crate) async fn fetch_raw_secrets(
proxy_status_mapping: conf.proxy_status_mapping,
trace_header: conf.trace_header,
internal_services: conf.internal_services,
+ micro_services: conf.micro_services,
superposition,
comparison_service: conf.comparison_service,
authentication_service_enabled_connectors: conf.authentication_service_enabled_connectors,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 0e57648c10..45200d9e05 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -40,6 +40,7 @@ pub use payment_methods::configs::settings::{
SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate,
SupportedPaymentMethodsForMandate, ZeroMandates,
};
+use payment_methods::configs::MicroServicesConfig;
use rand::seq::IteratorRandom;
use redis_interface::RedisSettings;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
@@ -182,6 +183,8 @@ pub struct Settings<S: SecretState> {
pub proxy_status_mapping: ProxyStatusMapping,
pub trace_header: TraceHeaderConfig,
pub internal_services: InternalServicesConfig,
+ #[serde(default)]
+ pub micro_services: MicroServicesConfig,
pub comparison_service: Option<ComparisonServiceConfig>,
pub authentication_service_enabled_connectors: AuthenticationServiceEnabledConnectors,
pub save_payment_method_on_session: OnSessionConfig,
diff --git a/crates/router_env/src/request_id.rs b/crates/router_env/src/request_id.rs
index e3ee0087ee..8400d8d8e6 100644
--- a/crates/router_env/src/request_id.rs
+++ b/crates/router_env/src/request_id.rs
@@ -167,6 +167,11 @@ impl TryFrom<&str> for RequestId {
}
impl RequestId {
+ /// Generate a new request ID using UUID v7.
+ pub fn new_generated() -> Self {
+ Self(generate_uuid_v7().into())
+ }
+
/// Extract request ID from ServiceRequest header or generate UUID v7.
///
/// This is the core logic: try to extract from the specified header,
@@ -252,6 +257,64 @@ impl RequestIdentifier {
..self
}
}
+
+ /// Get the header name used for request ID extraction.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use router_env::RequestIdentifier;
+ ///
+ /// let identifier = RequestIdentifier::new("x-request-id");
+ /// assert_eq!(identifier.header_name(), "x-request-id");
+ /// ```
+ pub fn header_name(&self) -> &str {
+ &self.header_name
+ }
+
+ /// Get the configured strategy for reusing incoming request IDs.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use router_env::{IdReuse, RequestIdentifier};
+ ///
+ /// let identifier = RequestIdentifier::new("x-request-id")
+ /// .use_incoming_id(IdReuse::IgnoreIncoming);
+ /// assert_eq!(identifier.id_reuse_strategy(), IdReuse::IgnoreIncoming);
+ /// ```
+ pub fn id_reuse_strategy(&self) -> IdReuse {
+ self.use_incoming_id
+ }
+}
+
+impl IdReuse {
+ /// Reuse the existing request ID or create a new one based on the configured strategy.
+ ///
+ /// Returns the request ID and a flag indicating whether it was newly generated.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use router_env::{IdReuse, RequestId};
+ ///
+ /// let existing = RequestId::new_generated();
+ /// let (id, generated) = IdReuse::UseIncoming.get_or_create_request_id(Some(&existing));
+ /// assert_eq!(id, existing);
+ /// assert!(!generated);
+ ///
+ /// let (_id, generated) = IdReuse::IgnoreIncoming.get_or_create_request_id(None);
+ /// assert!(generated);
+ /// ```
+ pub fn get_or_create_request_id(&self, existing: Option<&RequestId>) -> (RequestId, bool) {
+ match self {
+ Self::UseIncoming => existing
+ .cloned()
+ .map(|id| (id, false))
+ .unwrap_or_else(|| (RequestId::new_generated(), true)),
+ Self::IgnoreIncoming => (RequestId::new_generated(), true),
+ }
+ }
}
impl<S, B> Transform<S, ServiceRequest> for RequestIdentifier