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 support for Proxy api (#7901)

Prasunna Soppa8e9bad645744
diff --git a/api-reference-v2/api-reference/proxy/proxy.mdx b/api-reference-v2/api-reference/proxy/proxy.mdx
new file mode 100644
index 0000000000..efca3f7873
--- /dev/null
+++ b/api-reference-v2/api-reference/proxy/proxy.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /proxy
+---
\ No newline at end of file
diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json
index d0ad2e8799..e56b9d684e 100644
--- a/api-reference-v2/mint.json
+++ b/api-reference-v2/mint.json
@@ -142,6 +142,10 @@
{
"group": "Refunds",
"pages": ["api-reference/refunds/refunds--create"]
+ },
+ {
+ "group": "Proxy",
+ "pages": ["api-reference/proxy/proxy"]
}
],
"footerSocials": {
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 6d52decc7c..00e3e7bc4f 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -863,7 +863,7 @@
],
"summary": "Profile - Connector Accounts List",
"description": "List Connector Accounts for the profile",
- "operationId": "List all Merchant Connectors",
+ "operationId": "List all Merchant Connectors for Profile",
"parameters": [
{
"name": "id",
@@ -2151,7 +2151,7 @@
],
"summary": "Payments - Session token",
"description": "Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.",
- "operationId": "Create Session tokens for a Payment",
+ "operationId": "Create V2 Session tokens for a Payment",
"parameters": [
{
"name": "payment_id",
@@ -2921,7 +2921,7 @@
]
}
},
- "/v2/payment-method-session/:id": {
+ "/v2/payment-method-session/{id}": {
"get": {
"tags": [
"Payment Method Session"
@@ -3018,7 +3018,7 @@
]
}
},
- "/v2/payment-method-session/:id/list-payment-methods": {
+ "/v2/payment-method-session/{id}/list-payment-methods": {
"get": {
"tags": [
"Payment Method Session"
@@ -3059,7 +3059,7 @@
]
}
},
- "/v2/payment-method-session/:id/update-saved-payment-method": {
+ "/v2/payment-method-session/{id}/update-saved-payment-method": {
"put": {
"tags": [
"Payment Method Session"
@@ -3122,7 +3122,7 @@
]
}
},
- "/v2/payment-method-session/:id/confirm": {
+ "/v2/payment-method-session/{id}/confirm": {
"post": {
"tags": [
"Payment Method Session"
@@ -3450,6 +3450,88 @@
}
]
}
+ },
+ "/proxy": {
+ "post": {
+ "tags": [
+ "Proxy"
+ ],
+ "summary": "Proxy",
+ "description": "Create a proxy request",
+ "operationId": "Proxy Request",
+ "parameters": [
+ {
+ "name": "X-Profile-Id",
+ "in": "header",
+ "description": "Profile ID for authentication",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ProxyRequest"
+ },
+ "examples": {
+ "Create a proxy request": {
+ "value": {
+ "destination_url": "https://api.example.com/payments",
+ "headers": {
+ "Authorization": "Bearer sk_test_example",
+ "Content-Type": "application/json"
+ },
+ "method": "POST",
+ "request_body": {
+ "amount": 6540,
+ "capture": true,
+ "currency": "USD",
+ "reference": "ORD-5023-4E89",
+ "source": {
+ "billing_address": {
+ "address_line1": "123 High St.",
+ "city": "London",
+ "country": "GB"
+ },
+ "expiry_month": "{{$card_exp_month}}",
+ "expiry_year": "{{$card_exp_year}}",
+ "number": "{{$card_number}}",
+ "type": "card"
+ }
+ },
+ "token": "pm_0196ea5a42a67583863d5b1253d62931",
+ "token_type": "PaymentMethodId"
+ }
+ }
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Proxy request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ProxyResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
}
},
"components": {
@@ -7929,6 +8011,7 @@
"aci",
"adyen",
"airwallex",
+ "archipel",
"authorizedotnet",
"bambora",
"bamboraapac",
@@ -13184,6 +13267,16 @@
}
}
},
+ "Method": {
+ "type": "string",
+ "enum": [
+ "GET",
+ "POST",
+ "PUT",
+ "DELETE",
+ "PATCH"
+ ]
+ },
"MifinityData": {
"type": "object",
"required": [
@@ -13804,7 +13897,8 @@
"trigger_api",
"display_bank_transfer_information",
"display_wait_screen",
- "collect_otp"
+ "collect_otp",
+ "redirect_inside_popup"
]
},
"NoThirdPartySdkSessionResponse": {
@@ -14131,6 +14225,9 @@
},
"OrganizationUpdateRequest": {
"type": "object",
+ "required": [
+ "platform_merchant_id"
+ ],
"properties": {
"organization_name": {
"type": "string",
@@ -14148,12 +14245,8 @@
"nullable": true
},
"platform_merchant_id": {
- "allOf": [
- {
- "$ref": "#/components/schemas/id_type.MerchantId"
- }
- ],
- "nullable": true
+ "type": "string",
+ "description": "Platform merchant id is unique distiguisher for special merchant in the platform org"
}
},
"additionalProperties": false
@@ -18098,6 +18191,11 @@
"type": "boolean",
"description": "Indicates if 3ds challenge is forced",
"nullable": true
+ },
+ "is_iframe_redirection_enabled": {
+ "type": "boolean",
+ "description": "Indicates if the redirection has to open in the iframe",
+ "nullable": true
}
},
"additionalProperties": false
@@ -18269,6 +18367,11 @@
],
"default": "no_three_ds",
"nullable": true
+ },
+ "is_iframe_redirection_enabled": {
+ "type": "boolean",
+ "description": "Indicates if the redirection has to open in the iframe",
+ "nullable": true
}
}
},
@@ -20071,6 +20174,11 @@
],
"nullable": true
},
+ "is_iframe_redirection_enabled": {
+ "type": "boolean",
+ "description": "Indicates if the redirection has to open in the iframe",
+ "nullable": true
+ },
"is_external_vault_enabled": {
"type": "boolean",
"description": "Indicates if external vault is enabled or not.",
@@ -20334,6 +20442,11 @@
],
"nullable": true
},
+ "is_iframe_redirection_enabled": {
+ "type": "boolean",
+ "description": "Indicates if the redirection has to open in the iframe",
+ "nullable": true
+ },
"is_external_vault_enabled": {
"type": "boolean",
"description": "Indicates if external vault is enabled or not.",
@@ -20370,6 +20483,64 @@
}
}
},
+ "ProxyRequest": {
+ "type": "object",
+ "required": [
+ "request_body",
+ "destination_url",
+ "headers",
+ "method",
+ "token",
+ "token_type"
+ ],
+ "properties": {
+ "request_body": {
+ "description": "The request body that needs to be forwarded"
+ },
+ "destination_url": {
+ "type": "string",
+ "description": "The destination URL where the request needs to be forwarded",
+ "example": "https://api.example.com/endpoint"
+ },
+ "headers": {
+ "type": "object",
+ "description": "The headers that need to be forwarded"
+ },
+ "method": {
+ "$ref": "#/components/schemas/Method"
+ },
+ "token": {
+ "type": "string",
+ "description": "The vault token that is used to fetch sensitive data from the vault"
+ },
+ "token_type": {
+ "$ref": "#/components/schemas/TokenType"
+ }
+ }
+ },
+ "ProxyResponse": {
+ "type": "object",
+ "required": [
+ "response",
+ "status_code",
+ "response_headers"
+ ],
+ "properties": {
+ "response": {
+ "description": "The response received from the destination"
+ },
+ "status_code": {
+ "type": "integer",
+ "format": "int32",
+ "description": "The status code of the response",
+ "minimum": 0
+ },
+ "response_headers": {
+ "type": "object",
+ "description": "The headers of the response"
+ }
+ }
+ },
"PspTokenization": {
"type": "object",
"description": "The Payment Service Provider Configuration for payment methods that are created using the payment method session",
@@ -20614,6 +20785,9 @@
},
{
"type": "object",
+ "required": [
+ "refund_id"
+ ],
"properties": {
"payment_id": {
"type": "string",
@@ -20621,12 +20795,8 @@
"nullable": true
},
"refund_id": {
- "allOf": [
- {
- "$ref": "#/components/schemas/common_utils.id_type.GlobalRefundId"
- }
- ],
- "nullable": true
+ "type": "string",
+ "description": "The identifier for the refund"
},
"limit": {
"type": "integer",
@@ -21415,6 +21585,7 @@
"aci",
"adyen",
"airwallex",
+ "archipel",
"authorizedotnet",
"bankofamerica",
"billwerk",
@@ -23093,6 +23264,13 @@
}
]
},
+ "TokenType": {
+ "type": "string",
+ "enum": [
+ "tokenization_id",
+ "payment_method_id"
+ ]
+ },
"TokenizationType": {
"type": "string",
"description": "The type of tokenization to use for the payment method",
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index d57c3f55f2..d7f3cd4180 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -622,6 +622,16 @@
"description": "To list the *payments*",
"operationId": "List all Payments",
"parameters": [
+ {
+ "name": "customer_id",
+ "in": "query",
+ "description": "The identifier for the customer",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "nullable": true
+ }
+ },
{
"name": "starting_after",
"in": "query",
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 327406c198..120e912138 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -19,7 +19,7 @@ recon = []
v1 = ["common_utils/v1"]
v2 = ["common_types/v2", "common_utils/v2", "customer_v2", "refunds_v2"]
customer_v2 = ["common_utils/customer_v2"]
-payment_methods_v2 = ["common_utils/payment_methods_v2"]
+payment_methods_v2 = ["common_utils/payment_methods_v2", "dep:reqwest"]
refunds_v2 = []
dynamic_routing = []
control_center_theme = ["dep:actix-web", "dep:actix-multipart"]
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index 87e874f7fa..fa3c34db93 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -32,6 +32,8 @@ pub mod payouts;
pub mod pm_auth;
pub mod poll;
pub mod process_tracker;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub mod proxy;
#[cfg(feature = "recon")]
pub mod recon;
pub mod refunds;
diff --git a/crates/api_models/src/proxy.rs b/crates/api_models/src/proxy.rs
new file mode 100644
index 0000000000..f0b572384c
--- /dev/null
+++ b/crates/api_models/src/proxy.rs
@@ -0,0 +1,69 @@
+use std::collections::HashMap;
+
+use common_utils::request::Method;
+use reqwest::header::HeaderMap;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use utoipa::ToSchema;
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct Headers(pub HashMap<String, String>);
+
+impl Headers {
+ pub fn as_map(&self) -> &HashMap<String, String> {
+ &self.0
+ }
+
+ pub fn from_header_map(headers: Option<&HeaderMap>) -> Self {
+ headers
+ .map(|h| {
+ let map = h
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
+ .collect();
+ Self(map)
+ })
+ .unwrap_or_else(|| Self(HashMap::new()))
+ }
+}
+
+#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
+pub struct ProxyRequest {
+ /// The request body that needs to be forwarded
+ pub request_body: Value,
+ /// The destination URL where the request needs to be forwarded
+ #[schema(value_type = String, example = "https://api.example.com/endpoint")]
+ pub destination_url: url::Url,
+ /// The headers that need to be forwarded
+ #[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
+ pub headers: Headers,
+ /// The method that needs to be used for the request
+ #[schema(value_type = Method, example = "Post")]
+ pub method: Method,
+ /// The vault token that is used to fetch sensitive data from the vault
+ pub token: String,
+ /// The type of token that is used to fetch sensitive data from the vault
+ #[schema(value_type = TokenType, example = "payment_method_id")]
+ pub token_type: TokenType,
+}
+
+#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TokenType {
+ TokenizationId,
+ PaymentMethodId,
+}
+
+#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
+pub struct ProxyResponse {
+ /// The response received from the destination
+ pub response: Value,
+ /// The status code of the response
+ pub status_code: u16,
+ /// The headers of the response
+ #[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
+ pub response_headers: Headers,
+}
+
+impl common_utils::events::ApiEventMetric for ProxyRequest {}
+impl common_utils::events::ApiEventMetric for ProxyResponse {}
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index e556c7eccc..54fb4fb470 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -382,6 +382,7 @@ pub struct RefundListRequest {
#[schema(value_type = Option<String>)]
pub payment_id: Option<common_utils::id_type::GlobalPaymentId>,
/// The identifier for the refund
+ #[schema(value_type = String)]
pub refund_id: Option<common_utils::id_type::GlobalRefundId>,
/// Limit on the number of objects to return
pub limit: Option<i64>,
diff --git a/crates/common_utils/src/request.rs b/crates/common_utils/src/request.rs
index 38244e2a3d..ab78ffd1f2 100644
--- a/crates/common_utils/src/request.rs
+++ b/crates/common_utils/src/request.rs
@@ -1,10 +1,20 @@
use masking::{Maskable, Secret};
use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
pub type Headers = std::collections::HashSet<(String, Maskable<String>)>;
#[derive(
- Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString,
+ Clone,
+ Copy,
+ Debug,
+ Eq,
+ PartialEq,
+ Deserialize,
+ Serialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 6057797e20..9b8387389f 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -153,7 +153,10 @@ Never share your secret api keys. Keep them guarded and secure.
routes::refunds::refunds_list,
// Routes for Revenue Recovery flow under Process Tracker
- routes::revenue_recovery::revenue_recovery_pt_retrieve_api
+ routes::revenue_recovery::revenue_recovery_pt_retrieve_api,
+
+ // Routes for proxy
+ routes::proxy::proxy_core,
),
components(schemas(
common_utils::types::MinorUnit,
@@ -189,6 +192,7 @@ Never share your secret api keys. Keep them guarded and secure.
common_types::refunds::SplitRefund,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
+ common_utils::request::Method,
api_models::refunds::RefundsCreateRequest,
api_models::refunds::RefundErrorDetails,
api_models::refunds::RefundType,
@@ -728,6 +732,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::AuthenticationDetails,
api_models::process_tracker::revenue_recovery::RevenueRecoveryResponse,
api_models::enums::ProcessTrackerStatus,
+ api_models::proxy::ProxyRequest,
+ api_models::proxy::ProxyResponse,
+ api_models::proxy::TokenType,
routes::payments::ForceSync,
)),
modifiers(&SecurityAddon)
diff --git a/crates/openapi/src/routes.rs b/crates/openapi/src/routes.rs
index cbd215dccd..8f95de75b3 100644
--- a/crates/openapi/src/routes.rs
+++ b/crates/openapi/src/routes.rs
@@ -15,6 +15,7 @@ pub mod payments;
pub mod payouts;
pub mod poll;
pub mod profile;
+pub mod proxy;
pub mod refunds;
pub mod relay;
pub mod revenue_recovery;
diff --git a/crates/openapi/src/routes/proxy.rs b/crates/openapi/src/routes/proxy.rs
new file mode 100644
index 0000000000..f28b732f7b
--- /dev/null
+++ b/crates/openapi/src/routes/proxy.rs
@@ -0,0 +1,54 @@
+#[cfg(feature = "v2")]
+///Proxy
+///
+/// Create a proxy request
+#[utoipa::path(
+ post,
+ path = "/proxy",
+ request_body(
+ content = ProxyRequest,
+ examples((
+ "Create a proxy request" = (
+ value = json!({
+ "request_body": {
+ "source": {
+ "type": "card",
+ "number": "{{$card_number}}",
+ "expiry_month": "{{$card_exp_month}}",
+ "expiry_year": "{{$card_exp_year}}",
+ "billing_address": {
+ "address_line1": "123 High St.",
+ "city": "London",
+ "country": "GB"
+ }
+ },
+ "amount": 6540,
+ "currency": "USD",
+ "reference": "ORD-5023-4E89",
+ "capture": true
+ },
+ "destination_url": "https://api.example.com/payments",
+ "headers": {
+ "Content-Type": "application/json",
+ "Authorization": "Bearer sk_test_example"
+ },
+ "token": "pm_0196ea5a42a67583863d5b1253d62931",
+ "token_type": "PaymentMethodId",
+ "method": "POST"
+ })
+ )
+ ))
+ ),
+ responses(
+ (status = 200, description = "Proxy request", body = ProxyResponse),
+ (status = 400, description = "Invalid data")
+ ),
+ params(
+ ("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
+ ),
+ tag = "Proxy",
+ operation_id = "Proxy Request",
+ security(("api_key" = []))
+)]
+
+pub async fn proxy_core() {}
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index db2122b242..e67c3234b1 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -62,6 +62,8 @@ pub mod webhooks;
pub mod unified_authentication_service;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub mod proxy;
pub mod relay;
#[cfg(feature = "v2")]
pub mod revenue_recovery;
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 367c970e4a..e29527f9fe 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -1332,17 +1332,11 @@ pub async fn add_payment_method_to_vault(
pub async fn retrieve_payment_method_from_vault_internal(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
- pm: &domain::PaymentMethod,
+ vault_id: &domain::VaultId,
) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> {
let payload = pm_types::VaultRetrieveRequest {
entity_id: merchant_context.get_merchant_account().get_id().to_owned(),
- vault_id: pm
- .locker_id
- .clone()
- .ok_or(errors::VaultError::MissingRequiredField {
- field_name: "locker_id",
- })
- .attach_printable("Missing locker_id for VaultRetrieveRequest")?,
+ vault_id: vault_id.to_owned(),
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
@@ -1481,10 +1475,20 @@ pub async fn retrieve_payment_method_from_vault(
)
.await
}
- false => retrieve_payment_method_from_vault_internal(state, merchant_context, pm)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to retrieve payment method from vault"),
+ false => {
+ let vault_id = pm
+ .locker_id
+ .clone()
+ .ok_or(errors::VaultError::MissingRequiredField {
+ field_name: "locker_id",
+ })
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Missing locker_id for VaultRetrieveRequest")?;
+ retrieve_payment_method_from_vault_internal(state, merchant_context, &vault_id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to retrieve payment method from vault")
+ }
}
}
diff --git a/crates/router/src/core/proxy.rs b/crates/router/src/core/proxy.rs
new file mode 100644
index 0000000000..545c2ef9cc
--- /dev/null
+++ b/crates/router/src/core/proxy.rs
@@ -0,0 +1,152 @@
+use super::errors::{self, RouterResponse, RouterResult};
+use crate::{logger, routes::SessionState, services, types::domain};
+pub mod utils;
+use api_models::proxy as proxy_api_models;
+use common_utils::{
+ ext_traits::{BytesExt, Encode},
+ request::{self, RequestBuilder},
+};
+use error_stack::ResultExt;
+use hyperswitch_interfaces::types::Response;
+use serde_json::Value;
+
+pub async fn proxy_core(
+ state: SessionState,
+ merchant_context: domain::MerchantContext,
+ req: proxy_api_models::ProxyRequest,
+) -> RouterResponse<proxy_api_models::ProxyResponse> {
+ let req_wrapper = utils::ProxyRequestWrapper(req.clone());
+ let vault_id = req_wrapper
+ .get_vault_id(
+ &state,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_account().storage_scheme,
+ )
+ .await?;
+
+ let vault_response =
+ super::payment_methods::vault::retrieve_payment_method_from_vault_internal(
+ &state,
+ &merchant_context,
+ &vault_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while fetching data from vault")?;
+
+ let vault_data = vault_response
+ .data
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize vault data")?;
+
+ let processed_body =
+ interpolate_token_references_with_vault_data(req.request_body.clone(), &vault_data)?;
+
+ let res = execute_proxy_request(&state, &req_wrapper, processed_body).await?;
+
+ let proxy_response = proxy_api_models::ProxyResponse::try_from(ProxyResponseWrapper(res))?;
+
+ Ok(services::ApplicationResponse::Json(proxy_response))
+}
+
+fn interpolate_token_references_with_vault_data(
+ value: Value,
+ vault_data: &Value,
+) -> RouterResult<Value> {
+ match value {
+ Value::Object(obj) => {
+ let new_obj = obj
+ .into_iter()
+ .map(|(key, val)| interpolate_token_references_with_vault_data(val, vault_data).map(|processed| (key, processed)))
+ .collect::<Result<serde_json::Map<_, _>, error_stack::Report<errors::ApiErrorResponse>>>()?;
+
+ Ok(Value::Object(new_obj))
+ }
+ Value::String(s) => utils::parse_token(&s)
+ .map(|(_, token_ref)| extract_field_from_vault_data(vault_data, &token_ref.field))
+ .unwrap_or(Ok(Value::String(s.clone()))),
+ _ => Ok(value),
+ }
+}
+
+fn find_field_recursively_in_vault_data(
+ obj: &serde_json::Map<String, Value>,
+ field_name: &str,
+) -> Option<Value> {
+ obj.get(field_name).cloned().or_else(|| {
+ obj.values()
+ .filter_map(|val| {
+ if let Value::Object(inner_obj) = val {
+ find_field_recursively_in_vault_data(inner_obj, field_name)
+ } else {
+ None
+ }
+ })
+ .next()
+ })
+}
+
+fn extract_field_from_vault_data(vault_data: &Value, field_name: &str) -> RouterResult<Value> {
+ match vault_data {
+ Value::Object(obj) => find_field_recursively_in_vault_data(obj, field_name)
+ .ok_or_else(|| errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!("Field '{}' not found", field_name)),
+ _ => Err(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Vault data is not a valid JSON object"),
+ }
+}
+
+async fn execute_proxy_request(
+ state: &SessionState,
+ req_wrapper: &utils::ProxyRequestWrapper,
+ processed_body: Value,
+) -> RouterResult<Response> {
+ let request = RequestBuilder::new()
+ .method(req_wrapper.get_method())
+ .attach_default_headers()
+ .headers(req_wrapper.get_headers())
+ .url(req_wrapper.get_destination_url())
+ .set_body(request::RequestContent::Json(Box::new(processed_body)))
+ .build();
+
+ let response = services::call_connector_api(state, request, "proxy")
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to call the destination");
+
+ response
+ .map(|inner| match inner {
+ Err(err_res) => {
+ logger::error!("Error while receiving response: {err_res:?}");
+ err_res
+ }
+ Ok(res) => res,
+ })
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while receiving response")
+}
+
+struct ProxyResponseWrapper(Response);
+
+impl TryFrom<ProxyResponseWrapper> for proxy_api_models::ProxyResponse {
+ type Error = error_stack::Report<errors::ApiErrorResponse>;
+
+ fn try_from(wrapper: ProxyResponseWrapper) -> Result<Self, Self::Error> {
+ let res = wrapper.0;
+ let response_body: Value = res
+ .response
+ .parse_struct("ProxyResponse")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse the response")?;
+
+ let status_code = res.status_code;
+ let response_headers = proxy_api_models::Headers::from_header_map(res.headers.as_ref());
+
+ Ok(Self {
+ response: response_body,
+ status_code,
+ response_headers,
+ })
+ }
+}
diff --git a/crates/router/src/core/proxy/utils.rs b/crates/router/src/core/proxy/utils.rs
new file mode 100644
index 0000000000..e2a6c94641
--- /dev/null
+++ b/crates/router/src/core/proxy/utils.rs
@@ -0,0 +1,111 @@
+use api_models::{payment_methods::PaymentMethodId, proxy as proxy_api_models};
+use common_utils::{ext_traits::OptionExt, id_type};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ errors::api_error_response::NotImplementedMessage, payment_methods,
+};
+use masking::Mask;
+use x509_parser::nom::{
+ bytes::complete::{tag, take_while1},
+ character::complete::{char, multispace0},
+ sequence::{delimited, preceded, terminated},
+ IResult,
+};
+
+use crate::{
+ core::errors::{self, RouterResult},
+ routes::SessionState,
+ types::domain,
+};
+
+pub struct ProxyRequestWrapper(pub proxy_api_models::ProxyRequest);
+
+impl ProxyRequestWrapper {
+ pub async fn get_vault_id(
+ &self,
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: common_enums::enums::MerchantStorageScheme,
+ ) -> RouterResult<payment_methods::VaultId> {
+ let token = &self.0.token;
+
+ match self.0.token_type {
+ proxy_api_models::TokenType::PaymentMethodId => {
+ let pm_id = PaymentMethodId {
+ payment_method_id: token.clone(),
+ };
+ let pm_id =
+ id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
+ state
+ .store
+ .find_payment_method(&((state).into()), key_store, &pm_id, storage_scheme)
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)?
+ .locker_id
+ .get_required_value("vault_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Locker id not present in Payment Method Entry")
+ }
+ proxy_api_models::TokenType::TokenizationId => {
+ Err(report!(errors::ApiErrorResponse::NotImplemented {
+ message: NotImplementedMessage::Reason(
+ "Proxy flow using tokenization id".to_string(),
+ ),
+ }))
+ }
+ }
+ }
+
+ pub fn get_headers(&self) -> Vec<(String, masking::Maskable<String>)> {
+ self.0
+ .headers
+ .as_map()
+ .iter()
+ .map(|(key, value)| (key.clone(), value.clone().into_masked()))
+ .collect()
+ }
+
+ pub fn get_destination_url(&self) -> &str {
+ self.0.destination_url.as_str()
+ }
+
+ pub fn get_method(&self) -> common_utils::request::Method {
+ self.0.method
+ }
+}
+
+#[derive(Debug)]
+pub struct TokenReference {
+ pub field: String,
+}
+
+pub fn parse_token(input: &str) -> IResult<&str, TokenReference> {
+ let (input, field) = delimited(
+ tag("{{"),
+ preceded(
+ multispace0,
+ preceded(
+ char('$'),
+ terminated(
+ take_while1(|c: char| c.is_alphanumeric() || c == '_'),
+ multispace0,
+ ),
+ ),
+ ),
+ tag("}}"),
+ )(input)?;
+
+ Ok((
+ input,
+ TokenReference {
+ field: field.to_string(),
+ },
+ ))
+}
+
+pub fn contains_token(s: &str) -> bool {
+ s.contains("{{") && s.contains("$") && s.contains("}}")
+}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 16095e3faa..0388f68225 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -229,6 +229,11 @@ pub fn mk_app(
.service(routes::Cards::server(state.clone()));
}
+ #[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2"))]
+ {
+ server_app = server_app.service(routes::Proxy::server(state.clone()));
+ }
+
#[cfg(all(feature = "recon", feature = "v1"))]
{
server_app = server_app.service(routes::Recon::server(state.clone()));
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 03a5589f77..f36e7b6049 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -67,10 +67,15 @@ pub mod relay;
#[cfg(feature = "olap")]
pub mod process_tracker;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub mod proxy;
+
#[cfg(feature = "dummy_connector")]
pub use self::app::DummyConnector;
#[cfg(feature = "v2")]
pub use self::app::PaymentMethodSession;
+#[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2"))]
+pub use self::app::Proxy;
#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]
pub use self::app::Recon;
pub use self::app::{
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index bc5d58e482..173ac34bd3 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -47,6 +47,8 @@ use super::payouts::*;
use super::pm_auth;
#[cfg(feature = "oltp")]
use super::poll;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use super::proxy;
#[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))]
use super::recovery_webhooks::*;
#[cfg(all(feature = "oltp", feature = "v2"))]
@@ -666,6 +668,18 @@ impl Relay {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub struct Proxy;
+
+#[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2"))]
+impl Proxy {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("/proxy")
+ .app_data(web::Data::new(state))
+ .service(web::resource("").route(web::post().to(proxy::proxy)))
+ }
+}
+
#[cfg(feature = "v1")]
impl Payments {
pub fn server(state: AppState) -> Scope {
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 88f42da350..1f224d2177 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -43,6 +43,7 @@ pub enum ApiIdentifier {
Hypersense,
PaymentMethodSession,
ProcessTracker,
+ Proxy,
}
impl From<Flow> for ApiIdentifier {
@@ -340,6 +341,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentMethodSessionUpdate => Self::PaymentMethodSession,
Flow::RevenueRecoveryRetrieve => Self::ProcessTracker,
+ Flow::Proxy => Self::Proxy,
}
}
}
diff --git a/crates/router/src/routes/proxy.rs b/crates/router/src/routes/proxy.rs
new file mode 100644
index 0000000000..7d9c97eda5
--- /dev/null
+++ b/crates/router/src/routes/proxy.rs
@@ -0,0 +1,37 @@
+use actix_web::{web, Responder};
+use router_env::{instrument, tracing, Flow};
+
+use crate::{
+ self as app,
+ core::{api_locking, proxy},
+ services::{api, authentication as auth},
+ types::domain,
+};
+
+#[instrument(skip_all, fields(flow = ?Flow::Proxy))]
+pub async fn proxy(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ payload: web::Json<api_models::proxy::ProxyRequest>,
+) -> impl Responder {
+ let flow = Flow::Proxy;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload.into_inner(),
+ |state, auth: auth::AuthenticationData, req, _| {
+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
+ domain::Context(auth.merchant_account, auth.key_store),
+ ));
+ proxy::proxy_core(state, merchant_context, req)
+ },
+ &auth::V2ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 7b9e4e9a34..60a8939aeb 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -588,6 +588,8 @@ pub enum Flow {
RevenueRecoveryRetrieve,
/// Clone Connector flow
CloneConnector,
+ ///Proxy Flow
+ Proxy,
}
/// Trait for providing generic behaviour to flow metric