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(payouts): Add payout gateway and rollout config for UCS (#11683)

Sakil Mostakfc9503fe1ea3
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index b52d5770d8..1d570edf4c 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -34096,7 +34096,8 @@
"wise",
"worldpay",
"worldpayxml",
- "envoy"
+ "envoy",
+ "itaubank"
]
},
"PayoutCreatePayoutLinkConfig": {
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index af9cb96851..8092dc4126 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -24542,7 +24542,8 @@
"wise",
"worldpay",
"worldpayxml",
- "envoy"
+ "envoy",
+ "itaubank"
]
},
"PayoutCreatePayoutLinkConfig": {
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index b90b7cc522..3501669f83 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -63,6 +63,7 @@ pub enum PayoutConnectors {
Worldpay,
Worldpayxml,
Envoy,
+ Itaubank,
}
#[cfg(feature = "v2")]
@@ -107,6 +108,7 @@ impl From<PayoutConnectors> for RoutableConnectors {
PayoutConnectors::Worldpay => Self::Worldpay,
PayoutConnectors::Worldpayxml => Self::Worldpayxml,
PayoutConnectors::Envoy => Self::Envoy,
+ PayoutConnectors::Itaubank => Self::Itaubank,
}
}
}
@@ -132,6 +134,7 @@ impl From<PayoutConnectors> for Connector {
PayoutConnectors::Worldpay => Self::Worldpay,
PayoutConnectors::Worldpayxml => Self::Worldpayxml,
PayoutConnectors::Envoy => Self::Envoy,
+ PayoutConnectors::Itaubank => Self::Itaubank,
}
}
}
@@ -158,6 +161,7 @@ impl TryFrom<Connector> for PayoutConnectors {
Connector::Worldpay => Ok(Self::Worldpay),
Connector::Worldpayxml => Ok(Self::Worldpayxml),
Connector::Envoy => Ok(Self::Envoy),
+ Connector::Itaubank => Ok(Self::Itaubank),
_ => Err(format!("Invalid payout connector {value}")),
}
}
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 44d5036bef..ae7598ab04 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -850,7 +850,7 @@ pub struct PayoutActionRequest {
pub payout_id: id_type::PayoutId,
}
-#[derive(Default, Debug, ToSchema, Clone, Deserialize)]
+#[derive(Default, Debug, ToSchema, Clone, Serialize, Deserialize)]
pub struct PayoutVendorAccountDetails {
pub vendor_details: PayoutVendorDetails,
pub individual_details: PayoutIndividualDetails,
@@ -1375,3 +1375,36 @@ pub struct PayoutsManualUpdateResponse {
/// A unique identifier for a payout provided by the connector
pub connector_payout_id: Option<String>,
}
+
+impl From<&PayoutMethodData> for api_enums::PaymentMethodType {
+ fn from(data: &PayoutMethodData) -> Self {
+ match data {
+ // debit represent card payout methods, todo: consider renaming it to card in future
+ PayoutMethodData::Card(_) => Self::Debit,
+ PayoutMethodData::Bank(bank) => match bank {
+ Bank::Ach(_) => Self::Ach,
+ Bank::Bacs(_) => Self::Bacs,
+ Bank::Sepa(_) => Self::SepaBankTransfer,
+ Bank::Pix(_) => Self::Pix,
+ Bank::Trustly(_) => Self::Trustly,
+ },
+ PayoutMethodData::BankTransfer(bank_transfer) => match bank_transfer {
+ BankTransfer::Ach(_) => Self::Ach,
+ BankTransfer::Bacs(_) => Self::Bacs,
+ BankTransfer::Sepa(_) => Self::SepaBankTransfer,
+ BankTransfer::Pix(_) => Self::Pix,
+ BankTransfer::Trustly(_) => Self::Trustly,
+ },
+ PayoutMethodData::Wallet(wallet) => match wallet {
+ Wallet::ApplePayDecrypt(_) => Self::ApplePay,
+ Wallet::Paypal(_) => Self::Paypal,
+ Wallet::Venmo(_) => Self::Venmo,
+ },
+ PayoutMethodData::BankRedirect(bank_redirect) => match bank_redirect {
+ BankRedirect::Interac(_) => Self::Interac,
+ BankRedirect::OpenBankingUk(_) => Self::OpenBankingUk,
+ },
+ PayoutMethodData::Passthrough(passthrough) => passthrough.token_type,
+ }
+ }
+}
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs
index a37bc1efe2..24064774c7 100644
--- a/crates/common_enums/src/connector_enums.rs
+++ b/crates/common_enums/src/connector_enums.rs
@@ -221,6 +221,7 @@ impl Connector {
| (Self::Trustly, _)
| (Self::Worldpay, Some(PayoutType::Wallet))
| (Self::Worldpayxml, Some(PayoutType::Wallet))
+ | (Self::Itaubank, Some(PayoutType::Bank))
)
}
#[cfg(feature = "payouts")]
@@ -242,7 +243,7 @@ impl Connector {
pub fn supports_access_token_for_payout(self, payout_method: Option<PayoutType>) -> bool {
matches!(
(self, payout_method),
- (Self::Paypal, _) | (Self::Truelayer, _)
+ (Self::Paypal, _) | (Self::Truelayer, _) | (Self::Itaubank, _)
)
}
#[cfg(feature = "payouts")]
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs
index 6a7df2e282..dadfb2a9c5 100644
--- a/crates/common_utils/src/id_type.rs
+++ b/crates/common_utils/src/id_type.rs
@@ -58,6 +58,7 @@ pub use self::{
merchant_connector_account::MerchantConnectorAccountId,
organization::OrganizationId,
payment::{PaymentId, PaymentReferenceId, PaymentResourceId},
+ payout::{PayoutReferenceId, PayoutResourceId},
profile::ProfileId,
profile_acquirer::ProfileAcquirerId,
refunds::RefundReferenceId,
diff --git a/crates/common_utils/src/id_type/payout.rs b/crates/common_utils/src/id_type/payout.rs
index 8faa661d36..644e29bf71 100644
--- a/crates/common_utils/src/id_type/payout.rs
+++ b/crates/common_utils/src/id_type/payout.rs
@@ -1,3 +1,5 @@
+use crate::errors::ValidationError;
+
crate::id_type!(
PayoutId,
"A domain type for payout_id that can be used for payout ids"
@@ -8,3 +10,43 @@ crate::impl_try_from_cow_str_id_type!(PayoutId, "payout_id");
crate::impl_generate_id_id_type!(PayoutId, "payout");
crate::impl_queryable_id_type!(PayoutId);
crate::impl_to_sql_from_sql_id_type!(PayoutId);
+
+crate::id_type!(PayoutResourceId, "A type for payout_resource_id");
+crate::impl_id_type_methods!(PayoutResourceId, "payout_resource_id");
+
+// This is to display the `PayoutResourceId` as PayoutResourceId(abcd)
+crate::impl_debug_id_type!(PayoutResourceId);
+crate::impl_try_from_cow_str_id_type!(PayoutResourceId, "payout_resource_id");
+
+// Database related implementations so that this field can be used directly in the database tables
+crate::impl_queryable_id_type!(PayoutResourceId);
+crate::impl_to_sql_from_sql_id_type!(PayoutResourceId);
+
+crate::id_type!(PayoutReferenceId, "A type for payout_reference_id");
+crate::impl_id_type_methods!(PayoutReferenceId, "payout_reference_id");
+
+// This is to display the `PayoutReferenceId` as PayoutReferenceId(abcd)
+crate::impl_debug_id_type!(PayoutReferenceId);
+crate::impl_try_from_cow_str_id_type!(PayoutReferenceId, "payout_reference_id");
+
+// Database related implementations so that this field can be used directly in the database tables
+crate::impl_queryable_id_type!(PayoutReferenceId);
+crate::impl_to_sql_from_sql_id_type!(PayoutReferenceId);
+
+impl std::str::FromStr for PayoutReferenceId {
+ type Err = error_stack::Report<ValidationError>;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let cow_string = std::borrow::Cow::Owned(s.to_string());
+ Self::try_from(cow_string)
+ }
+}
+
+impl std::str::FromStr for PayoutResourceId {
+ type Err = error_stack::Report<ValidationError>;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let cow_string = std::borrow::Cow::Owned(s.to_string());
+ Self::try_from(cow_string)
+ }
+}
diff --git a/crates/common_utils/src/payout_method_utils.rs b/crates/common_utils/src/payout_method_utils.rs
index d09f53eff0..491ea57c77 100644
--- a/crates/common_utils/src/payout_method_utils.rs
+++ b/crates/common_utils/src/payout_method_utils.rs
@@ -336,3 +336,29 @@ pub struct PassthroughAdditionalData {
#[schema(value_type = PaymentMethodType, example = "paypal")]
pub token_type: common_enums::PaymentMethodType,
}
+
+impl From<&AdditionalPayoutMethodData> for common_enums::PaymentMethodType {
+ fn from(data: &AdditionalPayoutMethodData) -> Self {
+ match data {
+ // debit represent card payout methods, todo: consider renaming it to card in future
+ AdditionalPayoutMethodData::Card(_) => Self::Debit,
+ AdditionalPayoutMethodData::Bank(bank) => match **bank {
+ BankAdditionalData::Ach(_) => Self::Ach,
+ BankAdditionalData::Bacs(_) => Self::Bacs,
+ BankAdditionalData::Sepa(_) => Self::SepaBankTransfer,
+ BankAdditionalData::Pix(_) => Self::Pix,
+ BankAdditionalData::Trustly(_) => Self::Trustly,
+ },
+ AdditionalPayoutMethodData::Wallet(wallet) => match **wallet {
+ WalletAdditionalData::ApplePayDecrypt(_) => Self::ApplePay,
+ WalletAdditionalData::Paypal(_) => Self::Paypal,
+ WalletAdditionalData::Venmo(_) => Self::Venmo,
+ },
+ AdditionalPayoutMethodData::BankRedirect(bank_redirect) => match **bank_redirect {
+ BankRedirectAdditionalData::Interac(_) => Self::Interac,
+ BankRedirectAdditionalData::OpenBankingUk(_) => Self::OpenBankingUk,
+ },
+ AdditionalPayoutMethodData::Passthrough(passthrough) => passthrough.token_type,
+ }
+ }
+}
diff --git a/crates/common_utils/src/ucs_types.rs b/crates/common_utils/src/ucs_types.rs
index 7af39e2e3f..89880ad51f 100644
--- a/crates/common_utils/src/ucs_types.rs
+++ b/crates/common_utils/src/ucs_types.rs
@@ -12,6 +12,12 @@ pub enum UcsReferenceId {
/// This variant wraps a [`PaymentReferenceId`](id_type::PaymentReferenceId)
/// and is used to identify a payment transaction within the UCS.
Payment(id_type::PaymentReferenceId),
+
+ /// A payout reference ID.
+ ///
+ /// This variant wraps a [`PayoutReferenceId`](id_type::PayoutReferenceId)
+ /// and is used to identify a payout transaction within the UCS.
+ Payout(id_type::PayoutReferenceId),
}
impl UcsReferenceId {
@@ -27,6 +33,7 @@ impl UcsReferenceId {
pub fn get_string_repr(&self) -> &str {
match self {
Self::Payment(id) => id.get_string_repr(),
+ Self::Payout(id) => id.get_string_repr(),
}
}
}
@@ -48,6 +55,11 @@ pub enum UcsResourceId {
/// This variant wraps a [`RefundResourceId`](id_type::RefundResourceId)
/// and is used to identify a refund transaction within the UCS.
Refund(id_type::RefundReferenceId),
+ /// A payout resource ID.
+ ///
+ /// This variant wraps a [`PayoutResourceId`](id_type::PayoutResourceId)
+ /// and is used to identify a payout transaction within the UCS.
+ PayoutAttempt(id_type::PayoutResourceId),
}
impl UcsResourceId {
@@ -64,6 +76,7 @@ impl UcsResourceId {
match self {
Self::PaymentAttempt(id) => id.get_string_repr(),
Self::Refund(id) => id.get_string_repr(),
+ Self::PayoutAttempt(id) => id.get_string_repr(),
}
}
}
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 2d6710d88f..ed13248d98 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -453,6 +453,7 @@ impl ConnectorConfig {
PayoutConnectors::Worldpay => Ok(connector_data.worldpay_payout),
PayoutConnectors::Worldpayxml => Ok(connector_data.worldpayxml_payout),
PayoutConnectors::Envoy => Ok(connector_data.envoy_payout),
+ PayoutConnectors::Itaubank => Ok(connector_data.itaubank),
}
}
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 cff6172907..6dcc35b8d6 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -44,6 +44,8 @@ pub struct UnifiedConnectorServiceClient {
/// The Payment Method Authentication Service Client
pub payment_method_authentication_service_client:
payments_grpc::payment_method_authentication_service_client::PaymentMethodAuthenticationServiceClient<tonic::transport::Channel>,
+ /// The Payout Service Client
+ pub payout_service_client: payments_grpc::payout_service_client::PayoutServiceClient<tonic::transport::Channel>,
}
/// Contains the Unified Connector Service Client config
@@ -240,6 +242,15 @@ impl UnifiedConnectorServiceClient {
timeout
);
+ let payout_service_client = build_grpc_client!(
+ payments_grpc::payout_service_client::PayoutServiceClient<
+ tonic::transport::Channel,
+ >,
+ "payout_service_client",
+ uri,
+ timeout
+ );
+
logger::info!("Successfully connected to Unified Connector Service");
Some(Self {
@@ -252,6 +263,7 @@ impl UnifiedConnectorServiceClient {
customer_service_client,
merchant_authentication_service_client,
payment_method_authentication_service_client,
+ payout_service_client,
})
}
None => {
@@ -816,6 +828,37 @@ impl UnifiedConnectorServiceClient {
})
}
+ /// Performs Payout Create
+ pub async fn payout_create(
+ &self,
+ payout_create_request: payments_grpc::PayoutServiceCreateRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PayoutServiceCreateResponse>>
+ {
+ let mut request = tonic::Request::new(payout_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.payout_service_client
+ .clone()
+ .create(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PayoutCreateFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payout_create",
+ connector_name=?connector_name,
+ "UCS payout create gRPC call failed"
+ )
+ })
+ }
+
/// Performs Create Access Token Granular
pub async fn create_access_token(
&self,
@@ -847,6 +890,194 @@ impl UnifiedConnectorServiceClient {
)
})
}
+
+ /// Performs Payout Transfer
+ pub async fn payout_transfer(
+ &self,
+ payout_transfer_request: payments_grpc::PayoutServiceTransferRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PayoutServiceTransferResponse>>
+ {
+ let mut request = tonic::Request::new(payout_transfer_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.payout_service_client
+ .clone()
+ .transfer(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PayoutTransferFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payout_transfer",
+ connector_name=?connector_name,
+ "UCS payout transfer gRPC call failed"
+ )
+ })
+ }
+
+ /// Performs Payout Get
+ pub async fn payout_get(
+ &self,
+ payout_get_request: payments_grpc::PayoutServiceGetRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PayoutServiceGetResponse>>
+ {
+ let mut request = tonic::Request::new(payout_get_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.payout_service_client
+ .clone()
+ .get(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PayoutGetFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payout_get",
+ connector_name=?connector_name,
+ "UCS payout get gRPC call failed"
+ )
+ })
+ }
+
+ /// Performs Payout Void
+ pub async fn payout_void(
+ &self,
+ payout_void_request: payments_grpc::PayoutServiceVoidRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PayoutServiceVoidResponse>>
+ {
+ let mut request = tonic::Request::new(payout_void_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.payout_service_client
+ .clone()
+ .void(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PayoutVoidFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payout_void",
+ connector_name=?connector_name,
+ "UCS payout void gRPC call failed"
+ )
+ })
+ }
+
+ /// Performs Payout Stage
+ pub async fn payout_stage(
+ &self,
+ payout_stage_request: payments_grpc::PayoutServiceStageRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PayoutServiceStageResponse>>
+ {
+ let mut request = tonic::Request::new(payout_stage_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.payout_service_client
+ .clone()
+ .stage(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PayoutStageFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payout_stage",
+ connector_name=?connector_name,
+ "UCS payout stage gRPC call failed"
+ )
+ })
+ }
+
+ /// Performs Payout Create Recipient
+ pub async fn payout_create_recipient(
+ &self,
+ payout_create_recipient_request: payments_grpc::PayoutServiceCreateRecipientRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<
+ tonic::Response<payments_grpc::PayoutServiceCreateRecipientResponse>,
+ > {
+ let mut request = tonic::Request::new(payout_create_recipient_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.payout_service_client
+ .clone()
+ .create_recipient(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PayoutCreateRecipientFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payout_create_recipient",
+ connector_name=?connector_name,
+ "UCS payout create recipient gRPC call failed"
+ )
+ })
+ }
+
+ /// Performs Payout Enroll Disburse Account
+ pub async fn payout_enroll_disburse_account(
+ &self,
+ payout_enroll_disburse_account_request: payments_grpc::PayoutServiceEnrollDisburseAccountRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<
+ tonic::Response<payments_grpc::PayoutServiceEnrollDisburseAccountResponse>,
+ > {
+ let mut request = tonic::Request::new(payout_enroll_disburse_account_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.payout_service_client
+ .clone()
+ .enroll_disburse_account(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PayoutEnrollDisburseAccountFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payout_enroll_disburse_account",
+ connector_name=?connector_name,
+ "UCS payout enroll disburse account gRPC call failed"
+ )
+ })
+ }
}
/// Build the gRPC Headers for Unified Connector Service Request
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index a582eaebbc..68cf81d07c 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -1645,7 +1645,7 @@ pub struct UploadFileRequestData {
}
#[cfg(feature = "payouts")]
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Serialize)]
pub struct PayoutsData {
pub payout_id: id_type::PayoutId,
pub amount: i64,
@@ -1667,7 +1667,7 @@ pub struct PayoutsData {
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
}
-#[derive(Debug, Default, Clone)]
+#[derive(Debug, Default, Clone, Serialize)]
pub struct CustomerDetails {
pub customer_id: Option<id_type::CustomerId>,
pub name: Option<Secret<String, hyperswitch_masking::WithType>>,
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index 98707dd904..fe6abcc47e 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -627,7 +627,7 @@ pub struct RetrieveFileResponse {
}
#[cfg(feature = "payouts")]
-#[derive(Clone, Debug, Default)]
+#[derive(Clone, Debug, Default, Serialize)]
pub struct PayoutsResponseData {
pub status: Option<common_enums::PayoutStatus>,
pub connector_payout_id: Option<String>,
diff --git a/crates/hyperswitch_interfaces/src/api/gateway.rs b/crates/hyperswitch_interfaces/src/api/gateway.rs
index 0c79d4be17..7356e2dbc6 100644
--- a/crates/hyperswitch_interfaces/src/api/gateway.rs
+++ b/crates/hyperswitch_interfaces/src/api/gateway.rs
@@ -96,6 +96,49 @@ pub trait PaymentGateway<
) -> CustomResult<FlowOutput, ConnectorError>;
}
+/// Payout gateway trait
+///
+/// Defines the interface for executing payout operations through different gateway types.
+/// Implementations include DirectGateway and flow-specific UCS gateways.
+///
+/// # Type Parameters
+/// * `State` - Application state (e.g., SessionState)
+/// * `ConnectorData` - Connector-specific data type
+/// * `F` - Flow type (e.g., domain::Authorize, domain::PSync)
+/// * `Req` - Request data type
+/// * `Resp` - Response data type
+/// * `Context` - Gateway context type (must implement GatewayContext trait)
+#[async_trait]
+#[allow(clippy::too_many_arguments)]
+pub trait PayoutGateway<
+ State,
+ ConnectorData,
+ F,
+ Req,
+ Resp,
+ Context,
+ FlowOutput = RouterData<F, Req, Resp>,
+>: Send + Sync where
+ State: Clone + Send + Sync + 'static + ApiClientWrapper,
+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,
+ F: Clone + std::fmt::Debug + Send + Sync + 'static,
+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,
+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,
+ Context: GatewayContext,
+{
+ /// Execute payout gateway operation
+ async fn execute(
+ self: Box<Self>,
+ state: &State,
+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,
+ router_data: &RouterData<F, Req, Resp>,
+ call_connector_action: CallConnectorAction,
+ connector_request: Option<Request>,
+ return_raw_connector_response: Option<bool>,
+ context: Context,
+ ) -> CustomResult<FlowOutput, ConnectorError>;
+}
+
/// Direct gateway implementation
///
/// Executes payment operations through traditional HTTP connector integration.
@@ -138,6 +181,41 @@ where
}
}
+#[async_trait]
+impl<State, ConnectorData, F, Req, Resp, Context>
+ PayoutGateway<State, ConnectorData, F, Req, Resp, Context> for DirectGateway
+where
+ State: Clone + Send + Sync + 'static + ApiClientWrapper,
+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,
+ F: Clone + std::fmt::Debug + Send + Sync + 'static,
+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,
+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,
+ Context: GatewayContext + 'static,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &State,
+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,
+ router_data: &RouterData<F, Req, Resp>,
+ call_connector_action: CallConnectorAction,
+ connector_request: Option<Request>,
+ return_raw_connector_response: Option<bool>,
+ _context: Context,
+ ) -> CustomResult<RouterData<F, Req, Resp>, ConnectorError> {
+ // Direct gateway delegates to the existing execute_connector_processing_step
+ // This maintains backward compatibility with the traditional HTTP-based flow
+ api_client::execute_connector_processing_step(
+ state,
+ connector_integration,
+ router_data,
+ call_connector_action,
+ connector_request,
+ return_raw_connector_response,
+ )
+ .await
+ }
+}
+
#[async_trait]
impl<State, ConnectorData, F, Req, Resp, Context, T>
PaymentGateway<
@@ -211,6 +289,35 @@ pub trait FlowGateway<
) -> Box<dyn PaymentGateway<State, ConnectorData, Self, Req, Resp, Context, FlowOutput>>;
}
+/// Payout Flow gateway trait for determining execution path
+///
+/// This trait allows flows to specify which gateway implementation should be used
+/// based on the execution path. Each flow implements this trait to provide
+/// flow-specific gateway selection logic.
+pub trait PayoutFlowGateway<
+ State,
+ ConnectorData,
+ Req,
+ Resp,
+ Context,
+ FlowOutput = RouterData<Self, Req, Resp>,
+>: Clone + std::fmt::Debug + Send + Sync + 'static where
+ State: Clone + Send + Sync + 'static + ApiClientWrapper,
+ ConnectorData: Clone + RouterDataConversion<Self, Req, Resp> + Send + Sync + 'static,
+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,
+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,
+ Context: GatewayContext,
+{
+ /// Get the appropriate gateway for this flow based on execution path
+ ///
+ /// Returns a boxed gateway implementation that can be either:
+ /// - DirectGateway for traditional HTTP connector integration
+ /// - Flow-specific UCS gateway for gRPC integration
+ fn get_payout_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<dyn PayoutGateway<State, ConnectorData, Self, Req, Resp, Context, FlowOutput>>;
+}
+
/// Execute payment gateway operation (backward compatible version)
///
/// This version maintains backward compatibility by using direct execution when no context is provided.
@@ -344,3 +451,137 @@ where
}
}
}
+
+/// Execute payout gateway operation (backward compatible version)
+///
+/// This version maintains backward compatibility by using direct execution when no context is provided.
+/// Use `execute_payout_gateway_with_context` for UCS support.
+pub async fn execute_payout_gateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>(
+ state: &State,
+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,
+ router_data: &RouterData<F, Req, Resp>,
+ call_connector_action: CallConnectorAction,
+ connector_request: Option<Request>,
+ return_raw_connector_response: Option<bool>,
+ context: Context,
+) -> CustomResult<FlowOutput, ConnectorError>
+where
+ State: Clone + Send + Sync + 'static + ApiClientWrapper + helpers::GetComparisonServiceConfig,
+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,
+ F: Clone
+ + std::fmt::Debug
+ + Send
+ + Sync
+ + 'static
+ + PayoutFlowGateway<State, ConnectorData, Req, Resp, Context, FlowOutput>,
+ Req: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,
+ Resp: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,
+ Context: GatewayContext + 'static,
+ FlowOutput: Clone + Send + Sync + GetRouterData<F, Req, Resp> + 'static,
+{
+ let execution_path = context.execution_path();
+
+ match execution_path {
+ ExecutionPath::Direct => {
+ let gateway: Box<
+ dyn PayoutGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>,
+ > = F::get_payout_gateway(ExecutionPath::Direct);
+ gateway
+ .execute(
+ state,
+ connector_integration,
+ router_data,
+ call_connector_action,
+ connector_request,
+ return_raw_connector_response,
+ context,
+ )
+ .await
+ }
+ ExecutionPath::UnifiedConnectorService => {
+ let gateway: Box<
+ dyn PayoutGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>,
+ > = F::get_payout_gateway(ExecutionPath::UnifiedConnectorService);
+
+ // Execute through selected gateway
+ let ucs_result = gateway
+ .execute(
+ state,
+ connector_integration,
+ router_data,
+ call_connector_action,
+ connector_request,
+ return_raw_connector_response,
+ context,
+ )
+ .await
+ .attach_printable("Gateway execution failed")?;
+ Ok(ucs_result)
+ }
+ ExecutionPath::ShadowUnifiedConnectorService => {
+ let gateway: Box<
+ dyn PayoutGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>,
+ > = F::get_payout_gateway(ExecutionPath::Direct);
+ let direct_router_data = gateway
+ .execute(
+ state,
+ connector_integration.clone_box(),
+ router_data,
+ call_connector_action.clone(),
+ connector_request,
+ return_raw_connector_response,
+ context.clone(),
+ )
+ .await?;
+ let state_clone = state.clone();
+ let router_data_clone = router_data.clone();
+ let direct_router_data_clone = direct_router_data.clone();
+ let return_raw_connector_response_clone = return_raw_connector_response;
+ let context_clone = context;
+ tokio::spawn(
+ async move {
+ let gateway: Box<
+ dyn PayoutGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>,
+ > = F::get_payout_gateway(ExecutionPath::ShadowUnifiedConnectorService);
+ let ucs_shadow_result = gateway
+ .execute(
+ &state_clone,
+ connector_integration,
+ &router_data_clone,
+ call_connector_action,
+ None,
+ return_raw_connector_response_clone,
+ context_clone,
+ )
+ .await
+ .attach_printable("Gateway execution failed");
+ // Send comparison data asynchronously
+ match ucs_shadow_result {
+ Ok(ucs_router_data) => {
+ // Send comparison data asynchronously
+ if let Some(comparison_service_config) =
+ state_clone.get_comparison_service_config()
+ {
+ let request_id = state_clone.get_request_id_str();
+ let _ =
+ helpers::serialize_router_data_and_send_to_comparison_service(
+ &state_clone,
+ direct_router_data_clone.get_router_data().clone(),
+ ucs_router_data.get_router_data().clone(),
+ comparison_service_config,
+ request_id,
+ )
+ .await;
+ };
+ }
+ Err(e) => {
+ logger::error!(error=?e, "UCS shadow execution failed");
+ }
+ }
+ }
+ .instrument(router_env::tracing::Span::current()),
+ );
+ Ok(direct_router_data)
+ }
+ }
+}
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index 319583da14..c383a30f33 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -165,6 +165,34 @@ pub enum UnifiedConnectorServiceError {
/// Failed to perform Payment Incremental Authorization from gRPC Server
#[error("Failed to perform Payment Incremental Authorization from gRPC Server")]
PaymentIncrementalAuthorizationFailure,
+
+ /// Failed to perform Payout Create from gRPC Server
+ #[error("Failed to perform Payout Create from gRPC Server")]
+ PayoutCreateFailure,
+
+ /// Failed to perform Payout Transfer from gRPC Server
+ #[error("Failed to perform Payout Transfer from gRPC Server")]
+ PayoutTransferFailure,
+
+ /// Failed to perform Payout Get from gRPC Server
+ #[error("Failed to perform Payout Get from gRPC Server")]
+ PayoutGetFailure,
+
+ /// Failed to perform Payout Void from gRPC Server
+ #[error("Failed to perform Payout Void from gRPC Server")]
+ PayoutVoidFailure,
+
+ /// Failed to perform Payout Stage from gRPC Server
+ #[error("Failed to perform Payout Stage from gRPC Server")]
+ PayoutStageFailure,
+
+ /// Failed to perform Payout Create Recipient from gRPC Server
+ #[error("Failed to perform Payout Create Recipient from gRPC Server")]
+ PayoutCreateRecipientFailure,
+
+ /// Failed to perform Payout Enroll Disburse Account from gRPC Server
+ #[error("Failed to perform Payout Enroll Disburse Account from gRPC Server")]
+ PayoutEnrollDisburseAccountFailure,
}
/// UCS Webhook transformation status
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 97c0770029..60d1d3a7aa 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -5088,6 +5088,7 @@ where
previous_gateway,
call_connector_action.clone(),
shadow_ucs_call_connector_action.clone(),
+ common_enums::TransactionType::Payment,
)
.await?;
@@ -5666,6 +5667,7 @@ where
previous_gateway,
call_connector_action.clone(),
None,
+ common_enums::TransactionType::Payment,
)
.await?;
@@ -5792,6 +5794,7 @@ where
previous_gateway,
call_connector_action.clone(),
None,
+ common_enums::TransactionType::Payment,
)
.await?;
let lineage_ids = grpc_client::LineageIds::new(
@@ -5988,6 +5991,7 @@ where
None,
call_connector_action.clone(),
None,
+ common_enums::TransactionType::Payment,
)
.await?;
@@ -7144,6 +7148,7 @@ where
None, // No previous gateway information required for session flow
call_connector_action.clone(),
None,
+ common_enums::TransactionType::Payment,
)
.await?;
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 9f5e7753cd..9d540eafda 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -1,6 +1,7 @@
#[cfg(feature = "olap")]
use strum::IntoEnumIterator;
pub mod access_token;
+pub mod gateway;
pub mod helpers;
#[cfg(feature = "payout_retry")]
pub mod retry;
@@ -26,13 +27,16 @@ use common_utils::{
use diesel_models::{
enums as storage_enums,
generic_link::{GenericLinkNew, PayoutLink},
+ types::FeatureMetadata,
CommonMandateReference, PayoutsMandateReference, PayoutsMandateReferenceRecord,
};
use error_stack::{report, ResultExt};
+use external_services::grpc_client;
#[cfg(feature = "olap")]
use futures::future::join_all;
use hyperswitch_domain_models::{self as domain_models, payment_methods::PaymentMethod};
-use hyperswitch_masking::{PeekInterface, Secret};
+use hyperswitch_interfaces::api::gateway as payout_gateway;
+use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "payout_retry")]
use retry::GsmValidation;
use router_env::{instrument, logger, tracing, Env};
@@ -51,7 +55,11 @@ use crate::{
errors::{
self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt,
},
- payments::{self, customers, helpers as payment_helpers},
+ payments::{
+ self, customers, gateway::context as gateway_context, helpers as payment_helpers,
+ HeaderPayload,
+ },
+ unified_connector_service::should_call_unified_connector_service,
utils as core_utils,
},
db::StorageInterface,
@@ -173,6 +181,7 @@ pub async fn get_connector_choice(
pub async fn make_connector_decision(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
dimensions: DimensionsWithMerchantId,
@@ -182,6 +191,7 @@ pub async fn make_connector_decision(
Box::pin(call_connector_payout(
state,
platform,
+ header_payload.clone(),
&routing_data.connector_data,
payout_data,
&dimensions,
@@ -204,6 +214,7 @@ pub async fn make_connector_decision(
payout_data,
platform,
&dimensions,
+ header_payload.clone(),
))
.await?;
}
@@ -219,6 +230,7 @@ pub async fn make_connector_decision(
Box::pin(call_connector_payout(
state,
platform,
+ header_payload.clone(),
&connector_data,
payout_data,
&dimensions,
@@ -242,6 +254,7 @@ pub async fn make_connector_decision(
payout_data,
platform,
&dimensions,
+ header_payload.clone(),
))
.await?;
}
@@ -260,6 +273,7 @@ pub async fn make_connector_decision(
payout_data,
platform,
&dimensions,
+ header_payload,
))
.await?;
}
@@ -278,6 +292,7 @@ pub async fn make_connector_decision(
pub async fn payouts_core(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
payout_data: &mut PayoutData,
routing_algorithm: Option<serde_json::Value>,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
@@ -300,6 +315,7 @@ pub async fn payouts_core(
Box::pin(make_connector_decision(
state,
platform,
+ header_payload,
connector_call_type,
payout_data,
dimensions,
@@ -312,6 +328,7 @@ pub async fn payouts_core(
pub async fn payouts_core(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
payout_data: &mut PayoutData,
routing_algorithm: Option<serde_json::Value>,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
@@ -324,6 +341,7 @@ pub async fn payouts_core(
pub async fn payouts_create_core(
state: SessionState,
platform: domain::Platform,
+ header_payload: HeaderPayload,
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
// Validate create request
@@ -374,6 +392,7 @@ pub async fn payouts_create_core(
payouts_core(
&state,
&platform,
+ header_payload,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
@@ -390,6 +409,7 @@ pub async fn payouts_confirm_core(
state: SessionState,
platform: domain::Platform,
req: payouts::PayoutCreateRequest,
+ header_payload: HeaderPayload,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let dimensions = configs::dimension_state::Dimensions::new()
.with_merchant_id(platform.get_processor().get_account().get_id().clone());
@@ -441,6 +461,7 @@ pub async fn payouts_confirm_core(
payouts_core(
&state,
&platform,
+ header_payload,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
@@ -455,6 +476,7 @@ pub async fn payouts_update_core(
state: SessionState,
platform: domain::Platform,
req: payouts::PayoutCreateRequest,
+ header_payload: HeaderPayload,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let dimensions = configs::dimension_state::Dimensions::new()
.with_merchant_id(platform.get_processor().get_account().get_id().clone());
@@ -515,6 +537,7 @@ pub async fn payouts_update_core(
payouts_core(
&state,
&platform,
+ header_payload,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
@@ -531,6 +554,7 @@ pub async fn payouts_update_core(
pub async fn payouts_retrieve_core(
state: SessionState,
platform: domain::Platform,
+ header_payload: HeaderPayload,
profile_id: Option<id_type::ProfileId>,
req: payouts::PayoutRetrieveRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
@@ -560,6 +584,7 @@ pub async fn payouts_retrieve_core(
Box::pin(complete_payout_retrieve(
&state,
&platform,
+ header_payload,
connector_call_type,
&mut payout_data,
))
@@ -575,6 +600,7 @@ pub async fn payouts_retrieve_core(
pub async fn payouts_cancel_core(
state: SessionState,
platform: domain::Platform,
+ header_payload: HeaderPayload,
req: payouts::PayoutActionRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
@@ -658,6 +684,7 @@ pub async fn payouts_cancel_core(
Box::pin(cancel_payout(
&state,
&platform,
+ header_payload,
&connector_data,
&mut payout_data,
))
@@ -672,6 +699,7 @@ pub async fn payouts_cancel_core(
pub async fn payouts_fulfill_core(
state: SessionState,
platform: domain::Platform,
+ header_payload: HeaderPayload,
req: payouts::PayoutActionRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
@@ -723,6 +751,7 @@ pub async fn payouts_fulfill_core(
Box::pin(fulfill_payout(
&state,
&platform,
+ header_payload,
&connector_data,
&mut payout_data,
&dimensions,
@@ -1088,6 +1117,7 @@ pub async fn get_payout_filters_core(
pub async fn call_connector_payout(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
dimensions: &DimensionsWithMerchantId,
@@ -1154,6 +1184,7 @@ pub async fn call_connector_payout(
Box::pin(complete_create_recipient(
state,
platform,
+ header_payload.clone(),
connector_data,
payout_data,
))
@@ -1162,6 +1193,7 @@ pub async fn call_connector_payout(
Box::pin(complete_create_recipient_disburse_account(
state,
platform,
+ header_payload.clone(),
connector_data,
payout_data,
))
@@ -1170,6 +1202,7 @@ pub async fn call_connector_payout(
Box::pin(complete_create_payout(
state,
platform,
+ header_payload.clone(),
connector_data,
payout_data,
))
@@ -1181,6 +1214,7 @@ pub async fn call_connector_payout(
Box::pin(fulfill_payout(
state,
platform,
+ header_payload,
connector_data,
payout_data,
dimensions,
@@ -1195,6 +1229,7 @@ pub async fn call_connector_payout(
pub async fn complete_create_recipient(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -1212,6 +1247,7 @@ pub async fn complete_create_recipient(
Box::pin(create_recipient(
state,
platform,
+ header_payload,
connector_data,
payout_data,
))
@@ -1226,6 +1262,7 @@ pub async fn complete_create_recipient(
pub async fn create_recipient(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -1251,6 +1288,16 @@ pub async fn create_recipient(
core_utils::construct_payout_router_data(state, connector_data, platform, payout_data)
.await?;
+ let (gateway_context, updated_state) = decide_unified_connector_service_payout(
+ state,
+ platform,
+ header_payload,
+ &router_data,
+ connector_data,
+ payout_data,
+ )
+ .await?;
+
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipient,
@@ -1259,20 +1306,21 @@ pub async fn create_recipient(
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
- let router_resp = services::execute_connector_processing_step(
- state,
+ let router_resp = payout_gateway::execute_payout_gateway(
+ &updated_state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
+ gateway_context.clone(),
)
.await
.to_payout_failed_response()?;
match router_resp.response {
Ok(recipient_create_data) => {
- let db = &*state.store;
+ let db = &*updated_state.store;
if let Some(customer) = customer_details {
if let Some(updated_customer) =
customers::update_connector_customer_in_customers(
@@ -1306,7 +1354,7 @@ pub async fn create_recipient(
let customer_id = customer.get_id().clone();
payout_data.customer_details = Some(
db.update_customer_by_global_id(
- &state.into(),
+ &updated_state.into(),
&customer_id,
customer,
updated_customer,
@@ -1324,10 +1372,10 @@ pub async fn create_recipient(
// Add next step to ProcessTracker
if recipient_create_data.should_add_next_step_to_process_tracker {
add_external_account_addition_task(
- &*state.store,
+ &*updated_state.store,
payout_data,
common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)),
- state.conf.application_source,
+ updated_state.conf.application_source,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -1419,7 +1467,7 @@ pub async fn create_recipient(
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
- state,
+ &updated_state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
@@ -1488,6 +1536,7 @@ pub async fn create_recipient(
pub async fn create_recipient(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -1673,6 +1722,7 @@ pub async fn check_payout_eligibility(
pub async fn complete_create_payout(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -1728,9 +1778,15 @@ pub async fn complete_create_payout(
.attach_printable("Error updating payouts in db")?;
} else {
// create payout_object in connector as well as router
- Box::pin(create_payout(state, platform, connector_data, payout_data))
- .await
- .attach_printable("Payout creation failed for given Payout request")?;
+ Box::pin(create_payout(
+ state,
+ platform,
+ header_payload,
+ connector_data,
+ payout_data,
+ ))
+ .await
+ .attach_printable("Payout creation failed for given Payout request")?;
}
}
Ok(())
@@ -1739,6 +1795,7 @@ pub async fn complete_create_payout(
pub async fn create_payout(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -1747,24 +1804,36 @@ pub async fn create_payout(
core_utils::construct_payout_router_data(state, connector_data, platform, payout_data)
.await?;
+ let (gateway_context, updated_state) = decide_unified_connector_service_payout(
+ state,
+ platform,
+ header_payload,
+ &router_data,
+ connector_data,
+ payout_data,
+ )
+ .await?;
+
// 2. Get/Create access token
access_token::create_access_token(
- state,
+ &updated_state,
connector_data,
platform,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
+ &gateway_context,
)
.await?;
- // 3. Execute pretasks
+ // 4. Execute pretasks
if helpers::should_continue_payout(&router_data) {
- complete_payout_quote_steps_if_required(state, connector_data, &mut router_data).await?;
+ complete_payout_quote_steps_if_required(&updated_state, connector_data, &mut router_data)
+ .await?;
};
let connector_meta_data = router_data.connector_meta_data.clone();
- // 4. Call connector service
+ // 5. Call connector service (UCS or Direct based on execution path)
let router_data_resp = match helpers::should_continue_payout(&router_data) {
true => {
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
@@ -1773,13 +1842,14 @@ pub async fn create_payout(
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
- services::execute_connector_processing_step(
- state,
+ payout_gateway::execute_payout_gateway(
+ &updated_state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
+ gateway_context.clone(),
)
.await
.to_payout_failed_response()?
@@ -1935,6 +2005,7 @@ async fn complete_payout_quote_steps_if_required<F>(
pub async fn complete_payout_retrieve(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -1943,6 +2014,7 @@ pub async fn complete_payout_retrieve(
Box::pin(create_payout_retrieve(
state,
platform,
+ header_payload,
&routing_data.connector_data,
payout_data,
))
@@ -1971,6 +2043,7 @@ pub async fn complete_payout_retrieve(
pub async fn create_payout_retrieve(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -1979,13 +2052,24 @@ pub async fn create_payout_retrieve(
core_utils::construct_payout_router_data(state, connector_data, platform, payout_data)
.await?;
+ let (gateway_context, updated_state) = decide_unified_connector_service_payout(
+ state,
+ platform,
+ header_payload,
+ &router_data,
+ connector_data,
+ payout_data,
+ )
+ .await?;
+
// 2. Get/Create access token
access_token::create_access_token(
- state,
+ &updated_state,
connector_data,
platform,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
+ &gateway_context,
)
.await?;
@@ -1998,13 +2082,14 @@ pub async fn create_payout_retrieve(
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
- services::execute_connector_processing_step(
- state,
+ payout_gateway::execute_payout_gateway(
+ &updated_state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
+ gateway_context.clone(),
)
.await
.to_payout_failed_response()?
@@ -2013,7 +2098,8 @@ pub async fn create_payout_retrieve(
};
// 4. Process data returned by the connector
- update_retrieve_payout_tracker(state, platform, payout_data, &router_data_resp).await?;
+ update_retrieve_payout_tracker(&updated_state, platform, payout_data, &router_data_resp)
+ .await?;
Ok(())
}
@@ -2125,6 +2211,7 @@ pub async fn update_retrieve_payout_tracker<F, T>(
pub async fn complete_create_recipient_disburse_account(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -2142,6 +2229,7 @@ pub async fn complete_create_recipient_disburse_account(
Box::pin(create_recipient_disburse_account(
state,
platform,
+ header_payload,
connector_data,
payout_data,
))
@@ -2154,6 +2242,7 @@ pub async fn complete_create_recipient_disburse_account(
pub async fn create_recipient_disburse_account(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -2162,6 +2251,16 @@ pub async fn create_recipient_disburse_account(
core_utils::construct_payout_router_data(state, connector_data, platform, payout_data)
.await?;
+ let (gateway_context, updated_state) = decide_unified_connector_service_payout(
+ state,
+ platform,
+ header_payload,
+ &router_data,
+ connector_data,
+ payout_data,
+ )
+ .await?;
+
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipientAccount,
@@ -2170,19 +2269,20 @@ pub async fn create_recipient_disburse_account(
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
- let router_data_resp = services::execute_connector_processing_step(
- state,
+ let router_data_resp = payout_gateway::execute_payout_gateway(
+ &updated_state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
+ gateway_context.clone(),
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
- let db = &*state.store;
+ let db = &*updated_state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
@@ -2280,7 +2380,7 @@ pub async fn create_recipient_disburse_account(
if let Some(customer_id) = customer_id {
helpers::save_payout_data_to_locker(
- state,
+ &updated_state,
payout_data,
&customer_id,
payout_method_data,
@@ -2296,7 +2396,7 @@ pub async fn create_recipient_disburse_account(
Err(err) => {
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
- state,
+ &updated_state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
@@ -2353,6 +2453,7 @@ pub async fn create_recipient_disburse_account(
pub async fn cancel_payout(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
@@ -2361,6 +2462,16 @@ pub async fn cancel_payout(
core_utils::construct_payout_router_data(state, connector_data, platform, payout_data)
.await?;
+ let (gateway_context, updated_state) = decide_unified_connector_service_payout(
+ state,
+ platform,
+ header_payload,
+ &router_data,
+ connector_data,
+ payout_data,
+ )
+ .await?;
+
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoCancel,
@@ -2369,19 +2480,20 @@ pub async fn cancel_payout(
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
- let router_data_resp = services::execute_connector_processing_step(
- state,
+ let router_data_resp = payout_gateway::execute_payout_gateway(
+ &updated_state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
+ gateway_context.clone(),
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
- let db = &*state.store;
+ let db = &*updated_state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let status = payout_response_data
@@ -2422,7 +2534,7 @@ pub async fn cancel_payout(
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
- state,
+ &updated_state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
@@ -2489,6 +2601,7 @@ pub async fn cancel_payout(
pub async fn fulfill_payout(
state: &SessionState,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
dimensions: &DimensionsWithMerchantId,
@@ -2498,13 +2611,24 @@ pub async fn fulfill_payout(
core_utils::construct_payout_router_data(state, connector_data, platform, payout_data)
.await?;
+ let (gateway_context, updated_state) = decide_unified_connector_service_payout(
+ state,
+ platform,
+ header_payload,
+ &router_data,
+ connector_data,
+ payout_data,
+ )
+ .await?;
+
// 2. Get/Create access token
access_token::create_access_token(
- state,
+ &updated_state,
connector_data,
platform,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
+ &gateway_context,
)
.await?;
@@ -2515,9 +2639,9 @@ pub async fn fulfill_payout(
true => {
// add payout sync task to process tracker
payout_sync::PayoutSyncWorkFlow::add_payout_sync_task_to_process_tracker(
- state,
+ &updated_state,
payout_data,
- state.conf.application_source,
+ updated_state.conf.application_source,
&dimension_with_connector,
)
.await
@@ -2530,13 +2654,14 @@ pub async fn fulfill_payout(
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
- services::execute_connector_processing_step(
- state,
+ payout_gateway::execute_payout_gateway(
+ &updated_state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
+ gateway_context.clone(),
)
.await
.to_payout_failed_response()?
@@ -2591,7 +2716,7 @@ pub async fn fulfill_payout(
if let Some(customer_id) = payout_data.payouts.customer_id.clone() {
helpers::save_payout_data_to_locker(
- state,
+ &updated_state,
payout_data,
&customer_id,
&payout_method_data,
@@ -2607,7 +2732,7 @@ pub async fn fulfill_payout(
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
- state,
+ &updated_state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
@@ -3663,3 +3788,148 @@ pub async fn payouts_manual_update_core(
.into())
}
}
+
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
+#[allow(clippy::type_complexity)]
+#[instrument(skip_all)]
+pub async fn decide_unified_connector_service_payout<F: Clone>(
+ state: &SessionState,
+ platform: &domain::Platform,
+ header_payload: HeaderPayload,
+ router_data: &types::RouterData<F, types::PayoutsData, types::PayoutsResponseData>,
+ connector_data: &api::ConnectorData,
+ payout_data: &mut PayoutData,
+) -> RouterResult<(gateway_context::RouterGatewayContext, SessionState)> {
+ // Extract previous gateway from payment data
+ let previous_gateway = extract_gateway_system_from_payouts(payout_data);
+
+ let (execution_path, updated_state) = should_call_unified_connector_service(
+ state,
+ platform.get_processor(),
+ router_data,
+ previous_gateway,
+ common_enums::enums::CallConnectorAction::Trigger,
+ None,
+ common_enums::TransactionType::Payout,
+ )
+ .await?;
+
+ let lineage_ids = grpc_client::LineageIds::new(
+ payout_data.payouts.merchant_id.clone(),
+ payout_data.profile_id.clone(),
+ );
+
+ let execution_mode = match execution_path {
+ common_enums::enums::ExecutionPath::UnifiedConnectorService => {
+ common_enums::enums::ExecutionMode::Primary
+ }
+ common_enums::enums::ExecutionPath::ShadowUnifiedConnectorService => {
+ common_enums::enums::ExecutionMode::Shadow
+ }
+ // ExecutionMode is irrelevant for Direct path in this context
+ common_enums::enums::ExecutionPath::Direct => {
+ common_enums::enums::ExecutionMode::NotApplicable
+ }
+ };
+
+ let merchant_connector_account = match payout_data.merchant_connector_account.clone() {
+ Some(mca) => mca,
+ None => {
+ // If not present, perform the async fetch
+ get_mca_from_profile_id(
+ state,
+ platform,
+ &payout_data.profile_id,
+ &connector_data.connector_name.to_string(),
+ payout_data
+ .payout_attempt
+ .merchant_connector_id
+ .as_ref() // Use as_ref() directly on the existing Option
+ .or(connector_data.merchant_connector_id.as_ref()),
+ )
+ .await?
+ }
+ };
+
+ let gateway_context = gateway_context::RouterGatewayContext {
+ creds_identifier: None,
+ processor: platform.get_processor().clone(),
+ header_payload: header_payload.clone(),
+ lineage_ids,
+ merchant_connector_account,
+ execution_path,
+ execution_mode,
+ };
+ // Update feature metadata to track Direct routing usage for stickiness
+ update_gateway_system_in_payout_metadata(payout_data, gateway_context.get_gateway_system())?;
+ Ok((gateway_context, updated_state))
+}
+
+/// Extracts the gateway system from the payout's feature metadata
+/// Returns None if metadata is missing, corrupted, or doesn't contain gateway_system
+pub fn extract_gateway_system_from_payouts(
+ payout_data: &mut PayoutData,
+) -> Option<common_enums::GatewaySystem> {
+ #[cfg(feature = "v1")]
+ {
+ payout_data.payouts.metadata.as_ref().and_then(|metadata| {
+ // Try to parse the JSON value as FeatureMetadata
+ // Log errors but don't fail the flow for corrupted metadata
+ match serde_json::from_value::<FeatureMetadata>(metadata.clone().expose()) {
+ Ok(feature_metadata) => feature_metadata.gateway_system,
+ Err(err) => {
+ router_env::logger::warn!(
+ "Failed to parse metadata for gateway_system extraction: {}",
+ err
+ );
+ None
+ }
+ }
+ })
+ }
+ #[cfg(feature = "v2")]
+ {
+ None // V2 does not use feature metadata for gateway system tracking
+ }
+}
+
+#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
+#[allow(clippy::type_complexity)]
+#[instrument(skip_all)]
+pub async fn decide_unified_connector_service_payout<F: Clone>(
+ state: &SessionState,
+ platform: &domain::Platform,
+ header_payload: HeaderPayload,
+ router_data: &types::RouterData<F, types::PayoutsData, types::PayoutsResponseData>,
+ connector_data: &api::ConnectorData,
+ payout_data: &mut PayoutData,
+) -> RouterResult<(gateway_context::RouterGatewayContext, SessionState)> {
+ todo!()
+}
+
+/// Updates the payout intent's metadata to track the gateway system being used
+#[cfg(feature = "v1")]
+pub fn update_gateway_system_in_payout_metadata(
+ payout_data: &mut PayoutData,
+ gateway_system: common_enums::GatewaySystem,
+) -> RouterResult<()> {
+ let existing_metadata = payout_data.payouts.metadata.as_ref();
+
+ let mut feature_metadata = existing_metadata
+ .and_then(|metadata| {
+ serde_json::from_value::<FeatureMetadata>(metadata.clone().expose()).ok()
+ })
+ .unwrap_or_default();
+
+ feature_metadata.gateway_system = Some(gateway_system);
+
+ let updated_metadata = serde_json::to_value(feature_metadata)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize feature metadata")?;
+
+ payout_data.payouts.metadata = Some(Secret::new(updated_metadata.clone()));
+
+ Ok(())
+}
diff --git a/crates/router/src/core/payouts/access_token.rs b/crates/router/src/core/payouts/access_token.rs
index f7fa11e353..3064016e53 100644
--- a/crates/router/src/core/payouts/access_token.rs
+++ b/crates/router/src/core/payouts/access_token.rs
@@ -1,11 +1,14 @@
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
-use hyperswitch_interfaces::{api::ConnectorCommon, consts};
+use hyperswitch_interfaces::{
+ api::{gateway, ConnectorCommon},
+ consts,
+};
use crate::{
core::{
errors::{self, RouterResult},
- payments,
+ payments::{self, gateway::context as gateway_context},
},
routes::{metrics, SessionState},
services,
@@ -22,10 +25,17 @@ pub async fn create_access_token<F: Clone + 'static>(
platform: &domain::Platform,
router_data: &mut types::PayoutsRouterData<F>,
payout_type: Option<enums::PayoutType>,
+ gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<()> {
- let connector_access_token =
- add_access_token_for_payout(state, connector_data, platform, router_data, payout_type)
- .await?;
+ let connector_access_token = add_access_token_for_payout(
+ state,
+ connector_data,
+ platform,
+ router_data,
+ gateway_context,
+ payout_type,
+ )
+ .await?;
if connector_access_token.connector_supports_access_token {
match connector_access_token.access_token_result {
@@ -47,6 +57,7 @@ pub async fn add_access_token_for_payout<F: Clone + 'static>(
connector: &api_types::ConnectorData,
platform: &domain::Platform,
router_data: &types::PayoutsRouterData<F>,
+ gateway_context: &gateway_context::RouterGatewayContext,
payout_type: Option<enums::PayoutType>,
) -> RouterResult<types::AddAccessTokenResult> {
if connector
@@ -91,21 +102,27 @@ pub async fn add_access_token_for_payout<F: Clone + 'static>(
refresh_token_request_data,
refresh_token_response_data,
);
- refresh_connector_auth(state, connector, platform, &refresh_token_router_data)
- .await?
- .async_map(|access_token| async {
- //Store the access token in db
- let store = &*state.store;
- // This error should not be propagated, we don't want payments to fail once we have
- // the access token, the next request will create new access token
- let _ = store
- .set_access_token(key, access_token.clone())
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("DB error when setting the access token");
- Some(access_token)
- })
- .await
+ refresh_connector_auth(
+ state,
+ connector,
+ platform,
+ &refresh_token_router_data,
+ gateway_context,
+ )
+ .await?
+ .async_map(|access_token| async {
+ //Store the access token in db
+ let store = &*state.store;
+ // This error should not be propagated, we don't want payments to fail once we have
+ // the access token, the next request will create new access token
+ let _ = store
+ .set_access_token(key, access_token.clone())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("DB error when setting the access token");
+ Some(access_token)
+ })
+ .await
}
};
@@ -131,6 +148,7 @@ pub async fn refresh_connector_auth(
types::AccessTokenRequestData,
types::AccessToken,
>,
+ gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Result<types::AccessToken, types::ErrorResponse>> {
let connector_integration: services::BoxedAccessTokenConnectorIntegrationInterface<
api_types::AccessTokenAuth,
@@ -138,13 +156,14 @@ pub async fn refresh_connector_auth(
types::AccessToken,
> = connector.connector.get_connector_integration();
- let access_token_router_data_result = services::execute_connector_processing_step(
+ let access_token_router_data_result = gateway::execute_payment_gateway(
state,
connector_integration,
router_data,
payments::CallConnectorAction::Trigger,
None,
None,
+ gateway_context.clone(),
)
.await;
diff --git a/crates/router/src/core/payouts/gateway.rs b/crates/router/src/core/payouts/gateway.rs
new file mode 100644
index 0000000000..bcb4eb36c5
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway.rs
@@ -0,0 +1,8 @@
+pub mod cancel_gateway;
+pub mod context;
+pub mod create_gateway;
+pub mod fulfill_gateway;
+pub mod quote_gateway;
+pub mod recipient_account_gateway;
+pub mod recipient_gateway;
+pub mod sync_gateway;
diff --git a/crates/router/src/core/payouts/gateway/cancel_gateway.rs b/crates/router/src/core/payouts/gateway/cancel_gateway.rs
new file mode 100644
index 0000000000..e9e862d6bd
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway/cancel_gateway.rs
@@ -0,0 +1,182 @@
+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 payout_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},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PayoutGateway Implementation for domain::PoCancel
+// =============================================================================
+
+#[async_trait]
+impl<RCD>
+ payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoCancel
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let processor = &context.processor;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ processor,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let merchant_reference_id = unified_connector_service::parse_merchant_payout_reference_id(
+ header_payload
+ .x_reference_id
+ .as_deref()
+ .unwrap_or(router_data.request.payout_id.get_string_repr()),
+ )
+ .map(ucs_types::UcsReferenceId::Payout);
+ let resource_id = id_type::PayoutResourceId::from_str(router_data.attempt_id.as_str())
+ .inspect_err(|err| logger::warn!(error = ?err, "Invalid Payout Resource Id found"))
+ .ok()
+ .map(ucs_types::UcsResourceId::PayoutAttempt);
+
+ let grpc_headers = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .resource_id(resource_id)
+ .lineage_ids(lineage_ids);
+
+ logger::debug!("Granular Gateway: Payout cancel flow");
+ let granular_payout_void_request =
+ payments_grpc::PayoutServiceVoidRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payout Void Request")?;
+
+ let updated_router_data =
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ granular_payout_void_request,
+ grpc_headers,
+ unified_connector_service_execution_mode,
+ |mut router_data, granular_payout_void_request, grpc_headers| async move {
+ let response = Box::pin(client.payout_void(
+ granular_payout_void_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to void payout")?;
+
+ let payout_void_response = response.into_inner();
+
+ let ucs_data = types::UcsPayoutVoidResponseData::foreign_try_from((
+ payout_void_response.clone(),
+ common_enums::PayoutStatus::Cancelled,
+ ))
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = ucs_data.router_data_response.inspect_err(|_| {
+ logger::debug!("Error in UCS router data response");
+ });
+ router_data.response = router_data_response;
+
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
+
+ Ok((router_data, (), payout_void_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+impl<RCD>
+ payout_gateway::PayoutFlowGateway<
+ SessionState,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoCancel
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ fn get_payout_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payout_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/gateway/context.rs b/crates/router/src/core/payouts/gateway/context.rs
new file mode 100644
index 0000000000..a268c08125
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway/context.rs
@@ -0,0 +1,41 @@
+//! Gateway context for payout operations
+//!
+//! This module provides the context structure needed for payout gateway execution,
+//! similar to the payment gateway context.
+
+use common_enums::{ExecutionMode, ExecutionPath};
+use external_services::grpc_client::LineageIds;
+use hyperswitch_domain_models::payments::HeaderPayload;
+
+use crate::core::payments::helpers::MerchantConnectorAccountType;
+
+/// Context information required for payout gateway execution
+#[derive(Clone)]
+pub struct RouterGatewayContext {
+ /// Credentials identifier for connector authentication
+ pub creds_identifier: Option<String>,
+ /// Processor information
+ pub processor: hyperswitch_domain_models::platform::Processor,
+ /// HTTP header payload from the request
+ pub header_payload: HeaderPayload,
+ /// Lineage IDs for tracing and tracking
+ pub lineage_ids: LineageIds,
+ /// Merchant connector account details
+ pub merchant_connector_account: MerchantConnectorAccountType,
+ /// Execution path (Direct, UCS, or Shadow UCS)
+ pub execution_path: ExecutionPath,
+ /// Execution mode (Primary or Shadow)
+ pub execution_mode: ExecutionMode,
+}
+impl RouterGatewayContext {
+ /// Get the gateway system (Direct, UnifiedConnectorService, etc.)
+ pub fn get_gateway_system(&self) -> common_enums::GatewaySystem {
+ match self.execution_path {
+ ExecutionPath::Direct => common_enums::GatewaySystem::Direct,
+ ExecutionPath::UnifiedConnectorService => {
+ common_enums::GatewaySystem::UnifiedConnectorService
+ }
+ ExecutionPath::ShadowUnifiedConnectorService => common_enums::GatewaySystem::Direct,
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/gateway/create_gateway.rs b/crates/router/src/core/payouts/gateway/create_gateway.rs
new file mode 100644
index 0000000000..f82296b95c
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway/create_gateway.rs
@@ -0,0 +1,187 @@
+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 payout_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},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PayoutGateway Implementation for domain::PoCreate
+// =============================================================================
+
+#[async_trait]
+impl<RCD>
+ payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoCreate
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let processor = &context.processor;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ processor,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let merchant_reference_id = unified_connector_service::parse_merchant_payout_reference_id(
+ header_payload
+ .x_reference_id
+ .as_deref()
+ .unwrap_or(router_data.request.payout_id.get_string_repr()),
+ )
+ .map(ucs_types::UcsReferenceId::Payout);
+ let resource_id = id_type::PayoutResourceId::from_str(router_data.attempt_id.as_str())
+ .inspect_err(|err| {
+ logger::warn!(
+ error = ?err,
+ "Invalid Payout Resource Id found"
+ )
+ })
+ .ok()
+ .map(ucs_types::UcsResourceId::PayoutAttempt);
+
+ let grpc_headers = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .resource_id(resource_id)
+ .lineage_ids(lineage_ids);
+
+ logger::debug!("Granular Gateway: Payout create flow");
+ let granular_payout_create_request =
+ payments_grpc::PayoutServiceCreateRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payout Create Request")?;
+
+ let updated_router_data =
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ granular_payout_create_request,
+ grpc_headers,
+ unified_connector_service_execution_mode,
+ |mut router_data, granular_payout_create_request, grpc_headers| async move {
+ let response = Box::pin(client.payout_create(
+ granular_payout_create_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to create payout")?;
+
+ let payout_create_response = response.into_inner();
+
+ let ucs_data = types::UcsPayoutCreateResponseData::foreign_try_from((
+ payout_create_response.clone(),
+ common_enums::PayoutStatus::Pending,
+ ))
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = ucs_data.router_data_response.inspect_err(|_| {
+ logger::debug!("Error in UCS router data response");
+ });
+ router_data.response = router_data_response;
+
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
+
+ Ok((router_data, (), payout_create_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+impl<RCD>
+ payout_gateway::PayoutFlowGateway<
+ SessionState,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoCreate
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ fn get_payout_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payout_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/gateway/fulfill_gateway.rs b/crates/router/src/core/payouts/gateway/fulfill_gateway.rs
new file mode 100644
index 0000000000..061b274f2d
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway/fulfill_gateway.rs
@@ -0,0 +1,182 @@
+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 payout_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},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PayoutGateway Implementation for domain::PoFulfill
+// =============================================================================
+
+#[async_trait]
+impl<RCD>
+ payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoFulfill
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let processor = &context.processor;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ processor,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let merchant_reference_id = unified_connector_service::parse_merchant_payout_reference_id(
+ header_payload
+ .x_reference_id
+ .as_deref()
+ .unwrap_or(router_data.request.payout_id.get_string_repr()),
+ )
+ .map(ucs_types::UcsReferenceId::Payout);
+ let resource_id = id_type::PayoutResourceId::from_str(router_data.attempt_id.as_str())
+ .inspect_err(|err| logger::warn!(error = ?err, "Invalid Payout Resource Id found"))
+ .ok()
+ .map(ucs_types::UcsResourceId::PayoutAttempt);
+
+ let grpc_headers = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .resource_id(resource_id)
+ .lineage_ids(lineage_ids);
+
+ logger::debug!("Granular Gateway: Payout fulfill flow");
+ let granular_payout_transfer_request =
+ payments_grpc::PayoutServiceTransferRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payout Transfer Request")?;
+
+ let updated_router_data =
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ granular_payout_transfer_request,
+ grpc_headers,
+ unified_connector_service_execution_mode,
+ |mut router_data, granular_payout_transfer_request, grpc_headers| async move {
+ let response = Box::pin(client.payout_transfer(
+ granular_payout_transfer_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to transfer payout")?;
+
+ let payout_transfer_response = response.into_inner();
+
+ let ucs_data = types::UcsPayoutTransferResponseData::foreign_try_from((
+ payout_transfer_response.clone(),
+ common_enums::PayoutStatus::Pending,
+ ))
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = ucs_data.router_data_response.inspect_err(|_| {
+ logger::debug!("Error in UCS router data response");
+ });
+ router_data.response = router_data_response;
+
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
+
+ Ok((router_data, (), payout_transfer_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+impl<RCD>
+ payout_gateway::PayoutFlowGateway<
+ SessionState,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoFulfill
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ fn get_payout_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payout_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/gateway/quote_gateway.rs b/crates/router/src/core/payouts/gateway/quote_gateway.rs
new file mode 100644
index 0000000000..e32cd3b2e3
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway/quote_gateway.rs
@@ -0,0 +1,182 @@
+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 payout_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},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PayoutGateway Implementation for domain::PoQuote
+// =============================================================================
+
+#[async_trait]
+impl<RCD>
+ payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoQuote
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let processor = &context.processor;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ processor,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let merchant_reference_id = unified_connector_service::parse_merchant_payout_reference_id(
+ header_payload
+ .x_reference_id
+ .as_deref()
+ .unwrap_or(router_data.request.payout_id.get_string_repr()),
+ )
+ .map(ucs_types::UcsReferenceId::Payout);
+ let resource_id = id_type::PayoutResourceId::from_str(router_data.attempt_id.as_str())
+ .inspect_err(|err| logger::warn!(error = ?err, "Invalid Payout Resource Id found"))
+ .ok()
+ .map(ucs_types::UcsResourceId::PayoutAttempt);
+
+ let grpc_headers = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .resource_id(resource_id)
+ .lineage_ids(lineage_ids);
+
+ logger::debug!("Granular Gateway: Payout quote flow");
+ let granular_payout_stage_request =
+ payments_grpc::PayoutServiceStageRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payout Stage Request")?;
+
+ let updated_router_data =
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ granular_payout_stage_request,
+ grpc_headers,
+ unified_connector_service_execution_mode,
+ |mut router_data, granular_payout_stage_request, grpc_headers| async move {
+ let response = Box::pin(client.payout_stage(
+ granular_payout_stage_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to stage payout")?;
+
+ let payout_stage_response = response.into_inner();
+
+ let ucs_data = types::UcsPayoutStageResponseData::foreign_try_from((
+ payout_stage_response.clone(),
+ common_enums::PayoutStatus::Pending,
+ ))
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = ucs_data.router_data_response.inspect_err(|_| {
+ logger::debug!("Error in UCS router data response");
+ });
+ router_data.response = router_data_response;
+
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
+
+ Ok((router_data, (), payout_stage_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+impl<RCD>
+ payout_gateway::PayoutFlowGateway<
+ SessionState,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoQuote
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ fn get_payout_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payout_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs b/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs
new file mode 100644
index 0000000000..675486ff0d
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs
@@ -0,0 +1,181 @@
+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 payout_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},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PayoutGateway Implementation for domain::PoRecipientAccount
+// =============================================================================
+
+#[async_trait]
+impl<RCD>
+ payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoRecipientAccount
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let processor = &context.processor;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ processor,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let merchant_reference_id = unified_connector_service::parse_merchant_payout_reference_id(
+ header_payload
+ .x_reference_id
+ .as_deref()
+ .unwrap_or(router_data.request.payout_id.get_string_repr()),
+ )
+ .map(ucs_types::UcsReferenceId::Payout);
+ let resource_id = id_type::PayoutResourceId::from_str(router_data.attempt_id.as_str())
+ .inspect_err(|err| logger::warn!(error = ?err, "Invalid Payout Resource Id found"))
+ .ok()
+ .map(ucs_types::UcsResourceId::PayoutAttempt);
+
+ let grpc_headers = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .resource_id(resource_id)
+ .lineage_ids(lineage_ids);
+
+ logger::debug!("Granular Gateway: Payout recipient_account flow");
+ let granular_payout_enroll_disburse_account_request =
+ payments_grpc::PayoutServiceEnrollDisburseAccountRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payout Enroll Disburse Account Request")?;
+
+ let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ granular_payout_enroll_disburse_account_request,
+ grpc_headers,
+ unified_connector_service_execution_mode,
+ |mut router_data, granular_payout_enroll_disburse_account_request, grpc_headers| async move {
+ let response = Box::pin(client.payout_enroll_disburse_account(
+ granular_payout_enroll_disburse_account_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to enroll_disburse_account payout")?;
+
+ let payout_enroll_disburse_account_response = response.into_inner();
+
+ let ucs_data = types::UcsPayoutEnrollDisburseAccountResponseData::foreign_try_from((
+ payout_enroll_disburse_account_response.clone(),
+ common_enums::PayoutStatus::Pending,
+ ))
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = ucs_data.router_data_response.inspect_err(|_| {
+ logger::debug!("Error in UCS router data response");
+ });
+ router_data.response = router_data_response;
+
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
+
+ Ok((router_data, (), payout_enroll_disburse_account_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+impl<RCD>
+ payout_gateway::PayoutFlowGateway<
+ SessionState,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoRecipientAccount
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ fn get_payout_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payout_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/gateway/recipient_gateway.rs b/crates/router/src/core/payouts/gateway/recipient_gateway.rs
new file mode 100644
index 0000000000..7b859012a5
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway/recipient_gateway.rs
@@ -0,0 +1,181 @@
+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 payout_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},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PayoutGateway Implementation for domain::PoRecipient
+// =============================================================================
+
+#[async_trait]
+impl<RCD>
+ payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoRecipient
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let processor = &context.processor;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ processor,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let merchant_reference_id = unified_connector_service::parse_merchant_payout_reference_id(
+ header_payload
+ .x_reference_id
+ .as_deref()
+ .unwrap_or(router_data.request.payout_id.get_string_repr()),
+ )
+ .map(ucs_types::UcsReferenceId::Payout);
+ let resource_id = id_type::PayoutResourceId::from_str(router_data.attempt_id.as_str())
+ .inspect_err(|err| logger::warn!(error = ?err, "Invalid Payout Resource Id found"))
+ .ok()
+ .map(ucs_types::UcsResourceId::PayoutAttempt);
+
+ let grpc_headers = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .resource_id(resource_id)
+ .lineage_ids(lineage_ids);
+
+ logger::debug!("Granular Gateway: Payout recipient flow");
+ let granular_payout_create_recipient_request =
+ payments_grpc::PayoutServiceCreateRecipientRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payout Create Recipient Request")?;
+
+ let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ granular_payout_create_recipient_request,
+ grpc_headers,
+ unified_connector_service_execution_mode,
+ |mut router_data, granular_payout_create_recipient_request, grpc_headers| async move {
+ let response = Box::pin(client.payout_create_recipient(
+ granular_payout_create_recipient_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to create_recipient payout")?;
+
+ let payout_create_recipient_response = response.into_inner();
+
+ let ucs_data = types::UcsPayoutCreateRecipientResponseData::foreign_try_from((
+ payout_create_recipient_response.clone(),
+ common_enums::PayoutStatus::Pending,
+ ))
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = ucs_data.router_data_response.inspect_err(|_| {
+ logger::debug!("Error in UCS router data response");
+ });
+ router_data.response = router_data_response;
+
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
+
+ Ok((router_data, (), payout_create_recipient_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+impl<RCD>
+ payout_gateway::PayoutFlowGateway<
+ SessionState,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoRecipient
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ fn get_payout_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payout_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/gateway/sync_gateway.rs b/crates/router/src/core/payouts/gateway/sync_gateway.rs
new file mode 100644
index 0000000000..040859014c
--- /dev/null
+++ b/crates/router/src/core/payouts/gateway/sync_gateway.rs
@@ -0,0 +1,182 @@
+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 payout_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},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PayoutGateway Implementation for domain::PoSync
+// =============================================================================
+
+#[async_trait]
+impl<RCD>
+ payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoSync
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PayoutsData, types::PayoutsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let processor = &context.processor;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ processor,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let merchant_reference_id = unified_connector_service::parse_merchant_payout_reference_id(
+ header_payload
+ .x_reference_id
+ .as_deref()
+ .unwrap_or(router_data.request.payout_id.get_string_repr()),
+ )
+ .map(ucs_types::UcsReferenceId::Payout);
+ let resource_id = id_type::PayoutResourceId::from_str(router_data.attempt_id.as_str())
+ .inspect_err(|err| logger::warn!(error = ?err, "Invalid Payout Resource Id found"))
+ .ok()
+ .map(ucs_types::UcsResourceId::PayoutAttempt);
+
+ let grpc_headers = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .resource_id(resource_id)
+ .lineage_ids(lineage_ids);
+
+ logger::debug!("Granular Gateway: Payout sync flow");
+ let granular_payout_get_request =
+ payments_grpc::PayoutServiceGetRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payout Get Request")?;
+
+ let updated_router_data =
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ granular_payout_get_request,
+ grpc_headers,
+ unified_connector_service_execution_mode,
+ |mut router_data, granular_payout_get_request, grpc_headers| async move {
+ let response = Box::pin(client.payout_get(
+ granular_payout_get_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to get payout")?;
+
+ let payout_get_response = response.into_inner();
+
+ let ucs_data = types::UcsPayoutGetResponseData::foreign_try_from((
+ payout_get_response.clone(),
+ common_enums::PayoutStatus::Pending,
+ ))
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = ucs_data.router_data_response.inspect_err(|_| {
+ logger::debug!("Error in UCS router data response");
+ });
+ router_data.response = router_data_response;
+
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
+
+ Ok((router_data, (), payout_get_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+impl<RCD>
+ payout_gateway::PayoutFlowGateway<
+ SessionState,
+ RCD,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ > for domain::PoSync
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PayoutsData, types::PayoutsResponseData>,
+{
+ fn get_payout_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payout_gateway::PayoutGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PayoutsData,
+ types::PayoutsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payout_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs
index 61179d9ff3..835484e396 100644
--- a/crates/router/src/core/payouts/retry.rs
+++ b/crates/router/src/core/payouts/retry.rs
@@ -2,6 +2,7 @@ use std::vec::IntoIter;
use common_enums::PayoutRetryType;
use error_stack::ResultExt;
+use hyperswitch_domain_models::payments::HeaderPayload;
use router_env::{
logger,
tracing::{self, instrument},
@@ -30,6 +31,7 @@ pub async fn do_gsm_multiple_connector_actions(
payout_data: &mut PayoutData,
platform: &domain::Platform,
dimensions: &DimensionsWithMerchantId,
+ header_payload: HeaderPayload,
) -> RouterResult<()> {
let mut retries = None;
@@ -68,6 +70,7 @@ pub async fn do_gsm_multiple_connector_actions(
&state.clone(),
connector.to_owned(),
platform,
+ header_payload.clone(),
payout_data,
dimensions,
))
@@ -89,6 +92,7 @@ pub async fn do_gsm_single_connector_actions(
payout_data: &mut PayoutData,
platform: &domain::Platform,
dimensions: &DimensionsWithMerchantId,
+ header_payload: HeaderPayload,
) -> RouterResult<()> {
let mut retries = None;
@@ -125,6 +129,7 @@ pub async fn do_gsm_single_connector_actions(
&state.clone(),
original_connector_data.to_owned(),
platform,
+ header_payload.clone(),
payout_data,
dimensions,
))
@@ -208,6 +213,7 @@ pub async fn do_retry(
state: &routes::SessionState,
connector: api::ConnectorData,
platform: &domain::Platform,
+ header_payload: HeaderPayload,
payout_data: &mut PayoutData,
dimensions: &DimensionsWithMerchantId,
) -> RouterResult<()> {
@@ -218,6 +224,7 @@ pub async fn do_retry(
Box::pin(call_connector_payout(
state,
platform,
+ header_payload,
&connector,
payout_data,
dimensions,
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 1f13c86c33..cf23258981 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -231,6 +231,7 @@ pub async fn trigger_refund_to_gateway(
None, // No previous gateway information required for refunds
payments::CallConnectorAction::Trigger,
None,
+ common_enums::TransactionType::Payment,
)
.await?;
@@ -919,6 +920,7 @@ pub async fn sync_refund_with_gateway(
None, // No previous gateway information required for refunds
payments::CallConnectorAction::Trigger,
None,
+ common_enums::TransactionType::Payment,
)
.await?;
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 1b50d48e86..d5c9f1f5c5 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -36,7 +36,7 @@ use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::refunds,
router_request_types::RefundsData,
- router_response_types::{PaymentsResponseData, RefundsResponseData},
+ router_response_types::{PaymentsResponseData, PayoutsResponseData, RefundsResponseData},
};
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
@@ -306,6 +306,7 @@ pub async fn should_call_unified_connector_service<F: Clone, T, R>(
previous_gateway: Option<GatewaySystem>,
call_connector_action: CallConnectorAction,
shadow_ucs_call_connector_action: Option<CallConnectorAction>,
+ transaction_type: common_enums::TransactionType,
) -> RouterResult<(ExecutionPath, SessionState)>
where
R: Send + Sync + Clone,
@@ -323,13 +324,22 @@ where
// Check UCS availability using idiomatic helper
let ucs_availability = check_ucs_availability(state).await;
- let rollout_key = build_rollout_keys(
- merchant_id,
- connector_name,
- &flow_name,
- router_data.payment_method,
- router_data.payment_method_type,
- );
+ let rollout_key = match transaction_type {
+ common_enums::TransactionType::Payment
+ | common_enums::TransactionType::ThreeDsAuthentication => build_rollout_keys(
+ merchant_id,
+ connector_name,
+ &flow_name,
+ router_data.payment_method,
+ router_data.payment_method_type,
+ ),
+ common_enums::TransactionType::Payout => build_rollout_keys_for_payouts(
+ merchant_id,
+ connector_name,
+ &flow_name,
+ router_data.payment_method_type,
+ ),
+ };
// Determine connector integration type
let connector_integration_type =
@@ -590,6 +600,27 @@ fn build_rollout_keys(
}
}
+/// Build rollout keys based on flow type - include payment method type for payouts
+fn build_rollout_keys_for_payouts(
+ merchant_id: &str,
+ connector_name: &str,
+ flow_name: &str,
+ payment_method_type: Option<PaymentMethodType>,
+) -> String {
+ let payment_method_type_str = payment_method_type
+ .map(|data| data.to_string())
+ .unwrap_or_else(|| "unknown".to_string());
+
+ format!(
+ "{}_{}_{}_{}_{}",
+ consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
+ merchant_id,
+ connector_name,
+ payment_method_type_str,
+ flow_name
+ )
+}
+
/// Extracts the gateway system from the payment intent's feature metadata
/// Returns None if metadata is missing, corrupted, or doesn't contain gateway_system
pub fn extract_gateway_system_from_payment_intent<F: Clone, D>(
@@ -1782,6 +1813,17 @@ pub fn parse_merchant_reference_id(id: &str) -> Option<id_type::PaymentReference
.ok()
}
+pub fn parse_merchant_payout_reference_id(id: &str) -> Option<id_type::PayoutReferenceId> {
+ id_type::PayoutReferenceId::from_str(id)
+ .inspect_err(|err| {
+ logger::warn!(
+ error = ?err,
+ "Invalid Merchant Payout ReferenceId found"
+ )
+ })
+ .ok()
+}
+
#[cfg(feature = "v2")]
pub fn build_unified_connector_service_external_vault_proxy_metadata(
external_vault_merchant_connector_account: MerchantConnectorAccountTypeDetails,
@@ -2123,6 +2165,217 @@ pub fn handle_unified_connector_service_response_for_create_access_token(
Ok((access_token_result, status_code))
}
+/// Handle UCS payout create response and transform it to router data format
+impl
+ ForeignTryFrom<(
+ payments_grpc::PayoutServiceCreateResponse,
+ common_enums::PayoutStatus,
+ )> for crate::types::UcsPayoutCreateResponseData
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ value: (
+ payments_grpc::PayoutServiceCreateResponse,
+ common_enums::PayoutStatus,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (response, prev_status) = value;
+
+ let status_code =
+ transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response = Result::<PayoutsResponseData, ErrorResponse>::foreign_try_from(
+ (response.clone(), prev_status),
+ )?;
+
+ Ok(Self {
+ router_data_response,
+ status_code,
+ })
+ }
+}
+
+impl
+ ForeignTryFrom<(
+ payments_grpc::PayoutServiceTransferResponse,
+ common_enums::PayoutStatus,
+ )> for crate::types::UcsPayoutTransferResponseData
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ value: (
+ payments_grpc::PayoutServiceTransferResponse,
+ common_enums::PayoutStatus,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (response, prev_status) = value;
+
+ let status_code =
+ transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response = Result::<PayoutsResponseData, ErrorResponse>::foreign_try_from(
+ (response.clone(), prev_status),
+ )?;
+
+ Ok(Self {
+ router_data_response,
+ status_code,
+ })
+ }
+}
+
+impl
+ ForeignTryFrom<(
+ payments_grpc::PayoutServiceGetResponse,
+ common_enums::PayoutStatus,
+ )> for crate::types::UcsPayoutGetResponseData
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ value: (
+ payments_grpc::PayoutServiceGetResponse,
+ common_enums::PayoutStatus,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (response, prev_status) = value;
+
+ let status_code =
+ transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response = Result::<PayoutsResponseData, ErrorResponse>::foreign_try_from(
+ (response.clone(), prev_status),
+ )?;
+
+ Ok(Self {
+ router_data_response,
+ status_code,
+ })
+ }
+}
+
+impl
+ ForeignTryFrom<(
+ payments_grpc::PayoutServiceVoidResponse,
+ common_enums::PayoutStatus,
+ )> for crate::types::UcsPayoutVoidResponseData
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ value: (
+ payments_grpc::PayoutServiceVoidResponse,
+ common_enums::PayoutStatus,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (response, prev_status) = value;
+
+ let status_code =
+ transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response = Result::<PayoutsResponseData, ErrorResponse>::foreign_try_from(
+ (response.clone(), prev_status),
+ )?;
+
+ Ok(Self {
+ router_data_response,
+ status_code,
+ })
+ }
+}
+
+impl
+ ForeignTryFrom<(
+ payments_grpc::PayoutServiceStageResponse,
+ common_enums::PayoutStatus,
+ )> for crate::types::UcsPayoutStageResponseData
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ value: (
+ payments_grpc::PayoutServiceStageResponse,
+ common_enums::PayoutStatus,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (response, prev_status) = value;
+
+ let status_code =
+ transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response = Result::<PayoutsResponseData, ErrorResponse>::foreign_try_from(
+ (response.clone(), prev_status),
+ )?;
+
+ Ok(Self {
+ router_data_response,
+ status_code,
+ })
+ }
+}
+
+impl
+ ForeignTryFrom<(
+ payments_grpc::PayoutServiceCreateRecipientResponse,
+ common_enums::PayoutStatus,
+ )> for crate::types::UcsPayoutCreateRecipientResponseData
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ value: (
+ payments_grpc::PayoutServiceCreateRecipientResponse,
+ common_enums::PayoutStatus,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (response, prev_status) = value;
+
+ let status_code =
+ transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response = Result::<PayoutsResponseData, ErrorResponse>::foreign_try_from(
+ (response.clone(), prev_status),
+ )?;
+
+ Ok(Self {
+ router_data_response,
+ status_code,
+ })
+ }
+}
+
+impl
+ ForeignTryFrom<(
+ payments_grpc::PayoutServiceEnrollDisburseAccountResponse,
+ common_enums::PayoutStatus,
+ )> for crate::types::UcsPayoutEnrollDisburseAccountResponseData
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ value: (
+ payments_grpc::PayoutServiceEnrollDisburseAccountResponse,
+ common_enums::PayoutStatus,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (response, prev_status) = value;
+
+ let status_code =
+ transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response = Result::<PayoutsResponseData, ErrorResponse>::foreign_try_from(
+ (response.clone(), prev_status),
+ )?;
+
+ Ok(Self {
+ router_data_response,
+ status_code,
+ })
+ }
+}
+
pub fn build_webhook_secrets_from_merchant_connector_account(
#[cfg(feature = "v1")] merchant_connector_account: &MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: &MerchantConnectorAccountTypeDetails,
diff --git a/crates/router/src/core/unified_connector_service/connector_config.rs b/crates/router/src/core/unified_connector_service/connector_config.rs
index eaf5eebec5..68219d4e30 100644
--- a/crates/router/src/core/unified_connector_service/connector_config.rs
+++ b/crates/router/src/core/unified_connector_service/connector_config.rs
@@ -501,6 +501,11 @@ pub enum ConnectorSpecificConfig {
password: Secret<String>,
private_key: Secret<String>,
},
+ /// Itaubank connector configuration
+ Itaubank {
+ client_id: Secret<String>,
+ client_secret: Secret<String>,
+ },
}
impl ForeignTryFrom<(Connector, &ConnectorAuthType, Option<&serde_json::Value>)>
@@ -1350,6 +1355,13 @@ impl ForeignTryFrom<(Connector, &ConnectorAuthType, Option<&serde_json::Value>)>
_ => Err(err("Trustly requires SignatureKey auth type")),
},
+ Connector::Itaubank => match auth {
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::Itaubank {
+ client_secret: api_key.clone(),
+ client_id: key1.clone(),
+ }),
+ _ => Err(err("Itaubank requires BodyKey auth type")),
+ },
// --- Unsupported connectors ---
_ => Err(
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index 1e79abe3a3..bf3a65651c 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -32,7 +32,9 @@ use hyperswitch_domain_models::{
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
SyncRequestType,
},
- router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ router_response_types::{
+ PaymentsResponseData, PayoutsResponseData, RedirectForm, RefundsResponseData,
+ },
};
pub use hyperswitch_interfaces::{
helpers::ForeignTryFrom,
@@ -3643,6 +3645,70 @@ impl transformers::ForeignTryFrom<hyperswitch_domain_models::payment_address::Pa
}
}
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<hyperswitch_domain_models::address::Address>
+ for payments_grpc::Address
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ address: hyperswitch_domain_models::address::Address,
+ ) -> Result<Self, Self::Error> {
+ let details = address.address.as_ref();
+ let country = details.and_then(|details| {
+ details
+ .country
+ .as_ref()
+ .and_then(|c| payments_grpc::CountryAlpha2::from_str_name(&c.to_string()))
+ .map(|country| country.into())
+ });
+
+ Ok(Self {
+ first_name: details
+ .and_then(|d| d.first_name.as_ref().map(|s| s.peek().to_string().into())),
+ last_name: details
+ .and_then(|d| d.last_name.as_ref().map(|s| s.peek().to_string().into())),
+ line1: details.and_then(|d| d.line1.as_ref().map(|s| s.peek().to_string().into())),
+ line2: details.and_then(|d| d.line2.as_ref().map(|s| s.peek().to_string().into())),
+ line3: details.and_then(|d| d.line3.as_ref().map(|s| s.peek().to_string().into())),
+ city: details.and_then(|d| d.city.as_ref().map(|s| s.clone().into())),
+ state: details.and_then(|d| d.state.as_ref().map(|s| s.peek().to_string().into())),
+ zip_code: details.and_then(|d| d.zip.as_ref().map(|s| s.peek().to_string().into())),
+ country_alpha2_code: country,
+ email: address.email.as_ref().map(|e| e.peek().to_string().into()),
+ phone_number: address
+ .phone
+ .as_ref()
+ .and_then(|phone| phone.number.as_ref().map(|n| n.peek().to_string().into())),
+ phone_country_code: address.phone.as_ref().and_then(|p| p.country_code.clone()),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<hyperswitch_domain_models::payment_address::PaymentAddress>
+ for payments_grpc::PayoutAddress
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ payment_address: hyperswitch_domain_models::payment_address::PaymentAddress,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ shipping_address: payment_address
+ .get_shipping()
+ .cloned()
+ .map(payments_grpc::Address::foreign_try_from)
+ .transpose()?,
+ billing_address: payment_address
+ .get_payment_method_billing()
+ .cloned()
+ .map(payments_grpc::Address::foreign_try_from)
+ .transpose()?,
+ })
+ }
+}
+
impl transformers::ForeignTryFrom<AuthenticationType> for payments_grpc::AuthenticationType {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -6087,3 +6153,935 @@ impl
})
}
}
+
+// =============================================================================
+// PAYOUT TRANSFORMERS
+// =============================================================================
+
+#[cfg(feature = "payouts")]
+impl ForeignFrom<common_enums::PayoutSendPriority> for payments_grpc::payout_enums::PayoutPriority {
+ fn foreign_from(priority: common_enums::PayoutSendPriority) -> Self {
+ match priority {
+ common_enums::PayoutSendPriority::Instant => Self::Instant,
+ common_enums::PayoutSendPriority::Fast => Self::Fast,
+ common_enums::PayoutSendPriority::Regular => Self::Regular,
+ common_enums::PayoutSendPriority::Wire => Self::Wire,
+ common_enums::PayoutSendPriority::CrossBorder => Self::CrossBorder,
+ common_enums::PayoutSendPriority::Internal => Self::Internal,
+ }
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl ForeignFrom<&router_request_types::CustomerDetails> for payments_grpc::Customer {
+ fn foreign_from(customer: &router_request_types::CustomerDetails) -> Self {
+ Self {
+ id: customer
+ .customer_id
+ .clone()
+ .map(|id| id.get_string_repr().to_string()),
+ connector_customer_id: None,
+ name: customer.name.clone().map(|s| s.expose()),
+ email: customer.email.clone().map(|e| e.expose().expose().into()),
+ phone_number: customer.phone.clone().map(|s| s.expose()),
+ phone_country_code: customer.phone_country_code.clone(),
+ }
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl ForeignFrom<common_enums::PayoutEntityType>
+ for payments_grpc::payout_enums::PayoutRecipientType
+{
+ fn foreign_from(entity: common_enums::PayoutEntityType) -> Self {
+ match entity {
+ common_enums::PayoutEntityType::Individual => Self::Individual,
+ common_enums::PayoutEntityType::Company => Self::Company,
+ common_enums::PayoutEntityType::NonProfit => Self::NonProfit,
+ common_enums::PayoutEntityType::PublicSector => Self::PublicSector,
+ common_enums::PayoutEntityType::NaturalPerson => Self::NaturalPerson,
+ common_enums::PayoutEntityType::Business => Self::Business,
+ common_enums::PayoutEntityType::Personal => Self::Personal,
+ }
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<payments_grpc::payout_enums::PayoutStatus>
+ for common_enums::PayoutStatus
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ grpc_status: payments_grpc::payout_enums::PayoutStatus,
+ ) -> Result<Self, Self::Error> {
+ match grpc_status {
+ payments_grpc::payout_enums::PayoutStatus::Success => Ok(Self::Success),
+ payments_grpc::payout_enums::PayoutStatus::Failed => Ok(Self::Failed),
+ payments_grpc::payout_enums::PayoutStatus::Cancelled => Ok(Self::Cancelled),
+ payments_grpc::payout_enums::PayoutStatus::Initiated => Ok(Self::Initiated),
+ payments_grpc::payout_enums::PayoutStatus::Expired => Ok(Self::Expired),
+ payments_grpc::payout_enums::PayoutStatus::Reversed => Ok(Self::Reversed),
+ payments_grpc::payout_enums::PayoutStatus::Pending => Ok(Self::Pending),
+ payments_grpc::payout_enums::PayoutStatus::Ineligible => Ok(Self::Ineligible),
+ payments_grpc::payout_enums::PayoutStatus::RequiresCreation => {
+ Ok(Self::RequiresCreation)
+ }
+ payments_grpc::payout_enums::PayoutStatus::RequiresConfirmation => {
+ Ok(Self::RequiresConfirmation)
+ }
+ payments_grpc::payout_enums::PayoutStatus::RequiresPayoutMethodData => {
+ Ok(Self::RequiresPayoutMethodData)
+ }
+ payments_grpc::payout_enums::PayoutStatus::RequiresFulfillment => {
+ Ok(Self::RequiresFulfillment)
+ }
+ payments_grpc::payout_enums::PayoutStatus::RequiresVendorAccountCreation => {
+ Ok(Self::RequiresVendorAccountCreation)
+ }
+ payments_grpc::payout_enums::PayoutStatus::Unspecified => {
+ Err(error_stack::Report::new(
+ UnifiedConnectorServiceError::ResponseDeserializationFailed,
+ )
+ .attach_printable("Received unspecified payout status from UCS, cannot map to internal payout status"))
+ }
+ }
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoCreate,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ > for payments_grpc::PayoutServiceCreateRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoCreate,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let amount = router_data.request.amount;
+ let source_currency =
+ payments_grpc::Currency::foreign_try_from(router_data.request.source_currency)?;
+ let destination_currency =
+ payments_grpc::Currency::foreign_try_from(router_data.request.destination_currency)?;
+
+ let money = Some(payments_grpc::Money {
+ minor_amount: amount,
+ currency: source_currency.into(),
+ });
+
+ let customer = router_data
+ .request
+ .customer_details
+ .as_ref()
+ .map(payments_grpc::Customer::foreign_from);
+
+ let priority = router_data
+ .request
+ .priority
+ .map(payments_grpc::payout_enums::PayoutPriority::foreign_from)
+ .map(i32::from);
+
+ let connector_feature_data = router_data
+ .request
+ .payout_connector_metadata
+ .clone()
+ .map(|secret| Secret::new(secret.expose().to_string()));
+
+ let payout_method_data = router_data
+ .payout_method_data
+ .as_ref()
+ .map(|payout_method_data| {
+ payments_grpc::PayoutMethod::foreign_try_from(payout_method_data)
+ })
+ .transpose()?;
+
+ let address = Some(payments_grpc::PayoutAddress::foreign_try_from(
+ router_data.address.clone(),
+ )?);
+
+ let browser_info = router_data
+ .request
+ .browser_info
+ .as_ref()
+ .map(|b| payments_grpc::BrowserInformation::foreign_try_from(b.clone()))
+ .transpose()?;
+
+ let access_token = router_data.access_token.as_ref().map(|t| t.token.clone());
+
+ Ok(Self {
+ merchant_payout_id: router_data.payout_id.clone(),
+ address,
+ connector_feature_data,
+ payout_method_data,
+ connector_quote_id: router_data.quote_id.clone(),
+ connector_payout_id: router_data.request.connector_payout_id.clone(),
+ amount: money,
+ destination_currency: destination_currency.into(),
+ customer,
+ priority,
+ connector_payout_method_id: router_data.request.connector_transfer_method_id.clone(),
+ webhook_url: router_data.request.webhook_url.clone(),
+ browser_info,
+ access_token,
+ })
+ }
+}
+#[cfg(feature = "payouts")]
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoCancel,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ > for payments_grpc::PayoutServiceVoidRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoCancel,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let address = payments_grpc::PayoutAddress::foreign_try_from(router_data.address.clone())?;
+
+ let connector_feature_data = router_data
+ .request
+ .payout_connector_metadata
+ .clone()
+ .map(|secret| Secret::new(secret.expose().to_string()));
+
+ Ok(Self {
+ merchant_payout_id: router_data.payout_id.clone(),
+ address: Some(address),
+ connector_feature_data,
+ connector_payout_id: router_data.request.connector_payout_id.clone(),
+ access_token: router_data.access_token.clone().map(|at| at.token),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoFulfill,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ > for payments_grpc::PayoutServiceTransferRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoFulfill,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let address = payments_grpc::PayoutAddress::foreign_try_from(router_data.address.clone())?;
+ let source_currency =
+ payments_grpc::Currency::foreign_try_from(router_data.request.source_currency)?;
+ let destination_currency =
+ payments_grpc::Currency::foreign_try_from(router_data.request.destination_currency)?;
+ let money = payments_grpc::Money {
+ minor_amount: router_data.request.amount,
+ currency: source_currency.into(),
+ };
+ let customer = router_data
+ .request
+ .customer_details
+ .as_ref()
+ .map(payments_grpc::Customer::foreign_from)
+ .ok_or(
+ error_stack::Report::new(UnifiedConnectorServiceError::MissingRequiredField {
+ field_name: "customer",
+ })
+ .attach_printable("Missing customer details in Payout Transfer Request"),
+ )?;
+ let payout_method_data = router_data
+ .payout_method_data
+ .as_ref()
+ .map(|payout_method_data| {
+ payments_grpc::PayoutMethod::foreign_try_from(payout_method_data)
+ })
+ .transpose()?;
+ let browser_info = router_data
+ .request
+ .browser_info
+ .as_ref()
+ .map(|b| payments_grpc::BrowserInformation::foreign_try_from(b.clone()))
+ .transpose()?;
+
+ Ok(Self {
+ merchant_payout_id: router_data.payout_id.clone(),
+ address: Some(address),
+ amount: Some(money),
+ destination_currency: destination_currency.into(),
+ customer: Some(customer),
+ access_token: router_data.access_token.clone().map(|at| at.token),
+ connector_payout_id: router_data.request.connector_payout_id.clone(),
+ payout_method_data,
+ connector_quote_id: router_data.quote_id.clone(),
+ priority: router_data
+ .request
+ .priority
+ .map(payments_grpc::payout_enums::PayoutPriority::foreign_from)
+ .map(i32::from),
+ connector_payout_method_id: router_data.request.connector_transfer_method_id.clone(),
+ webhook_url: router_data.request.webhook_url.clone(),
+ browser_info,
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoQuote,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ > for payments_grpc::PayoutServiceStageRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoQuote,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let address =
+ payments_grpc::PayoutAddress::foreign_try_from(router_data.address.clone()).ok();
+ let source_currency =
+ payments_grpc::Currency::foreign_try_from(router_data.request.source_currency)?;
+ let destination_currency =
+ payments_grpc::Currency::foreign_try_from(router_data.request.destination_currency)?;
+ let money = payments_grpc::Money {
+ minor_amount: router_data.request.amount,
+ currency: source_currency.into(),
+ };
+ let customer = router_data
+ .request
+ .customer_details
+ .as_ref()
+ .map(payments_grpc::Customer::foreign_from)
+ .ok_or(
+ error_stack::Report::new(UnifiedConnectorServiceError::MissingRequiredField {
+ field_name: "customer",
+ })
+ .attach_printable("Missing customer details in Payout Stage Request"),
+ )?;
+ let browser_info = router_data
+ .request
+ .browser_info
+ .as_ref()
+ .map(|b| payments_grpc::BrowserInformation::foreign_try_from(b.clone()))
+ .transpose()?;
+
+ Ok(Self {
+ merchant_quote_id: router_data.quote_id.clone(),
+ address,
+ amount: Some(money),
+ destination_currency: destination_currency.into(),
+ customer: Some(customer),
+ access_token: router_data.access_token.clone().map(|at| at.token),
+ browser_info,
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoRecipient,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ > for payments_grpc::PayoutServiceCreateRecipientRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoRecipient,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let address =
+ payments_grpc::PayoutAddress::foreign_try_from(router_data.address.clone()).ok();
+ let customer = router_data
+ .request
+ .customer_details
+ .as_ref()
+ .map(payments_grpc::Customer::foreign_from)
+ .ok_or(
+ error_stack::Report::new(UnifiedConnectorServiceError::MissingRequiredField {
+ field_name: "customer",
+ })
+ .attach_printable("Missing customer details in Payout Create Recipient Request"),
+ )?;
+ let payout_method_data = router_data
+ .payout_method_data
+ .as_ref()
+ .map(|payout_method_data| {
+ payments_grpc::PayoutMethod::foreign_try_from(payout_method_data)
+ })
+ .transpose()?;
+ let source_currency =
+ payments_grpc::Currency::foreign_try_from(router_data.request.source_currency)?;
+ let amount = payments_grpc::Money {
+ minor_amount: router_data.request.amount,
+ currency: source_currency.into(),
+ };
+
+ Ok(Self {
+ merchant_payout_id: router_data.payout_id.clone(),
+ address,
+ customer: Some(customer),
+ access_token: router_data.access_token.clone().map(|at| at.token),
+ payout_method_data,
+ amount: Some(amount),
+ recipient_type: i32::from(
+ payments_grpc::payout_enums::PayoutRecipientType::foreign_from(
+ router_data.request.entity_type,
+ ),
+ ),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoRecipientAccount,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ > for payments_grpc::PayoutServiceEnrollDisburseAccountRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoRecipientAccount,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let address =
+ payments_grpc::PayoutAddress::foreign_try_from(router_data.address.clone()).ok();
+ let payout_method_data = router_data
+ .payout_method_data
+ .as_ref()
+ .map(|payout_method_data| {
+ payments_grpc::PayoutMethod::foreign_try_from(payout_method_data)
+ })
+ .transpose()?;
+
+ let source_currency =
+ payments_grpc::Currency::foreign_try_from(router_data.request.source_currency)?;
+ let money = payments_grpc::Money {
+ minor_amount: router_data.request.amount,
+ currency: source_currency.into(),
+ };
+ let customer = router_data
+ .request
+ .customer_details
+ .as_ref()
+ .map(payments_grpc::Customer::foreign_from)
+ .ok_or(
+ error_stack::Report::new(UnifiedConnectorServiceError::MissingRequiredField {
+ field_name: "customer",
+ })
+ .attach_printable(
+ "Missing customer details in Payout Enroll Disburse Account Request",
+ ),
+ )?;
+
+ Ok(Self {
+ merchant_payout_id: router_data.payout_id.clone(),
+ address,
+ payout_method_data,
+ amount: Some(money),
+ customer: Some(customer),
+ access_token: router_data.access_token.clone().map(|at| at.token),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoSync,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ > for payments_grpc::PayoutServiceGetRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<
+ hyperswitch_domain_models::router_flow_types::payouts::PoSync,
+ router_request_types::PayoutsData,
+ PayoutsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ merchant_payout_id: router_data.payout_id.clone(),
+ connector_payout_id: router_data.request.connector_payout_id.clone(),
+ access_token: router_data.access_token.clone().map(|at| at.token),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+macro_rules! impl_ucs_payout_response_transformation {
+ ($response_type:ty, $merchant_id_field:ident) => {
+ impl transformers::ForeignTryFrom<($response_type, common_enums::PayoutStatus)>
+ for Result<PayoutsResponseData, ErrorResponse>
+ {
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ (response, prev_status): ($response_type, common_enums::PayoutStatus),
+ ) -> Result<Self, Self::Error> {
+ let status_code = convert_connector_service_status_code(response.status_code)?;
+ let status = common_enums::PayoutStatus::foreign_try_from(response.payout_status())
+ .unwrap_or(prev_status);
+
+ let router_response = if let Some(error_info) = response.error {
+ Err(ErrorResponse {
+ code: error_info
+ .connector_details
+ .as_ref()
+ .and_then(|cd| cd.code.clone())
+ .ok_or(
+ error_stack::Report::new(
+ UnifiedConnectorServiceError::ResponseDeserializationFailed,
+ )
+ .attach_printable("Missing error code in UCS response ErrorInfo"),
+ )?,
+ message: error_info
+ .connector_details
+ .as_ref()
+ .and_then(|cd| cd.message.clone())
+ .ok_or(
+ error_stack::Report::new(
+ UnifiedConnectorServiceError::ResponseDeserializationFailed,
+ )
+ .attach_printable(
+ "Missing error message in UCS response ErrorInfo",
+ ),
+ )?,
+ reason: error_info
+ .connector_details
+ .as_ref()
+ .and_then(|cd| cd.reason.clone()),
+ status_code,
+ attempt_status: None,
+ connector_transaction_id: response.connector_payout_id.clone(),
+ connector_response_reference_id: response.$merchant_id_field.clone(),
+ network_decline_code: error_info.issuer_details.as_ref().and_then(|id| {
+ id.network_details
+ .as_ref()
+ .and_then(|nd| nd.decline_code.clone())
+ }),
+ network_advice_code: error_info.issuer_details.as_ref().and_then(|id| {
+ id.network_details
+ .as_ref()
+ .and_then(|nd| nd.advice_code.clone())
+ }),
+ network_error_message: error_info.issuer_details.as_ref().and_then(|id| {
+ id.network_details
+ .as_ref()
+ .and_then(|nd| nd.error_message.clone())
+ }),
+ connector_metadata: None,
+ })
+ } else {
+ Ok(PayoutsResponseData {
+ status: Some(status),
+ connector_payout_id: response.connector_payout_id,
+ payout_eligible: None,
+ should_add_next_step_to_process_tracker: false,
+ error_code: None,
+ error_message: None,
+ payout_connector_metadata: None,
+ })
+ };
+
+ Ok(router_response)
+ }
+ }
+ };
+}
+
+#[cfg(feature = "payouts")]
+impl_ucs_payout_response_transformation!(
+ payments_grpc::PayoutServiceCreateResponse,
+ merchant_payout_id
+);
+#[cfg(feature = "payouts")]
+impl_ucs_payout_response_transformation!(
+ payments_grpc::PayoutServiceTransferResponse,
+ merchant_payout_id
+);
+#[cfg(feature = "payouts")]
+impl_ucs_payout_response_transformation!(
+ payments_grpc::PayoutServiceGetResponse,
+ merchant_payout_id
+);
+#[cfg(feature = "payouts")]
+impl_ucs_payout_response_transformation!(
+ payments_grpc::PayoutServiceVoidResponse,
+ merchant_payout_id
+);
+#[cfg(feature = "payouts")]
+impl_ucs_payout_response_transformation!(
+ payments_grpc::PayoutServiceStageResponse,
+ merchant_payout_id
+);
+#[cfg(feature = "payouts")]
+impl_ucs_payout_response_transformation!(
+ payments_grpc::PayoutServiceCreateRecipientResponse,
+ merchant_payout_id
+);
+#[cfg(feature = "payouts")]
+impl_ucs_payout_response_transformation!(
+ payments_grpc::PayoutServiceEnrollDisburseAccountResponse,
+ merchant_payout_id
+);
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::PayoutMethodData>
+ for payments_grpc::PayoutMethod
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::PayoutMethodData) -> Result<Self, Self::Error> {
+ let payout_method_data = match item {
+ api_models::payouts::PayoutMethodData::Card(card) => {
+ payments_grpc::payout_method::PayoutMethodData::Card(
+ payments_grpc::CardPayout::foreign_try_from(card)?,
+ )
+ }
+ api_models::payouts::PayoutMethodData::Bank(bank) => match bank {
+ api_models::payouts::Bank::Ach(ach) => {
+ payments_grpc::payout_method::PayoutMethodData::Ach(
+ payments_grpc::AchBankTransferPayout::foreign_try_from(ach)?,
+ )
+ }
+ api_models::payouts::Bank::Bacs(bacs) => {
+ payments_grpc::payout_method::PayoutMethodData::Bacs(
+ payments_grpc::BacsBankTransferPayout::foreign_try_from(bacs)?,
+ )
+ }
+ api_models::payouts::Bank::Sepa(sepa) => {
+ payments_grpc::payout_method::PayoutMethodData::Sepa(
+ payments_grpc::SepaBankTransferPayout::foreign_try_from(sepa)?,
+ )
+ }
+ api_models::payouts::Bank::Pix(pix) => {
+ payments_grpc::payout_method::PayoutMethodData::Pix(
+ payments_grpc::PixBankTransferPayout::foreign_try_from(pix)?,
+ )
+ }
+ api_models::payouts::Bank::Trustly(_) => Err(error_stack::Report::new(
+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
+ "Trustly bank transfer not supported for Unified Connector Service"
+ .to_string(),
+ ),
+ ))?,
+ },
+ api_models::payouts::PayoutMethodData::BankTransfer(bank_transfer) => {
+ match bank_transfer {
+ api_models::payouts::BankTransfer::Ach(ach) => {
+ payments_grpc::payout_method::PayoutMethodData::Ach(
+ payments_grpc::AchBankTransferPayout::foreign_try_from(ach)?,
+ )
+ }
+ api_models::payouts::BankTransfer::Bacs(bacs) => {
+ payments_grpc::payout_method::PayoutMethodData::Bacs(
+ payments_grpc::BacsBankTransferPayout::foreign_try_from(bacs)?,
+ )
+ }
+ api_models::payouts::BankTransfer::Sepa(sepa) => {
+ payments_grpc::payout_method::PayoutMethodData::Sepa(
+ payments_grpc::SepaBankTransferPayout::foreign_try_from(sepa)?,
+ )
+ }
+ api_models::payouts::BankTransfer::Pix(pix) => {
+ payments_grpc::payout_method::PayoutMethodData::Pix(
+ payments_grpc::PixBankTransferPayout::foreign_try_from(pix)?,
+ )
+ }
+ api_models::payouts::BankTransfer::Trustly(_) => {
+ Err(error_stack::Report::new(
+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
+ "Trustly bank transfer not supported for Unified Connector Service"
+ .to_string(),
+ ),
+ ))?
+ }
+ }
+ }
+ api_models::payouts::PayoutMethodData::Wallet(wallet) => match wallet {
+ api_models::payouts::Wallet::ApplePayDecrypt(apple_pay) => {
+ payments_grpc::payout_method::PayoutMethodData::ApplePayDecrypt(
+ payments_grpc::ApplePayDecrypt::foreign_try_from(apple_pay)?,
+ )
+ }
+ api_models::payouts::Wallet::Paypal(paypal) => {
+ payments_grpc::payout_method::PayoutMethodData::Paypal(
+ payments_grpc::Paypal::foreign_try_from(paypal)?,
+ )
+ }
+ api_models::payouts::Wallet::Venmo(venmo) => {
+ payments_grpc::payout_method::PayoutMethodData::Venmo(
+ payments_grpc::Venmo::foreign_try_from(venmo)?,
+ )
+ }
+ },
+ api_models::payouts::PayoutMethodData::BankRedirect(bank_redirect) => {
+ match bank_redirect {
+ api_models::payouts::BankRedirect::Interac(interac) => {
+ payments_grpc::payout_method::PayoutMethodData::Interac(
+ payments_grpc::InteracPayout::foreign_try_from(interac)?,
+ )
+ }
+ api_models::payouts::BankRedirect::OpenBankingUk(open_banking) => {
+ payments_grpc::payout_method::PayoutMethodData::OpenBankingUk(
+ payments_grpc::OpenBankingUkPayout::foreign_try_from(open_banking)?,
+ )
+ }
+ }
+ }
+ api_models::payouts::PayoutMethodData::Passthrough(passthrough) => {
+ payments_grpc::payout_method::PayoutMethodData::Passthrough(
+ payments_grpc::Passthrough::foreign_try_from(passthrough)?,
+ )
+ }
+ };
+
+ Ok(Self {
+ payout_method_data: Some(payout_method_data),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::CardPayout> for payments_grpc::CardPayout {
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::CardPayout) -> Result<Self, Self::Error> {
+ Ok(Self {
+ card_number: Some(
+ CardNumber::from_str(&item.card_number.get_card_no()).change_context(
+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
+ "Failed to parse card number".to_string(),
+ ),
+ )?,
+ ),
+ card_exp_month: Some(item.expiry_month.clone()),
+ card_exp_year: Some(item.expiry_year.clone()),
+ card_holder_name: item.card_holder_name.clone(),
+ card_network: item
+ .card_network
+ .clone()
+ .map(payments_grpc::CardNetwork::foreign_from)
+ .map(i32::from),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::AchBankTransfer>
+ for payments_grpc::AchBankTransferPayout
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::AchBankTransfer) -> Result<Self, Self::Error> {
+ Ok(Self {
+ bank_name: None,
+ bank_country_code: item
+ .bank_country_code
+ .and_then(|c| payments_grpc::CountryAlpha2::from_str_name(&c.to_string()))
+ .map(|country| country.into()),
+ bank_city: item.bank_city.clone(),
+ bank_account_number: Some(item.bank_account_number.clone()),
+ bank_routing_number: Some(item.bank_routing_number.clone()),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::BacsBankTransfer>
+ for payments_grpc::BacsBankTransferPayout
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::BacsBankTransfer) -> Result<Self, Self::Error> {
+ Ok(Self {
+ bank_name: None,
+ bank_country_code: item
+ .bank_country_code
+ .and_then(|c| payments_grpc::CountryAlpha2::from_str_name(&c.to_string()))
+ .map(|country| country.into()),
+ bank_city: item.bank_city.clone(),
+ bank_account_number: Some(item.bank_account_number.clone()),
+ bank_sort_code: Some(item.bank_sort_code.clone()),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::SepaBankTransfer>
+ for payments_grpc::SepaBankTransferPayout
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::SepaBankTransfer) -> Result<Self, Self::Error> {
+ Ok(Self {
+ bank_name: None,
+ bank_country_code: item
+ .bank_country_code
+ .and_then(|c| payments_grpc::CountryAlpha2::from_str_name(&c.to_string()))
+ .map(|country| country.into()),
+ bank_city: item.bank_city.clone(),
+ iban: Some(item.iban.clone()),
+ bic: item.bic.clone(),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::PixBankTransfer>
+ for payments_grpc::PixBankTransferPayout
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::PixBankTransfer) -> Result<Self, Self::Error> {
+ Ok(Self {
+ bank_name: None,
+ bank_branch: item.bank_branch.clone(),
+ bank_account_number: Some(item.bank_account_number.clone()),
+ pix_key: Some(item.pix_key.clone()),
+ tax_id: item.tax_id.clone(),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::ApplePayDecrypt>
+ for payments_grpc::ApplePayDecrypt
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::ApplePayDecrypt) -> Result<Self, Self::Error> {
+ Ok(Self {
+ dpan: Some(
+ CardNumber::from_str(&item.dpan.get_card_no()).change_context(
+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
+ "Failed to parse card number".to_string(),
+ ),
+ )?,
+ ),
+ expiry_month: Some(item.expiry_month.clone()),
+ expiry_year: Some(item.expiry_year.clone()),
+ card_holder_name: item.card_holder_name.clone(),
+ card_network: item
+ .card_network
+ .clone()
+ .map(payments_grpc::CardNetwork::foreign_from)
+ .map(i32::from),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::Paypal> for payments_grpc::Paypal {
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::Paypal) -> Result<Self, Self::Error> {
+ Ok(Self {
+ email: item
+ .email
+ .as_ref()
+ .map(|e| Secret::new(e.clone().expose().expose())),
+ telephone_number: item.telephone_number.clone(),
+ paypal_id: item.paypal_id.clone(),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::Venmo> for payments_grpc::Venmo {
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::Venmo) -> Result<Self, Self::Error> {
+ Ok(Self {
+ telephone_number: item.telephone_number.clone(),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::Interac> for payments_grpc::InteracPayout {
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::Interac) -> Result<Self, Self::Error> {
+ Ok(Self {
+ email: Some(Secret::new(item.email.clone().expose().expose())),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::OpenBankingUk>
+ for payments_grpc::OpenBankingUkPayout
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::OpenBankingUk) -> Result<Self, Self::Error> {
+ Ok(Self {
+ account_holder_name: Some(item.account_holder_name.clone()),
+ iban: Some(item.iban.clone()),
+ })
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl transformers::ForeignTryFrom<&api_models::payouts::Passthrough>
+ for payments_grpc::Passthrough
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(item: &api_models::payouts::Passthrough) -> Result<Self, Self::Error> {
+ Ok(Self {
+ psp_token: item.psp_token.clone().expose(),
+ token_type: payments_grpc::PaymentMethodType::foreign_from(item.token_type).into(),
+ })
+ }
+}
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 32a1d1a932..5bf331a610 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -196,6 +196,16 @@ pub async fn construct_payout_router_data<'a, F>(
let browser_info = payout_data.browser_info.to_owned();
+ let payment_method_type =
+ payout_data
+ .payout_method_data
+ .as_ref()
+ .map(From::from)
+ .or(payout_attempt
+ .additional_payout_method_data
+ .as_ref()
+ .map(From::from));
+
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: platform.get_processor().get_account().get_id().to_owned(),
@@ -212,10 +222,10 @@ pub async fn construct_payout_router_data<'a, F>(
payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("payout")
.get_string_repr()
.to_owned(),
- attempt_id: "".to_string(),
+ attempt_id: payout_attempt.payout_attempt_id.clone(),
status: enums::AttemptStatus::Failure,
payment_method: enums::PaymentMethod::default(),
- payment_method_type: None,
+ payment_method_type,
connector_auth_type,
description: payout_data.payouts.description.clone(),
address,
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index c614cf3b2b..eabde53924 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -1965,6 +1965,7 @@ async fn payout_incoming_webhook_retrieve_status(
Box::pin(payouts::create_payout_retrieve(
&state,
&platform,
+ HeaderPayload::default(),
&connector_data,
payout_data,
))
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 1e340d586c..9c2d6f3b1c 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -53,7 +53,7 @@ pub async fn payouts_create(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payouts_create_core(state, auth.platform, req)
+ payouts_create_core(state, auth.platform, header_payload.clone(), req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
allow_connected_scope_operation: false,
@@ -80,6 +80,11 @@ pub async fn payouts_retrieve(
};
let flow = Flow::PayoutsRetrieve;
+ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
+ Ok(headers) => headers,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
+
Box::pin(api::server_wrap(
flow,
state,
@@ -87,7 +92,13 @@ pub async fn payouts_retrieve(
payout_retrieve_request,
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
- payouts_retrieve_core(state, auth.platform, profile_id, req)
+ payouts_retrieve_core(
+ state,
+ auth.platform,
+ header_payload.clone(),
+ profile_id,
+ req,
+ )
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
@@ -134,7 +145,7 @@ pub async fn payouts_update(
&req,
payout_update_payload,
|state, auth: auth::AuthenticationData, req, _| {
- payouts_update_core(state, auth.platform, req)
+ payouts_update_core(state, auth.platform, req, header_payload.clone())
},
&auth::HeaderAuth(auth::ApiKeyAuth {
allow_connected_scope_operation: false,
@@ -196,7 +207,7 @@ pub async fn payouts_confirm(
req.client_secret = Some(client_secret);
}
- payouts_confirm_core(state, auth.platform, req)
+ payouts_confirm_core(state, auth.platform, req, header_payload.clone())
},
&*auth_type,
api_locking::LockAction::NotApplicable,
@@ -215,6 +226,10 @@ pub async fn payouts_cancel(
let payload = payout_types::PayoutActionRequest {
payout_id: path.into_inner(),
};
+ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
+ Ok(headers) => headers,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
Box::pin(api::server_wrap(
flow,
@@ -222,7 +237,7 @@ pub async fn payouts_cancel(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payouts_cancel_core(state, auth.platform, req)
+ payouts_cancel_core(state, auth.platform, header_payload.clone(), req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
allow_connected_scope_operation: false,
@@ -244,13 +259,18 @@ pub async fn payouts_fulfill(
payout_id: path.into_inner(),
};
+ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
+ Ok(headers) => headers,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
+
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payouts_fulfill_core(state, auth.platform, req)
+ payouts_fulfill_core(state, auth.platform, header_payload.clone(), req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
allow_connected_scope_operation: false,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 081e173ab5..377350180c 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -758,6 +758,48 @@ pub struct UcsPaymentSetupRecurringResponseData {
pub minor_amount_captured: Option<MinorUnit>,
}
+#[cfg(feature = "payouts")]
+pub struct UcsPayoutCreateResponseData {
+ pub router_data_response: Result<PayoutsResponseData, ErrorResponse>,
+ pub status_code: u16,
+}
+
+#[cfg(feature = "payouts")]
+pub struct UcsPayoutTransferResponseData {
+ pub router_data_response: Result<PayoutsResponseData, ErrorResponse>,
+ pub status_code: u16,
+}
+
+#[cfg(feature = "payouts")]
+pub struct UcsPayoutGetResponseData {
+ pub router_data_response: Result<PayoutsResponseData, ErrorResponse>,
+ pub status_code: u16,
+}
+
+#[cfg(feature = "payouts")]
+pub struct UcsPayoutVoidResponseData {
+ pub router_data_response: Result<PayoutsResponseData, ErrorResponse>,
+ pub status_code: u16,
+}
+
+#[cfg(feature = "payouts")]
+pub struct UcsPayoutStageResponseData {
+ pub router_data_response: Result<PayoutsResponseData, ErrorResponse>,
+ pub status_code: u16,
+}
+
+#[cfg(feature = "payouts")]
+pub struct UcsPayoutCreateRecipientResponseData {
+ pub router_data_response: Result<PayoutsResponseData, ErrorResponse>,
+ pub status_code: u16,
+}
+
+#[cfg(feature = "payouts")]
+pub struct UcsPayoutEnrollDisburseAccountResponseData {
+ pub router_data_response: Result<PayoutsResponseData, ErrorResponse>,
+ pub status_code: u16,
+}
+
#[derive(Debug, Clone, Copy)]
pub enum Redirection {
Redirect,
diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rs
index 0aecdef6c4..b2217c53a7 100644
--- a/crates/router/src/workflows/attach_payout_account_workflow.rs
+++ b/crates/router/src/workflows/attach_payout_account_workflow.rs
@@ -2,6 +2,7 @@ use common_utils::{
consts::DEFAULT_LOCALE,
ext_traits::{OptionExt, ValueExt},
};
+use hyperswitch_domain_models::payments::HeaderPayload;
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
@@ -66,7 +67,16 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow {
))
.await?;
- payouts::payouts_core(state, &platform, &mut payout_data, None, None, dimensions).await?;
+ payouts::payouts_core(
+ state,
+ &platform,
+ HeaderPayload::default(),
+ &mut payout_data,
+ None,
+ None,
+ dimensions,
+ )
+ .await?;
Ok(())
}
diff --git a/crates/router/src/workflows/payout_sync.rs b/crates/router/src/workflows/payout_sync.rs
index e2ed4564fe..808a627128 100644
--- a/crates/router/src/workflows/payout_sync.rs
+++ b/crates/router/src/workflows/payout_sync.rs
@@ -41,6 +41,8 @@ impl ProcessTrackerWorkflow<SessionState> for PayoutSyncWorkFlow {
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
// Gather context
+
+ use hyperswitch_domain_models::payments::HeaderPayload;
let db = &*state.store;
let tracking_data: api::PayoutRetrieveRequest = process
.tracking_data
@@ -96,12 +98,13 @@ impl ProcessTrackerWorkflow<SessionState> for PayoutSyncWorkFlow {
.change_context(core_errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
- Box::pin(payouts::create_payout_retrieve(
+ payouts::create_payout_retrieve(
state,
&platform,
+ HeaderPayload::default(),
&connector_data,
&mut payout_data,
- ))
+ )
.await?;
let dimensions = configs::dimension_state::Dimensions::new()