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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat: add payout service (#1665)
Kashif763e2df3bdfb
diff --git a/.github/secrets/connector_auth.toml.gpg b/.github/secrets/connector_auth.toml.gpgindex 806d0a5887..1fbf759427 100644Binary files a/.github/secrets/connector_auth.toml.gpg and b/.github/secrets/connector_auth.toml.gpg differdiff --git a/config/config.example.toml b/config/config.example.tomlindex 12c46b6b29..dd75f40ba7 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -150,6 +150,7 @@ hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"[connectors]aci.base_url = "https://eu-test.oppwa.com/"adyen.base_url = "https://checkout-test.adyen.com/"+adyen.secondary_base_url = "https://pal-test.adyen.com/"airwallex.base_url = "https://api-demo.airwallex.com/"applepay.base_url = "https://apple-pay-gateway.apple.com/"authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"@@ -189,6 +190,7 @@ shift4.base_url = "https://api.shift4.com/"stax.base_url = "https://apiprod.fattlabs.com/"stripe.base_url = "https://api.stripe.com/"stripe.base_url_file_upload = "https://files.stripe.com/"+wise.base_url = "https://api.sandbox.transferwise.tech/"worldline.base_url = "https://eu.sandbox.api-ingenico.com/"worldpay.base_url = "https://try.access.worldpay.com/"trustpay.base_url = "https://test-tpgw.trustpay.eu/"@@ -311,3 +313,6 @@ afterpay_clearpay = {fields = {stripe = [ # payment_method_type = afterpay_clea{ required_field = "shipping.address.last_name", display_name = "last_name", field_type = "text" },{ required_field = "shipping.address.country", display_name = "country", field_type = { drop_down = { options = [ "US", "IN" ] } } },] } }++[payouts]+payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibilitydiff --git a/config/development.toml b/config/development.tomlindex 8016d71208..ee1b7c55f2 100644--- a/config/development.toml+++ b/config/development.toml@@ -91,6 +91,7 @@ cards = ["stripe","trustpay","tsys",+ "wise","worldline","worldpay","zen",@@ -112,6 +113,7 @@ hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"[connectors]aci.base_url = "https://eu-test.oppwa.com/"adyen.base_url = "https://checkout-test.adyen.com/"+adyen.secondary_base_url = "https://pal-test.adyen.com/"airwallex.base_url = "https://api-demo.airwallex.com/"applepay.base_url = "https://apple-pay-gateway.apple.com/"authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"@@ -151,6 +153,7 @@ shift4.base_url = "https://api.shift4.com/"stax.base_url = "https://apiprod.fattlabs.com/"stripe.base_url = "https://api.stripe.com/"stripe.base_url_file_upload = "https://files.stripe.com/"+wise.base_url = "https://api.sandbox.transferwise.tech/"worldline.base_url = "https://eu.sandbox.api-ingenico.com/"worldpay.base_url = "https://try.access.worldpay.com/"trustpay.base_url = "https://test-tpgw.trustpay.eu/"@@ -301,6 +304,7 @@ mollie = {long_lived_token = false, payment_method = "card"}[connector_customer]connector_list = "bluesnap,stripe"+payout_connector_list = "wise"[dummy_connector]payment_ttl = 172800@@ -325,4 +329,7 @@ card.credit = {connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpaycard.debit = {connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon"}[connector_request_reference_id_config]-merchant_ids_send_payment_id_as_connector_request_id = []\ No newline at end of file+merchant_ids_send_payment_id_as_connector_request_id = []++[payouts]+payout_eligibility = truediff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex bd9bccda64..ffe76c35e5 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -72,6 +72,7 @@ hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"[connectors]aci.base_url = "https://eu-test.oppwa.com/"adyen.base_url = "https://checkout-test.adyen.com/"+adyen.secondary_base_url = "https://pal-test.adyen.com/"airwallex.base_url = "https://api-demo.airwallex.com/"applepay.base_url = "https://apple-pay-gateway.apple.com/"authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"@@ -111,6 +112,7 @@ shift4.base_url = "https://api.shift4.com/"stax.base_url = "https://apiprod.fattlabs.com/"stripe.base_url = "https://api.stripe.com/"stripe.base_url_file_upload = "https://files.stripe.com/"+wise.base_url = "https://api.sandbox.transferwise.tech/"worldline.base_url = "https://eu.sandbox.api-ingenico.com/"worldpay.base_url = "https://try.access.worldpay.com/"trustpay.base_url = "https://test-tpgw.trustpay.eu/"@@ -160,6 +162,7 @@ cards = ["stripe","trustpay","tsys",+ "wise","worldline","worldpay","zen",@@ -193,3 +196,6 @@ refund_duration = 1000refund_tolerance = 100refund_retrieve_duration = 500refund_retrieve_tolerance = 100++[payouts]+payout_eligibility = truediff --git a/connector-template/test.rs b/connector-template/test.rsindex 8dfc7c9743..5c7c2f9905 100644--- a/connector-template/test.rs+++ b/connector-template/test.rs@@ -1,6 +1,9 @@use std::str::FromStr;use masking::Secret;-use router::types::{self, api, storage::enums};+use router::{+ core::utils as core_utils,+ types::{self, api, storage::enums,+}};use crate::utils::{self, ConnectorActions};use test_utils::connector_auth;@@ -395,6 +398,215 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() {);}+/******************** Payouts test cases ********************/+// Creates a BACS payout at connector's end+#[actix_web::test]+async fn should_create_bacs_payout() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Bacs(api::BacsBankTransfer {+ bank_sort_code: "231470".to_string(),+ bank_account_number: "28821822".to_string(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ ))+ };+ let response = CONNECTOR+ .create_payout(payment_info)+ .await+ .expect("Payout bank creation response");+ assert_eq!(response.status, enums::PayoutStatus::RequiresFulfillment);+}++// Fulfills an existing BACS payout at connector's end+#[actix_web::test]+async fn should_fulfill_bacs_payout() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Bacs(api::BacsBankTransfer {+ bank_sort_code: "231470".to_string(),+ bank_account_number: "28821822".to_string(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ ))+ };+ let payout_id = core_utils::get_or_generate_uuid("payout_id", &None)+ .map_or("payout_3154763247".to_string(), |p| p);+ let response = CONNECTOR+ .fulfill_payout(payout_id, payment_info)+ .await+ .expect("Payout bank fulfill response");+ assert_eq!(response.status, enums::PayoutStatus::Success);+}++// Creates and fulfills BACS payout at connector's end+#[actix_web::test]+async fn should_create_and_fulfill_bacs_payout() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Bacs(api::BacsBankTransfer {+ bank_sort_code: "231470".to_string(),+ bank_account_number: "28821822".to_string(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ ))+ };+ let response = CONNECTOR+ .create_and_fulfill_payout(None, payment_info)+ .await+ .expect("Payout bank creation and fulfill response");+ assert_eq!(response.status, enums::PayoutStatus::Success);+}++// Creates a ACH payout at connector's end+#[actix_web::test]+async fn should_create_ach_payout() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Ach(api::AchBankTransfer {+ bank_sort_code: "231470".to_string(),+ bank_account_number: "28821822".to_string(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ ))+ };+ let response = CONNECTOR+ .create_payout(payment_info)+ .await+ .expect("Payout bank creation response");+ assert_eq!(response.status, enums::PayoutStatus::RequiresFulfillment);+}++// Fulfills an existing ACH payout at connector's end+#[actix_web::test]+async fn should_fulfill_ach_payout() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Ach(api::AchBankTransfer {+ bank_sort_code: "231470".to_string(),+ bank_account_number: "28821822".to_string(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ ))+ };+ let payout_id = core_utils::get_or_generate_uuid("payout_id", &None)+ .map_or("payout_3154763247".to_string(), |p| p);+ let response = CONNECTOR+ .fulfill_payout(payout_id, payment_info)+ .await+ .expect("Payout bank fulfill response");+ assert_eq!(response.status, enums::PayoutStatus::Success);+}++// Creates and fulfills ACH payout at connector's end+#[actix_web::test]+async fn should_create_and_fulfill_ach_payout() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Ach(api::AchBankTransfer {+ bank_sort_code: "231470".to_string(),+ bank_account_number: "28821822".to_string(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ ))+ };+ let response = CONNECTOR+ .create_and_fulfill_payout(None, payment_info)+ .await+ .expect("Payout bank creation and fulfill response");+ assert_eq!(response.status, enums::PayoutStatus::Success);+}++// Creates a recipient at connector's end+#[actix_web::test]+async fn should_create_payout_recipient() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Ach(api::AchBankTransfer {+ bank_sort_code: "231470".to_string(),+ bank_account_number: "28821822".to_string(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ ))+ };+ let response = CONNECTOR+ .create_payout_recipient(payment_info)+ .await+ .expect("Payout recipient creation response");+ assert_eq!(response.status, enums::PayoutStatus::RequiresCreation);+}++// Checks eligibility of given card details at connector's end+#[actix_web::test]+async fn should_verify_payout_eligibility() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Card(api::payouts::CardPayout {+ card_number: CardNumber::from_str("4111111111111111").unwrap(),+ expiry_month: Secret::new("3".to_string()),+ expiry_year: Secret::new("2030".to_string()),+ card_holder_name: Secret::new("John Doe".to_string()),+ }))+ };+ let response = CONNECTOR+ .verify_payout_eligibility(payment_info)+ .await+ .expect("Payout eligibility response");+ assert_eq!(response.status.unwrap(), enums::PayoutStatus::RequiresCreation);+}++// Fulfills card payout at connector's end+#[actix_web::test]+async fn should_fulfill_card_payout() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Card(api::payouts::CardPayout {+ card_number: CardNumber::from_str("4111111111111111").unwrap(),+ expiry_month: Secret::new("3".to_string()),+ expiry_year: Secret::new("2030".to_string()),+ card_holder_name: Secret::new("John Doe".to_string()),+ }))+ };+ let response = CONNECTOR+ .fulfill_payout(payment_info)+ .await+ .expect("Payout fulfill response");+ assert_eq!(response.status.unwrap(), enums::PayoutStatus::RequiresCreation);+}++// Attempts cancellation of a created payout at connector's end+#[actix_web::test]+async fn should_create_and_cancel_created_payout() {+ let payment_info = PaymentInfo {+ payout_method_data: Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Ach(api::AchBankTransfer {+ bank_sort_code: "231470".to_string(),+ bank_account_number: "28821822".to_string(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ ))+ };+ let response = CONNECTOR+ .create_and_cancel_payout(None, payment_info)+ .await+ .expect("Payout cancel response");+ assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success);+}+// Connector dependent test cases goes here// [#478]: add unit tests for non 3DS, wallets & webhooks in connector testsdiff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.tomlindex fc4d56e025..4e8710e031 100644--- a/crates/api_models/Cargo.toml+++ b/crates/api_models/Cargo.toml@@ -8,11 +8,12 @@ readme = "README.md"license.workspace = true[features]-default = []+default = ["payouts"]errors = ["dep:actix-web", "dep:reqwest"]multiple_mca = []dummy_connector = ["common_enums/dummy_connector"]detailed_errors = []+payouts = [][dependencies]actix-web = { version = "4.3.1", optional = true }diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rsindex 7a6e984776..ec68111dd0 100644--- a/crates/api_models/src/admin.rs+++ b/crates/api_models/src/admin.rs@@ -35,6 +35,15 @@ pub struct MerchantAccountCreate {#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))]pub routing_algorithm: Option<serde_json::Value>,+ /// The routing algorithm to be used for routing payouts to desired connectors+ #[cfg(feature = "payouts")]+ #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]+ #[serde(+ default,+ deserialize_with = "payout_routing_algorithm::deserialize_option"+ )]+ pub payout_routing_algorithm: Option<serde_json::Value>,+/// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.#[schema(default = false, example = false)]pub sub_merchants_enabled: Option<bool>,@@ -113,6 +122,15 @@ pub struct MerchantAccountUpdate {#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))]pub routing_algorithm: Option<serde_json::Value>,+ /// The routing algorithm to be used for routing payouts to desired connectors+ #[cfg(feature = "payouts")]+ #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]+ #[serde(+ default,+ deserialize_with = "payout_routing_algorithm::deserialize_option"+ )]+ pub payout_routing_algorithm: Option<serde_json::Value>,+/// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.#[schema(default = false, example = false)]pub sub_merchants_enabled: Option<bool>,@@ -194,6 +212,15 @@ pub struct MerchantAccountResponse {#[schema(value_type = Option<RoutingAlgorithm>, max_length = 255, example = "custom")]pub routing_algorithm: Option<serde_json::Value>,+ /// The routing algorithm to be used for routing payouts to desired connectors+ #[cfg(feature = "payouts")]+ #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]+ #[serde(+ default,+ deserialize_with = "payout_routing_algorithm::deserialize_option"+ )]+ pub payout_routing_algorithm: Option<serde_json::Value>,+/// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.#[schema(default = false, example = false)]pub sub_merchants_enabled: Option<bool>,@@ -273,6 +300,117 @@ pub struct MerchantDetails {/// The merchant's address detailspub address: Option<AddressDetails>,}+#[cfg(feature = "payouts")]+pub mod payout_routing_algorithm {+ use std::{fmt, str::FromStr};++ use serde::{+ de::{self, Visitor},+ Deserializer,+ };+ use serde_json::Map;++ use super::PayoutRoutingAlgorithm;+ use crate::enums::PayoutConnectors;+ struct RoutingAlgorithmVisitor;+ struct OptionalRoutingAlgorithmVisitor;++ impl<'de> Visitor<'de> for RoutingAlgorithmVisitor {+ type Value = serde_json::Value;++ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str("routing algorithm")+ }++ fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>+ where+ A: de::MapAccess<'de>,+ {+ let mut output = serde_json::Value::Object(Map::new());+ let mut routing_data: String = "".to_string();+ let mut routing_type: String = "".to_string();++ while let Some(key) = map.next_key()? {+ match key {+ "type" => {+ routing_type = map.next_value()?;+ output["type"] = serde_json::Value::String(routing_type.to_owned());+ }+ "data" => {+ routing_data = map.next_value()?;+ output["data"] = serde_json::Value::String(routing_data.to_owned());+ }+ f => {+ output[f] = map.next_value()?;+ }+ }+ }++ match routing_type.as_ref() {+ "single" => {+ let routable_payout_connector = PayoutConnectors::from_str(&routing_data);+ let routable_conn = match routable_payout_connector {+ Ok(rpc) => Ok(rpc),+ Err(_) => Err(de::Error::custom(format!(+ "Unknown payout connector {routing_data}"+ ))),+ }?;+ Ok(PayoutRoutingAlgorithm::Single(routable_conn))+ }+ u => Err(de::Error::custom(format!("Unknown routing algorithm {u}"))),+ }?;+ Ok(output)+ }+ }++ impl<'de> Visitor<'de> for OptionalRoutingAlgorithmVisitor {+ type Value = Option<serde_json::Value>;++ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str("routing algorithm")+ }++ fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>+ where+ D: Deserializer<'de>,+ {+ deserializer+ .deserialize_any(RoutingAlgorithmVisitor)+ .map(Some)+ }++ fn visit_none<E>(self) -> Result<Self::Value, E>+ where+ E: de::Error,+ {+ Ok(None)+ }++ fn visit_unit<E>(self) -> Result<Self::Value, E>+ where+ E: de::Error,+ {+ Ok(None)+ }+ }++ #[allow(dead_code)]+ pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<serde_json::Value, D::Error>+ where+ D: Deserializer<'a>,+ {+ deserializer.deserialize_any(RoutingAlgorithmVisitor)+ }++ pub(crate) fn deserialize_option<'a, D>(+ deserializer: D,+ ) -> Result<Option<serde_json::Value>, D::Error>+ where+ D: Deserializer<'a>,+ {+ deserializer.deserialize_option(OptionalRoutingAlgorithmVisitor)+ }+}#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(tag = "type", content = "data", rename_all = "snake_case")]@@ -787,3 +925,17 @@ pub struct MerchantConnectorDetails {#[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))]pub metadata: Option<pii::SecretSerdeValue>,}++#[cfg(feature = "payouts")]+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(tag = "type", content = "data", rename_all = "snake_case")]+pub enum PayoutRoutingAlgorithm {+ Single(api_enums::PayoutConnectors),+}++#[cfg(feature = "payouts")]+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(tag = "type", content = "data", rename_all = "snake_case")]+pub enum PayoutStraightThroughAlgorithm {+ Single(api_enums::PayoutConnectors),+}diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rsindex 2fe1e18b07..884cf63c37 100644--- a/crates/api_models/src/enums.rs+++ b/crates/api_models/src/enums.rs@@ -43,19 +43,6 @@ pub enum RoutingAlgorithm {#[serde(rename_all = "snake_case")]#[strum(serialize_all = "snake_case")]pub enum Connector {- Aci,- Adyen,- Airwallex,- Authorizedotnet,- Bitpay,- Bluesnap,- Braintree,- Cashtocode,- Checkout,- Coinbase,- Cryptopay,- Cybersource,- Iatapay,#[cfg(feature = "dummy_connector")]#[serde(rename = "phonypay")]#[strum(serialize = "phonypay")]@@ -84,12 +71,25 @@ pub enum Connector {#[serde(rename = "paypal_test")]#[strum(serialize = "paypal_test")]DummyConnector7,+ Aci,+ Adyen,+ Airwallex,+ Authorizedotnet,+ Bitpay,Bambora,+ Bluesnap,+ Braintree,+ Cashtocode,+ Checkout,+ Coinbase,+ Cryptopay,+ Cybersource,Dlocal,Fiserv,Forte,Globalpay,- Globepay,+ Globepay, // added as template code for future usage+ Iatapay,Klarna,Mollie,Multisafepay,@@ -109,7 +109,9 @@ pub enum Connector {Stax,Stripe,Trustpay,+ // Tsys,Tsys,+ Wise,Worldline,Worldpay,Zen,@@ -218,12 +220,45 @@ pub enum RoutableConnectors {Shift4,Stripe,Trustpay,+ // Tsys,Tsys,+ Wise,Worldline,Worldpay,Zen,}+#[cfg(feature = "payouts")]+#[derive(+ Clone,+ Copy,+ Debug,+ Eq,+ Hash,+ PartialEq,+ serde::Serialize,+ serde::Deserialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum PayoutConnectors {+ Adyen,+ Wise,+}++#[cfg(feature = "payouts")]+impl From<PayoutConnectors> for RoutableConnectors {+ fn from(value: PayoutConnectors) -> Self {+ match value {+ PayoutConnectors::Adyen => Self::Adyen,+ PayoutConnectors::Wise => Self::Wise,+ }+ }+}+/// Name of banks supported by Hyperswitch#[derive(Clone,diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex ef794ccfa8..749b12f77d 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -5,6 +5,8 @@ use common_utils::{crypto::OptionalEncryptableName, pii};use serde::de;use utoipa::ToSchema;+#[cfg(feature = "payouts")]+use crate::payouts;use crate::{admin, enums as api_enums,payments::{self, BankCodeResponse},@@ -568,6 +570,11 @@ pub struct CustomerPaymentMethod {#[schema(value_type = Option<PrimitiveDateTime>,example = "2023-01-18T11:04:09.922Z")]#[serde(default, with = "common_utils::custom_serde::iso8601::option")]pub created: Option<time::PrimitiveDateTime>,++ /// Payment method details from locker+ #[cfg(feature = "payouts")]+ #[schema(value_type = Option<Bank>)]+ pub bank_transfer: Option<payouts::Bank>,}#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct PaymentMethodId {diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 71e9081f35..81cf36b5cd 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -2379,7 +2379,7 @@ mod payment_id_type {}}-mod amount {+pub mod amount {use serde::de;use super::Amount;diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rsindex 8b13789179..711b28057d 100644--- a/crates/api_models/src/payouts.rs+++ b/crates/api_models/src/payouts.rs@@ -1 +1,434 @@+#[cfg(feature = "payouts")]+use cards::CardNumber;+#[cfg(feature = "payouts")]+use common_utils::{+ crypto,+ pii::{self, Email},+};+#[cfg(feature = "payouts")]+use masking::Secret;+#[cfg(feature = "payouts")]+use serde::{Deserialize, Serialize};+#[cfg(feature = "payouts")]+use utoipa::ToSchema;+#[cfg(feature = "payouts")]+use crate::{admin, enums as api_enums, payments};++#[cfg(feature = "payouts")]+#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]+pub enum PayoutRequest {+ PayoutActionRequest(PayoutActionRequest),+ PayoutCreateRequest(PayoutCreateRequest),+ PayoutRetrieveRequest(PayoutRetrieveRequest),+}++#[cfg(feature = "payouts")]+#[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct PayoutCreateRequest {+ /// Unique identifier for the payout. This ensures idempotency for multiple payouts+ /// that have been done by a single merchant. This field is auto generated and is returned in the API response.+ #[schema(+ value_type = Option<String>,+ min_length = 30,+ max_length = 30,+ example = "payout_mbabizu24mvu3mela5njyhpit4"+ )]+ pub payout_id: Option<String>, // TODO: #1321 https://github.com/juspay/hyperswitch/issues/1321++ /// This is an identifier for the merchant account. This is inferred from the API key+ /// provided during the request+ #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")]+ pub merchant_id: Option<String>,++ /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,+ #[schema(value_type = i64, example = 1000)]+ #[serde(default, deserialize_with = "payments::amount::deserialize_option")]+ pub amount: Option<payments::Amount>,++ /// The currency of the payout request can be specified here+ #[schema(value_type = Currency, example = "USD")]+ pub currency: Option<api_enums::Currency>,++ /// Specifies routing algorithm for selecting a connector+ #[schema(value_type = Option<RoutingAlgorithm>, example = json!({+ "type": "single",+ "data": "adyen"+ }))]+ #[serde(+ default,+ deserialize_with = "admin::payout_routing_algorithm::deserialize_option"+ )]+ pub routing: Option<serde_json::Value>,++ /// This allows the merchant to manually select a connector with which the payout can go through+ #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["wise", "adyen"]))]+ pub connector: Option<Vec<api_enums::Connector>>,++ /// The boolean value to create payout with connector+ #[schema(value_type = bool, example = true, default = false)]+ pub confirm: Option<bool>,++ /// The payout_type of the payout request can be specified here+ #[schema(value_type = PayoutType, example = "card")]+ pub payout_type: Option<api_enums::PayoutType>,++ /// The payout method information required for carrying out a payout+ #[schema(value_type = Option<PayoutMethodData>)]+ pub payout_method_data: Option<PayoutMethodData>,++ /// The billing address for the payout+ #[schema(value_type = Option<Object>, example = json!(r#"{+ "address": {+ "line1": "1467",+ "line2": "Harrison Street",+ "line3": "Harrison Street",+ "city": "San Francisco",+ "state": "CA",+ "zip": "94122",+ "country": "US",+ "first_name": "John",+ "last_name": "Doe"+ },+ "phone": { "number": "8056594427", "country_code": "+1" }+ }"#))]+ pub billing: Option<payments::Address>,++ /// The identifier for the customer object. If not provided the customer ID will be autogenerated.+ #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]+ pub customer_id: Option<String>,++ /// Set to true to confirm the payout without review, no further action required+ #[schema(value_type = bool, example = true, default = false)]+ pub auto_fulfill: Option<bool>,++ /// description: The customer's email address+ #[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")]+ pub email: Option<Email>,++ /// description: The customer's name+ #[schema(value_type = Option<String>, max_length = 255, example = "John Test")]+ pub name: Option<Secret<String>>,++ /// The customer's phone number+ #[schema(value_type = Option<String>, max_length = 255, example = "3141592653")]+ pub phone: Option<Secret<String>>,++ /// The country code for the customer phone number+ #[schema(max_length = 255, example = "+1")]+ pub phone_country_code: Option<String>,++ /// It's a token used for client side verification.+ #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]+ pub client_secret: Option<String>,++ /// The URL to redirect after the completion of the operation+ #[schema(value_type = String, example = "https://hyperswitch.io")]+ pub return_url: Option<String>,++ /// Business country of the merchant for this payout+ #[schema(example = "US", value_type = CountryAlpha2)]+ pub business_country: Option<api_enums::CountryAlpha2>,++ /// Business label of the merchant for this payout+ #[schema(example = "food", value_type = Option<String>)]+ pub business_label: Option<String>,++ /// A description of the payout+ #[schema(example = "It's my first payout request", value_type = String)]+ pub description: Option<String>,++ /// Type of entity to whom the payout is being carried out to+ #[schema(value_type = PayoutEntityType, example = "Individual")]+ pub entity_type: Option<api_enums::PayoutEntityType>,++ /// Specifies whether or not the payout request is recurring+ #[schema(value_type = Option<bool>, default = false)]+ pub recurring: Option<bool>,++ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.+ #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]+ pub metadata: Option<pii::SecretSerdeValue>,++ /// Provide a reference to a stored payment method+ #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")]+ pub payout_token: Option<String>,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum PayoutMethodData {+ Card(Card),+ Bank(Bank),+}++#[cfg(feature = "payouts")]+impl Default for PayoutMethodData {+ fn default() -> Self {+ Self::Card(Card::default())+ }+}++#[cfg(feature = "payouts")]+#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]+pub struct Card {+ /// The card number+ #[schema(value_type = String, example = "4242424242424242")]+ pub card_number: CardNumber,++ /// The card's expiry month+ #[schema(value_type = String)]+ pub expiry_month: Secret<String>,++ /// The card's expiry year+ #[schema(value_type = String)]+ pub expiry_year: Secret<String>,++ /// The card holder's name+ #[schema(value_type = String, example = "John Doe")]+ pub card_holder_name: Secret<String>,+}++#[cfg(feature = "payouts")]+#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(untagged)]+pub enum Bank {+ Ach(AchBankTransfer),+ Bacs(BacsBankTransfer),+ Sepa(SepaBankTransfer),+}++#[cfg(feature = "payouts")]+#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]+pub struct AchBankTransfer {+ /// Bank name+ #[schema(value_type = String, example = "Deutsche Bank")]+ pub bank_name: String,++ /// Bank country code+ #[schema(value_type = CountryAlpha2, example = "US")]+ pub bank_country_code: api_enums::CountryAlpha2,++ /// Bank city+ #[schema(value_type = String, example = "California")]+ pub bank_city: String,++ /// Bank account number is an unique identifier assigned by a bank to a customer.+ #[schema(value_type = String, example = "000123456")]+ pub bank_account_number: Secret<String>,++ /// [9 digits] Routing number - used in USA for identifying a specific bank.+ #[schema(value_type = String, example = "110000000")]+ pub bank_routing_number: Secret<String>,+}++#[cfg(feature = "payouts")]+#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]+pub struct BacsBankTransfer {+ /// Bank name+ #[schema(value_type = String, example = "Deutsche Bank")]+ pub bank_name: String,++ /// Bank country code+ #[schema(value_type = CountryAlpha2, example = "US")]+ pub bank_country_code: api_enums::CountryAlpha2,++ /// Bank city+ #[schema(value_type = String, example = "California")]+ pub bank_city: String,++ /// Bank account number is an unique identifier assigned by a bank to a customer.+ #[schema(value_type = String, example = "000123456")]+ pub bank_account_number: Secret<String>,++ /// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches.+ #[schema(value_type = String, example = "98-76-54")]+ pub bank_sort_code: Secret<String>,+}++#[cfg(feature = "payouts")]+#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]+// The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone.+pub struct SepaBankTransfer {+ /// Bank name+ #[schema(value_type = String, example = "Deutsche Bank")]+ pub bank_name: String,++ /// Bank country code+ #[schema(value_type = CountryAlpha2, example = "US")]+ pub bank_country_code: api_enums::CountryAlpha2,++ /// Bank city+ #[schema(value_type = String, example = "California")]+ pub bank_city: String,++ /// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer.+ #[schema(value_type = String, example = "DE89370400440532013000")]+ pub iban: Secret<String>,++ /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches+ #[schema(value_type = String, example = "HSBCGB2LXXX")]+ pub bic: Option<Secret<String>>,+}++#[cfg(feature = "payouts")]+#[derive(Debug, ToSchema, Clone, Serialize)]+#[serde(deny_unknown_fields)]+pub struct PayoutCreateResponse {+ /// Unique identifier for the payout. This ensures idempotency for multiple payouts+ /// that have been done by a single merchant. This field is auto generated and is returned in the API response.+ #[schema(+ value_type = String,+ min_length = 30,+ max_length = 30,+ example = "payout_mbabizu24mvu3mela5njyhpit4"+ )]+ pub payout_id: String, // TODO: Update this to PayoutIdType similar to PaymentIdType++ /// This is an identifier for the merchant account. This is inferred from the API key+ /// provided during the request+ #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")]+ pub merchant_id: String,++ /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,+ #[schema(value_type = i64, example = 1000)]+ pub amount: i64,++ /// Recipient's currency for the payout request+ #[schema(value_type = Currency, example = "USD")]+ pub currency: api_enums::Currency,++ /// The connector used for the payout+ #[schema(example = "wise")]+ pub connector: Option<String>,++ /// The payout method that is to be used+ #[schema(value_type = PayoutType, example = "bank")]+ pub payout_type: api_enums::PayoutType,++ /// The billing address for the payout+ #[schema(value_type = Option<Object>, example = json!(r#"{+ "address": {+ "line1": "1467",+ "line2": "Harrison Street",+ "line3": "Harrison Street",+ "city": "San Francisco",+ "state": "CA",+ "zip": "94122",+ "country": "US",+ "first_name": "John",+ "last_name": "Doe"+ },+ "phone": { "number": "8056594427", "country_code": "+1" }+ }"#))]+ pub billing: Option<payments::Address>,++ /// The identifier for the customer object. If not provided the customer ID will be autogenerated.+ #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]+ pub customer_id: String,++ /// Set to true to confirm the payout without review, no further action required+ #[schema(value_type = bool, example = true, default = false)]+ pub auto_fulfill: bool,++ /// description: The customer's email address+ #[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")]+ pub email: crypto::OptionalEncryptableEmail,++ /// description: The customer's name+ #[schema(value_type = Option<String>, max_length = 255, example = "John Test")]+ pub name: crypto::OptionalEncryptableName,++ /// The customer's phone number+ #[schema(value_type = Option<String>, max_length = 255, example = "3141592653")]+ pub phone: crypto::OptionalEncryptablePhone,++ /// The country code for the customer phone number+ #[schema(max_length = 255, example = "+1")]+ pub phone_country_code: Option<String>,++ /// It's a token used for client side verification.+ #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]+ pub client_secret: Option<String>,++ /// The URL to redirect after the completion of the operation+ #[schema(value_type = String, example = "https://hyperswitch.io")]+ pub return_url: Option<String>,++ /// Business country of the merchant for this payout+ #[schema(example = "US", value_type = CountryAlpha2)]+ pub business_country: Option<api_enums::CountryAlpha2>,++ /// Business label of the merchant for this payout+ #[schema(example = "food", value_type = Option<String>)]+ pub business_label: Option<String>,++ /// A description of the payout+ #[schema(example = "It's my first payout request", value_type = String)]+ pub description: Option<String>,++ /// Type of entity to whom the payout is being carried out to+ #[schema(value_type = PayoutEntityType, example = "Individual")]+ pub entity_type: api_enums::PayoutEntityType,++ /// Specifies whether or not the payout request is recurring+ #[schema(value_type = Option<bool>, default = false)]+ pub recurring: bool,++ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.+ #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]+ pub metadata: Option<pii::SecretSerdeValue>,++ /// Current status of the Payout+ #[schema(value_type = PayoutStatus, example = Pending)]+ pub status: api_enums::PayoutStatus,++ /// If there was an error while calling the connector the error message is received here+ #[schema(value_type = String, example = "Failed while verifying the card")]+ pub error_message: Option<String>,++ /// If there was an error while calling the connectors the code is received here+ #[schema(value_type = String, example = "E0001")]+ pub error_code: Option<String>,+}++#[cfg(feature = "payouts")]+#[derive(Default, Debug, Clone, Deserialize, ToSchema)]+pub struct PayoutRetrieveBody {+ pub force_sync: Option<bool>,+}++#[cfg(feature = "payouts")]+#[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)]+pub struct PayoutRetrieveRequest {+ /// Unique identifier for the payout. This ensures idempotency for multiple payouts+ /// that have been done by a single merchant. This field is auto generated and is returned in the API response.+ #[schema(+ value_type = String,+ min_length = 30,+ max_length = 30,+ example = "payout_mbabizu24mvu3mela5njyhpit4"+ )]+ pub payout_id: String,++ /// `force_sync` with the connector to get payout details+ /// (defaults to false)+ #[schema(value_type = Option<bool>, default = false, example = true)]+ pub force_sync: Option<bool>,+}++#[cfg(feature = "payouts")]+#[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)]+pub struct PayoutActionRequest {+ /// Unique identifier for the payout. This ensures idempotency for multiple payouts+ /// that have been done by a single merchant. This field is auto generated and is returned in the API response.+ #[schema(+ value_type = String,+ min_length = 30,+ max_length = 30,+ example = "payout_mbabizu24mvu3mela5njyhpit4"+ )]+ pub payout_id: String,+}diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex bece1bc3a3..dad8d57c1d 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -1194,3 +1194,85 @@ pub enum CanadaStatesAbbreviation {SK,YT,}++#[derive(+ Clone,+ Copy,+ Debug,+ Default,+ Eq,+ PartialEq,+ ToSchema,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+)]+#[router_derive::diesel_enum(storage_type = "pg_enum")]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum PayoutStatus {+ Success,+ Failed,+ Cancelled,+ Pending,+ Ineligible,+ #[default]+ RequiresCreation,+ RequiresPayoutMethodData,+ RequiresFulfillment,+}++#[derive(+ Clone,+ Copy,+ Debug,+ Default,+ Eq,+ PartialEq,+ ToSchema,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+)]+#[router_derive::diesel_enum(storage_type = "pg_enum")]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum PayoutType {+ #[default]+ Card,+ Bank,+}++#[derive(+ Clone,+ Copy,+ Debug,+ Default,+ Eq,+ Hash,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[router_derive::diesel_enum(storage_type = "text")]+#[serde(rename_all = "PascalCase")]+#[strum(serialize_all = "PascalCase")]+pub enum PayoutEntityType {+ /// Adyen+ #[default]+ Individual,+ Company,+ NonProfit,+ PublicSector,++ /// Wise+ #[strum(serialize = "lowercase")]+ #[serde(rename = "lowercase")]+ Business,+ Personal,+}diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rsindex bf29c07c91..7b5cfb5c04 100644--- a/crates/diesel_models/src/enums.rs+++ b/crates/diesel_models/src/enums.rs@@ -9,9 +9,9 @@ pub mod diesel_exports {DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus,DbMandateStatus as MandateStatus, DbMandateType as MandateType,DbMerchantStorageScheme as MerchantStorageScheme,- DbPaymentMethodIssuerCode as PaymentMethodIssuerCode,- DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus,- DbRefundType as RefundType,+ DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPayoutStatus as PayoutStatus,+ DbPayoutType as PayoutType, DbProcessTrackerStatus as ProcessTrackerStatus,+ DbRefundStatus as RefundStatus, DbRefundType as RefundType,};}pub use common_enums::*;diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rsindex 3caedbfc27..b62d751e61 100644--- a/crates/diesel_models/src/lib.rs+++ b/crates/diesel_models/src/lib.rs@@ -21,6 +21,8 @@ pub mod merchant_key_store;pub mod payment_attempt;pub mod payment_intent;pub mod payment_method;+pub mod payout_attempt;+pub mod payouts;pub mod process_tracker;pub mod query;pub mod refund;diff --git a/crates/diesel_models/src/locker_mock_up.rs b/crates/diesel_models/src/locker_mock_up.rsindex f20ccd29a9..eefaea86ab 100644--- a/crates/diesel_models/src/locker_mock_up.rs+++ b/crates/diesel_models/src/locker_mock_up.rs@@ -20,6 +20,7 @@ pub struct LockerMockUp {pub duplicate: Option<bool>,pub card_cvc: Option<String>,pub payment_method_id: Option<String>,+ pub enc_card_data: Option<String>,}#[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)]@@ -38,4 +39,5 @@ pub struct LockerMockUpNew {pub payment_method_id: Option<String>,pub customer_id: Option<String>,pub nickname: Option<String>,+ pub enc_card_data: Option<String>,}diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rsindex 4d6e90757b..8b0833f88e 100644--- a/crates/diesel_models/src/merchant_account.rs+++ b/crates/diesel_models/src/merchant_account.rs@@ -35,6 +35,7 @@ pub struct MerchantAccount {pub created_at: time::PrimitiveDateTime,pub modified_at: time::PrimitiveDateTime,pub frm_routing_algorithm: Option<serde_json::Value>,+ pub payout_routing_algorithm: Option<serde_json::Value>,pub organization_id: Option<String>,pub is_recon_enabled: bool,}@@ -61,6 +62,7 @@ pub struct MerchantAccountNew {pub created_at: time::PrimitiveDateTime,pub modified_at: time::PrimitiveDateTime,pub frm_routing_algorithm: Option<serde_json::Value>,+ pub payout_routing_algorithm: Option<serde_json::Value>,pub organization_id: Option<String>,pub is_recon_enabled: bool,}@@ -86,6 +88,7 @@ pub struct MerchantAccountUpdateInternal {pub modified_at: Option<time::PrimitiveDateTime>,pub intent_fulfillment_time: Option<i64>,pub frm_routing_algorithm: Option<serde_json::Value>,+ pub payout_routing_algorithm: Option<serde_json::Value>,pub organization_id: Option<String>,pub is_recon_enabled: bool,}diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rsnew file mode 100644index 0000000000..86c7e65310--- /dev/null+++ b/crates/diesel_models/src/payout_attempt.rs@@ -0,0 +1,164 @@+use diesel::{AsChangeset, Identifiable, Insertable, Queryable};+use serde::{self, Deserialize, Serialize};+use time::PrimitiveDateTime;++use crate::{enums as storage_enums, schema::payout_attempt};++#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)]+#[diesel(table_name = payout_attempt)]+#[diesel(primary_key(payout_attempt_id))]+pub struct PayoutAttempt {+ pub payout_attempt_id: String,+ pub payout_id: String,+ pub customer_id: String,+ pub merchant_id: String,+ pub address_id: String,+ pub connector: String,+ pub connector_payout_id: String,+ pub payout_token: Option<String>,+ pub status: storage_enums::PayoutStatus,+ pub is_eligible: Option<bool>,+ pub error_message: Option<String>,+ pub error_code: Option<String>,+ pub business_country: Option<storage_enums::CountryAlpha2>,+ pub business_label: Option<String>,+ #[serde(with = "common_utils::custom_serde::iso8601")]+ pub created_at: PrimitiveDateTime,+ #[serde(with = "common_utils::custom_serde::iso8601")]+ pub last_modified_at: PrimitiveDateTime,+}++impl Default for PayoutAttempt {+ fn default() -> Self {+ let now = common_utils::date_time::now();++ Self {+ payout_attempt_id: String::default(),+ payout_id: String::default(),+ customer_id: String::default(),+ merchant_id: String::default(),+ address_id: String::default(),+ connector: String::default(),+ connector_payout_id: String::default(),+ payout_token: None,+ status: storage_enums::PayoutStatus::default(),+ is_eligible: Some(true),+ error_message: None,+ error_code: None,+ business_country: Some(storage_enums::CountryAlpha2::default()),+ business_label: None,+ created_at: now,+ last_modified_at: now,+ }+ }+}++#[derive(+ Clone,+ Debug,+ Default,+ Eq,+ PartialEq,+ Insertable,+ serde::Serialize,+ serde::Deserialize,+ router_derive::DebugAsDisplay,+ router_derive::Setter,+)]+#[diesel(table_name = payout_attempt)]+pub struct PayoutAttemptNew {+ pub payout_attempt_id: String,+ pub payout_id: String,+ pub customer_id: String,+ pub merchant_id: String,+ pub address_id: String,+ pub connector: String,+ pub connector_payout_id: String,+ pub payout_token: Option<String>,+ pub status: storage_enums::PayoutStatus,+ pub is_eligible: Option<bool>,+ pub error_message: Option<String>,+ pub error_code: Option<String>,+ pub business_country: Option<storage_enums::CountryAlpha2>,+ pub business_label: Option<String>,+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub created_at: Option<PrimitiveDateTime>,+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub last_modified_at: Option<PrimitiveDateTime>,+}++#[derive(Debug)]+pub enum PayoutAttemptUpdate {+ StatusUpdate {+ connector_payout_id: String,+ status: storage_enums::PayoutStatus,+ error_message: Option<String>,+ error_code: Option<String>,+ is_eligible: Option<bool>,+ last_modified_at: Option<PrimitiveDateTime>,+ },+ PayoutTokenUpdate {+ payout_token: String,+ last_modified_at: Option<PrimitiveDateTime>,+ },+ BusinessUpdate {+ business_country: Option<storage_enums::CountryAlpha2>,+ business_label: Option<String>,+ last_modified_at: Option<PrimitiveDateTime>,+ },+}++#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]+#[diesel(table_name = payout_attempt)]+pub struct PayoutAttemptUpdateInternal {+ pub payout_token: Option<String>,+ pub connector_payout_id: Option<String>,+ pub status: Option<storage_enums::PayoutStatus>,+ pub error_message: Option<String>,+ pub error_code: Option<String>,+ pub is_eligible: Option<bool>,+ pub business_country: Option<storage_enums::CountryAlpha2>,+ pub business_label: Option<String>,+ pub last_modified_at: Option<PrimitiveDateTime>,+}++impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {+ fn from(payout_update: PayoutAttemptUpdate) -> Self {+ match payout_update {+ PayoutAttemptUpdate::PayoutTokenUpdate {+ last_modified_at,+ payout_token,+ } => Self {+ last_modified_at,+ payout_token: Some(payout_token),+ ..Default::default()+ },+ PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id,+ status,+ error_message,+ error_code,+ is_eligible,+ last_modified_at,+ } => Self {+ connector_payout_id: Some(connector_payout_id),+ status: Some(status),+ error_message,+ error_code,+ is_eligible,+ last_modified_at,+ ..Default::default()+ },+ PayoutAttemptUpdate::BusinessUpdate {+ business_country,+ business_label,+ last_modified_at,+ } => Self {+ business_country,+ business_label,+ last_modified_at,+ ..Default::default()+ },+ }+ }+}diff --git a/crates/diesel_models/src/payouts.rs b/crates/diesel_models/src/payouts.rsnew file mode 100644index 0000000000..fd068b5a8d--- /dev/null+++ b/crates/diesel_models/src/payouts.rs@@ -0,0 +1,180 @@+use common_utils::pii;+use diesel::{AsChangeset, Identifiable, Insertable, Queryable};+use serde::{self, Deserialize, Serialize};+use time::PrimitiveDateTime;++use crate::{enums as storage_enums, schema::payouts};++// Payouts+#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)]+#[diesel(table_name = payouts)]+#[diesel(primary_key(payout_id))]+pub struct Payouts {+ pub payout_id: String,+ pub merchant_id: String,+ pub customer_id: String,+ pub address_id: String,+ pub payout_type: storage_enums::PayoutType,+ pub payout_method_id: Option<String>,+ pub amount: i64,+ pub destination_currency: storage_enums::Currency,+ pub source_currency: storage_enums::Currency,+ pub description: Option<String>,+ pub recurring: bool,+ pub auto_fulfill: bool,+ pub return_url: Option<String>,+ pub entity_type: storage_enums::PayoutEntityType,+ pub metadata: Option<pii::SecretSerdeValue>,+ #[serde(with = "common_utils::custom_serde::iso8601")]+ pub created_at: PrimitiveDateTime,+ #[serde(with = "common_utils::custom_serde::iso8601")]+ pub last_modified_at: PrimitiveDateTime,+}++impl Default for Payouts {+ fn default() -> Self {+ let now = common_utils::date_time::now();++ Self {+ payout_id: String::default(),+ merchant_id: String::default(),+ customer_id: String::default(),+ address_id: String::default(),+ payout_type: storage_enums::PayoutType::default(),+ payout_method_id: Option::default(),+ amount: i64::default(),+ destination_currency: storage_enums::Currency::default(),+ source_currency: storage_enums::Currency::default(),+ description: Option::default(),+ recurring: bool::default(),+ auto_fulfill: bool::default(),+ return_url: None,+ entity_type: storage_enums::PayoutEntityType::default(),+ metadata: Option::default(),+ created_at: now,+ last_modified_at: now,+ }+ }+}++#[derive(+ Clone,+ Debug,+ Default,+ Eq,+ PartialEq,+ Insertable,+ serde::Serialize,+ serde::Deserialize,+ router_derive::DebugAsDisplay,+ router_derive::Setter,+)]+#[diesel(table_name = payouts)]+pub struct PayoutsNew {+ pub payout_id: String,+ pub merchant_id: String,+ pub customer_id: String,+ pub address_id: String,+ pub payout_type: storage_enums::PayoutType,+ pub payout_method_id: Option<String>,+ pub amount: i64,+ pub destination_currency: storage_enums::Currency,+ pub source_currency: storage_enums::Currency,+ pub description: Option<String>,+ pub recurring: bool,+ pub auto_fulfill: bool,+ pub return_url: Option<String>,+ pub entity_type: storage_enums::PayoutEntityType,+ pub metadata: Option<pii::SecretSerdeValue>,+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub created_at: Option<PrimitiveDateTime>,+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub last_modified_at: Option<PrimitiveDateTime>,+}++#[derive(Debug)]+pub enum PayoutsUpdate {+ Update {+ amount: i64,+ destination_currency: storage_enums::Currency,+ source_currency: storage_enums::Currency,+ description: Option<String>,+ recurring: bool,+ auto_fulfill: bool,+ return_url: Option<String>,+ entity_type: storage_enums::PayoutEntityType,+ metadata: Option<pii::SecretSerdeValue>,+ last_modified_at: Option<PrimitiveDateTime>,+ },+ PayoutMethodIdUpdate {+ payout_method_id: Option<String>,+ last_modified_at: Option<PrimitiveDateTime>,+ },+ RecurringUpdate {+ recurring: bool,+ last_modified_at: Option<PrimitiveDateTime>,+ },+}++#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]+#[diesel(table_name = payouts)]+pub struct PayoutsUpdateInternal {+ pub amount: Option<i64>,+ pub destination_currency: Option<storage_enums::Currency>,+ pub source_currency: Option<storage_enums::Currency>,+ pub description: Option<String>,+ pub recurring: Option<bool>,+ pub auto_fulfill: Option<bool>,+ pub return_url: Option<String>,+ pub entity_type: Option<storage_enums::PayoutEntityType>,+ pub metadata: Option<pii::SecretSerdeValue>,+ pub last_modified_at: Option<PrimitiveDateTime>,+ pub payout_method_id: Option<String>,+}++impl From<PayoutsUpdate> for PayoutsUpdateInternal {+ fn from(payout_update: PayoutsUpdate) -> Self {+ match payout_update {+ PayoutsUpdate::Update {+ amount,+ destination_currency,+ source_currency,+ description,+ recurring,+ auto_fulfill,+ return_url,+ entity_type,+ metadata,+ last_modified_at,+ } => Self {+ amount: Some(amount),+ destination_currency: Some(destination_currency),+ source_currency: Some(source_currency),+ description,+ recurring: Some(recurring),+ auto_fulfill: Some(auto_fulfill),+ return_url,+ entity_type: Some(entity_type),+ metadata,+ last_modified_at,+ ..Default::default()+ },+ PayoutsUpdate::PayoutMethodIdUpdate {+ last_modified_at,+ payout_method_id,+ } => Self {+ last_modified_at,+ payout_method_id,+ ..Default::default()+ },+ PayoutsUpdate::RecurringUpdate {+ last_modified_at,+ recurring,+ } => Self {+ last_modified_at,+ recurring: Some(recurring),+ ..Default::default()+ },+ }+ }+}diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rsindex 8da83de0ea..3e9ad77fc5 100644--- a/crates/diesel_models/src/query.rs+++ b/crates/diesel_models/src/query.rs@@ -16,6 +16,8 @@ pub mod merchant_key_store;pub mod payment_attempt;pub mod payment_intent;pub mod payment_method;+pub mod payout_attempt;+pub mod payouts;pub mod process_tracker;pub mod refund;pub mod reverse_lookup;diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rsnew file mode 100644index 0000000000..804d49d948--- /dev/null+++ b/crates/diesel_models/src/query/payout_attempt.rs@@ -0,0 +1,57 @@+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};+use error_stack::report;+use router_env::{instrument, tracing};++use super::generics;+use crate::{+ errors,+ payout_attempt::{+ PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,+ },+ schema::payout_attempt::dsl,+ PgPooledConn, StorageResult,+};++impl PayoutAttemptNew {+ #[instrument(skip(conn))]+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PayoutAttempt> {+ generics::generic_insert(conn, self).await+ }+}++impl PayoutAttempt {+ pub async fn find_by_merchant_id_payout_id(+ conn: &PgPooledConn,+ merchant_id: &str,+ payout_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::payout_id.eq(payout_id.to_owned())),+ )+ .await+ }++ pub async fn update_by_merchant_id_payout_id(+ conn: &PgPooledConn,+ merchant_id: &str,+ payout_id: &str,+ payout: PayoutAttemptUpdate,+ ) -> StorageResult<Self> {+ generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::payout_id.eq(payout_id.to_owned())),+ PayoutAttemptUpdateInternal::from(payout),+ )+ .await?+ .first()+ .cloned()+ .ok_or_else(|| {+ report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout")+ })+ }+}diff --git a/crates/diesel_models/src/query/payouts.rs b/crates/diesel_models/src/query/payouts.rsnew file mode 100644index 0000000000..2997584136--- /dev/null+++ b/crates/diesel_models/src/query/payouts.rs@@ -0,0 +1,54 @@+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};+use error_stack::report;+use router_env::{instrument, tracing};++use super::generics;+use crate::{+ errors,+ payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal},+ schema::payouts::dsl,+ PgPooledConn, StorageResult,+};++impl PayoutsNew {+ #[instrument(skip(conn))]+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Payouts> {+ generics::generic_insert(conn, self).await+ }+}+impl Payouts {+ pub async fn find_by_merchant_id_payout_id(+ conn: &PgPooledConn,+ merchant_id: &str,+ payout_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::payout_id.eq(payout_id.to_owned())),+ )+ .await+ }++ pub async fn update_by_merchant_id_payout_id(+ conn: &PgPooledConn,+ merchant_id: &str,+ payout_id: &str,+ payout: PayoutsUpdate,+ ) -> StorageResult<Self> {+ generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::payout_id.eq(payout_id.to_owned())),+ PayoutsUpdateInternal::from(payout),+ )+ .await?+ .first()+ .cloned()+ .ok_or_else(|| {+ report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout")+ })+ }+}diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex cd74ed2152..b1cbb88e07 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -253,6 +253,7 @@ diesel::table! {card_cvc -> Nullable<Varchar>,#[max_length = 64]payment_method_id -> Nullable<Varchar>,+ enc_card_data -> Nullable<Text>,}}@@ -328,6 +329,7 @@ diesel::table! {created_at -> Timestamp,modified_at -> Timestamp,frm_routing_algorithm -> Nullable<Jsonb>,+ payout_routing_algorithm -> Nullable<Jsonb>,#[max_length = 32]organization_id -> Nullable<Varchar>,is_recon_enabled -> Bool,@@ -530,6 +532,73 @@ diesel::table! {}}+diesel::table! {+ use diesel::sql_types::*;+ use crate::enums::diesel_exports::*;++ payout_attempt (payout_attempt_id) {+ #[max_length = 64]+ payout_attempt_id -> Varchar,+ #[max_length = 64]+ payout_id -> Varchar,+ #[max_length = 64]+ customer_id -> Varchar,+ #[max_length = 64]+ merchant_id -> Varchar,+ #[max_length = 64]+ address_id -> Varchar,+ #[max_length = 64]+ connector -> Varchar,+ #[max_length = 128]+ connector_payout_id -> Varchar,+ #[max_length = 64]+ payout_token -> Nullable<Varchar>,+ status -> PayoutStatus,+ is_eligible -> Nullable<Bool>,+ error_message -> Nullable<Text>,+ #[max_length = 64]+ error_code -> Nullable<Varchar>,+ business_country -> Nullable<CountryAlpha2>,+ #[max_length = 64]+ business_label -> Nullable<Varchar>,+ created_at -> Timestamp,+ last_modified_at -> Timestamp,+ }+}++diesel::table! {+ use diesel::sql_types::*;+ use crate::enums::diesel_exports::*;++ payouts (payout_id) {+ #[max_length = 64]+ payout_id -> Varchar,+ #[max_length = 64]+ merchant_id -> Varchar,+ #[max_length = 64]+ customer_id -> Varchar,+ #[max_length = 64]+ address_id -> Varchar,+ payout_type -> PayoutType,+ #[max_length = 64]+ payout_method_id -> Nullable<Varchar>,+ amount -> Int8,+ destination_currency -> Currency,+ source_currency -> Currency,+ #[max_length = 255]+ description -> Nullable<Varchar>,+ recurring -> Bool,+ auto_fulfill -> Bool,+ #[max_length = 255]+ return_url -> Nullable<Varchar>,+ #[max_length = 64]+ entity_type -> Varchar,+ metadata -> Nullable<Jsonb>,+ created_at -> Timestamp,+ last_modified_at -> Timestamp,+ }+}+diesel::table! {use diesel::sql_types::*;use crate::enums::diesel_exports::*;@@ -634,6 +703,8 @@ diesel::allow_tables_to_appear_in_same_query!(payment_attempt,payment_intent,payment_methods,+ payout_attempt,+ payouts,process_tracker,refund,reverse_lookup,diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 4b2fde7f62..cccaaca5cb 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -9,7 +9,7 @@ readme = "README.md"license.workspace = true[features]-default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector"]+default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts"]s3 = ["dep:aws-sdk-s3", "dep:aws-config"]kms = ["external_services/kms", "dep:aws-config"]email = ["external_services/email", "dep:aws-config"]@@ -20,12 +20,13 @@ olap = []oltp = []kv_store = []accounts_cache = []-openapi = ["olap", "oltp"]+openapi = ["olap", "oltp", "payouts"]vergen = ["router_env/vergen"]multiple_mca = ["api_models/multiple_mca"]dummy_connector = ["api_models/dummy_connector"]external_access_dc = ["dummy_connector"]detailed_errors = ["api_models/detailed_errors", "error-stack/serde"]+payouts = [][dependencies]diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rsindex c056b454a6..b9d711b195 100644--- a/crates/router/src/compatibility/stripe/errors.rs+++ b/crates/router/src/compatibility/stripe/errors.rs@@ -52,6 +52,9 @@ pub enum StripeErrorCode {#[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")]RefundFailed, // stripe error code+ #[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")]+ PayoutFailed,+#[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")]InternalServerError,@@ -103,6 +106,12 @@ pub enum StripeErrorCode {#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")]ApiKeyNotFound,+ #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")]+ PayoutNotFound,++ #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")]+ DuplicatePayout { payout_id: String },+#[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")]ReturnUrlUnavailable,@@ -427,6 +436,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {errors::ApiErrorResponse::CardExpired { data } => Self::ExpiredCard,errors::ApiErrorResponse::RefundNotPossible { connector } => Self::RefundFailed,errors::ApiErrorResponse::RefundFailed { data } => Self::RefundFailed, // Nothing at stripe to map+ errors::ApiErrorResponse::PayoutFailed { data } => Self::PayoutFailed,errors::ApiErrorResponse::MandateUpdateFailed| errors::ApiErrorResponse::MandateSerializationFailed@@ -451,6 +461,9 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe codeerrors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe codeerrors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest,+ errors::ApiErrorResponse::DuplicatePayout { payout_id } => {+ Self::DuplicatePayout { payout_id }+ }errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound,errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound,errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound,@@ -464,6 +477,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {}errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound,errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound,+ errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound,errors::ApiErrorResponse::MandateValidationFailed { reason } => {Self::PaymentIntentMandateInvalid { message: reason }}@@ -557,6 +571,7 @@ impl actix_web::ResponseError for StripeErrorCode {| Self::ExpiredCard| Self::InvalidCardType| Self::DuplicateRefundRequest+ | Self::DuplicatePayout { .. }| Self::RefundNotFound| Self::CustomerNotFound| Self::ConfigNotFound@@ -568,6 +583,7 @@ impl actix_web::ResponseError for StripeErrorCode {| Self::MerchantConnectorAccountDisabled| Self::MandateNotFound| Self::ApiKeyNotFound+ | Self::PayoutNotFound| Self::DuplicateMerchantAccount| Self::DuplicateMerchantConnectorAccount { .. }| Self::DuplicatePaymentMethod@@ -598,6 +614,7 @@ impl actix_web::ResponseError for StripeErrorCode {| Self::FileProviderNotSupported| Self::PaymentMethodUnactivated => StatusCode::BAD_REQUEST,Self::RefundFailed+ | Self::PayoutFailed| Self::InternalServerError| Self::MandateActive| Self::CustomerRedacteddiff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rsindex 16c8a1e04e..7c4373f7eb 100644--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs@@ -263,7 +263,11 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest {type Error = error_stack::Report<errors::ApiErrorResponse>;fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> {let routable_connector: Option<api_enums::RoutableConnectors> =- item.connector.and_then(|v| v.into_iter().next());+ item.connector.and_then(|v| {+ v.into_iter()+ .next()+ .map(api_enums::RoutableConnectors::from)+ });let routing = routable_connector.map(crate::types::api::RoutingAlgorithm::Single)diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rsindex 5224228a96..10ff32c9ac 100644--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs@@ -154,7 +154,11 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest {type Error = error_stack::Report<errors::ApiErrorResponse>;fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> {let routable_connector: Option<api_enums::RoutableConnectors> =- item.connector.and_then(|v| v.into_iter().next());+ item.connector.and_then(|v| {+ v.into_iter()+ .next()+ .map(api_enums::RoutableConnectors::from)+ });let routing = routable_connector.map(api_types::RoutingAlgorithm::Single)diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 618f49ef21..faa67f0472 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -87,6 +87,8 @@ pub struct Settings {pub required_fields: RequiredFields,pub delayed_session_response: DelayedSessionConfig,pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig,+ #[cfg(feature = "payouts")]+ pub payouts: Payouts,}#[derive(Debug, Deserialize, Clone, Default)]@@ -97,6 +99,9 @@ pub struct TokenizationConfig(pub HashMap<String, PaymentMethodTokenFilter>);pub struct ConnectorCustomer {#[serde(deserialize_with = "connector_deser")]pub connector_list: HashSet<api_models::enums::Connector>,+ #[cfg(feature = "payouts")]+ #[serde(deserialize_with = "payout_connector_deser")]+ pub payout_connector_list: HashSet<api_models::enums::PayoutConnectors>,}fn connector_deser<'a, D>(@@ -113,6 +118,21 @@ where.collect())}+#[cfg(feature = "payouts")]+fn payout_connector_deser<'a, D>(+ deserializer: D,+) -> Result<HashSet<api_models::enums::PayoutConnectors>, D::Error>+where+ D: Deserializer<'a>,+{+ let value = <String>::deserialize(deserializer)?;+ Ok(value+ .trim()+ .split(',')+ .flat_map(api_models::enums::PayoutConnectors::from_str)+ .collect())+}+#[cfg(feature = "dummy_connector")]#[derive(Debug, Deserialize, Clone, Default)]pub struct DummyConnector {@@ -407,6 +427,9 @@ pub struct SupportedConnectors {#[serde(default)]pub struct Connectors {pub aci: ConnectorParams,+ #[cfg(feature = "payouts")]+ pub adyen: ConnectorParamsWithSecondaryBaseUrl,+ #[cfg(not(feature = "payouts"))]pub adyen: ConnectorParams,pub airwallex: ConnectorParams,pub applepay: ConnectorParams,@@ -448,6 +471,7 @@ pub struct Connectors {pub stripe: ConnectorParamsWithFileUploadUrl,pub trustpay: ConnectorParamsWithMoreUrls,pub tsys: ConnectorParams,+ pub wise: ConnectorParams,pub worldline: ConnectorParams,pub worldpay: ConnectorParams,pub zen: ConnectorParams,@@ -477,6 +501,14 @@ pub struct ConnectorParamsWithFileUploadUrl {pub base_url_file_upload: String,}+#[cfg(feature = "payouts")]+#[derive(Debug, Deserialize, Clone, Default)]+#[serde(default)]+pub struct ConnectorParamsWithSecondaryBaseUrl {+ pub base_url: String,+ pub secondary_base_url: String,+}+#[derive(Debug, Clone, Deserialize)]#[serde(default)]pub struct SchedulerSettings {@@ -678,3 +710,9 @@ mod payment_method_deserialization_test {assert!(test_pm.is_ok())}}++#[cfg(feature = "payouts")]+#[derive(Debug, Deserialize, Clone, Default)]+pub struct Payouts {+ pub payout_eligibility: bool,+}diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rsindex 5a78486ad9..8efbd7f313 100644--- a/crates/router/src/configs/validations.rs+++ b/crates/router/src/configs/validations.rs@@ -175,6 +175,22 @@ impl super::settings::ConnectorParamsWithFileUploadUrl {}}+#[cfg(feature = "payouts")]+impl super::settings::ConnectorParamsWithSecondaryBaseUrl {+ pub fn validate(&self) -> Result<(), ApplicationError> {+ common_utils::fp_utils::when(self.base_url.is_default_or_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "connector base URL must not be empty".into(),+ ))+ })?;+ common_utils::fp_utils::when(self.secondary_base_url.is_default_or_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "connector secondary base URL must not be empty".into(),+ ))+ })+ }+}+impl super::settings::SchedulerSettings {pub fn validate(&self) -> Result<(), ApplicationError> {use common_utils::fp_utils::when;diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rsindex 8a103b394c..ab0f3e0587 100644--- a/crates/router/src/connector.rs+++ b/crates/router/src/connector.rs@@ -40,6 +40,7 @@ pub mod stripe;pub mod trustpay;pub mod tsys;pub mod utils;+pub mod wise;pub mod worldline;pub mod worldpay;pub mod zen;@@ -55,5 +56,5 @@ pub use self::{multisafepay::Multisafepay, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei,opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, paypal::Paypal, payu::Payu,powertranz::Powertranz, rapyd::Rapyd, shift4::Shift4, stax::Stax, stripe::Stripe,- trustpay::Trustpay, tsys::Tsys, worldline::Worldline, worldpay::Worldpay, zen::Zen,+ trustpay::Trustpay, tsys::Tsys, wise::Wise, worldline::Worldline, worldpay::Worldpay, zen::Zen,};diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rsindex ed971ecc4f..b2fdc683e7 100644--- a/crates/router/src/connector/adyen.rs+++ b/crates/router/src/connector/adyen.rs@@ -52,6 +52,22 @@ impl ConnectorCommon for Adyen {fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {connectors.adyen.base_url.as_ref()}++ fn build_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ let response: adyen::ErrorResponse = res+ .response+ .parse_struct("ErrorResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ Ok(types::ErrorResponse {+ status_code: res.status_code,+ code: response.error_code,+ message: response.message,+ reason: None,+ })+ }}impl api::Payment for Adyen {}@@ -645,7 +661,6 @@ impl.response.parse_struct("ErrorResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;- logger::info!(response=?res);Ok(types::ErrorResponse {status_code: res.status_code,code: response.error_code,@@ -655,6 +670,380 @@ impl}}+impl api::Payouts for Adyen {}+#[cfg(feature = "payouts")]+impl api::PayoutCancel for Adyen {}+#[cfg(feature = "payouts")]+impl api::PayoutCreate for Adyen {}+#[cfg(feature = "payouts")]+impl api::PayoutEligibility for Adyen {}+#[cfg(feature = "payouts")]+impl api::PayoutFulfill for Adyen {}++#[cfg(feature = "payouts")]+impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData>+ for Adyen+{+ fn get_url(+ &self,+ _req: &types::PayoutsRouterData<api::PoCancel>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!(+ "{}pal/servlet/Payout/v68/declineThirdParty",+ connectors.adyen.secondary_base_url+ ))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoCancel>,+ _connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ let mut header = vec![(+ headers::CONTENT_TYPE.to_string(),+ types::PayoutCancelType::get_content_type(self)+ .to_string()+ .into(),+ )];+ let auth = adyen::AdyenAuthType::try_from(&req.connector_auth_type)+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;+ let mut api_key = vec![(+ headers::X_API_KEY.to_string(),+ auth.review_key.unwrap_or(auth.api_key).into(),+ )];+ header.append(&mut api_key);+ Ok(header)+ }++ fn get_request_body(+ &self,+ req: &types::PayoutsRouterData<api::PoCancel>,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let connector_req = adyen::AdyenPayoutCancelRequest::try_from(req)?;+ let adyen_req = types::RequestBody::log_and_get_request_body(+ &connector_req,+ utils::Encode::<adyen::AdyenPayoutCancelRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(adyen_req))+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoCancel>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PayoutCancelType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PayoutCancelType::get_headers(self, req, connectors)?)+ .body(types::PayoutCancelType::get_request_body(self, req)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoCancel>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> {+ let response: adyen::AdyenPayoutResponse = res+ .response+ .parse_struct("AdyenPayoutResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res)+ }+}++#[cfg(feature = "payouts")]+impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData>+ for Adyen+{+ fn get_url(+ &self,+ _req: &types::PayoutsRouterData<api::PoCreate>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!(+ "{}pal/servlet/Payout/v68/storeDetailAndSubmitThirdParty",+ connectors.adyen.secondary_base_url+ ))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoCreate>,+ _connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ let mut header = vec![(+ headers::CONTENT_TYPE.to_string(),+ types::PayoutCreateType::get_content_type(self)+ .to_string()+ .into(),+ )];+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;+ header.append(&mut api_key);+ Ok(header)+ }++ fn get_request_body(+ &self,+ req: &types::PayoutsRouterData<api::PoCreate>,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let connector_req = adyen::AdyenPayoutCreateRequest::try_from(req)?;+ let adyen_req = types::RequestBody::log_and_get_request_body(+ &connector_req,+ utils::Encode::<adyen::AdyenPayoutCreateRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(adyen_req))+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoCreate>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PayoutCreateType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PayoutCreateType::get_headers(self, req, connectors)?)+ .body(types::PayoutCreateType::get_request_body(self, req)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoCreate>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> {+ let response: adyen::AdyenPayoutResponse = res+ .response+ .parse_struct("AdyenPayoutResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res)+ }+}++#[cfg(feature = "payouts")]+impl+ services::ConnectorIntegration<+ api::PoEligibility,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for Adyen+{+ fn get_url(+ &self,+ _req: &types::PayoutsRouterData<api::PoEligibility>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!("{}v68/payments", self.base_url(connectors),))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoEligibility>,+ _connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ let mut header = vec![(+ headers::CONTENT_TYPE.to_string(),+ types::PayoutEligibilityType::get_content_type(self)+ .to_string()+ .into(),+ )];+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;+ header.append(&mut api_key);+ Ok(header)+ }++ fn get_request_body(+ &self,+ req: &types::PayoutsRouterData<api::PoEligibility>,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let connector_req = adyen::AdyenPayoutEligibilityRequest::try_from(req)?;+ let adyen_req = types::RequestBody::log_and_get_request_body(+ &connector_req,+ utils::Encode::<adyen::AdyenPayoutEligibilityRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(adyen_req))+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoEligibility>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PayoutEligibilityType::get_url(+ self, req, connectors,+ )?)+ .attach_default_headers()+ .headers(types::PayoutEligibilityType::get_headers(+ self, req, connectors,+ )?)+ .body(types::PayoutEligibilityType::get_request_body(self, req)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoEligibility>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoEligibility>, errors::ConnectorError> {+ let response: adyen::AdyenPayoutResponse = res+ .response+ .parse_struct("AdyenPayoutResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res)+ }+}++#[cfg(feature = "payouts")]+impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData>+ for Adyen+{+ fn get_url(+ &self,+ req: &types::PayoutsRouterData<api::PoFulfill>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!(+ "{}pal/servlet/Payout/v68/{}",+ connectors.adyen.secondary_base_url,+ match req.request.payout_type {+ storage_enums::PayoutType::Bank => "confirmThirdParty".to_string(),+ storage_enums::PayoutType::Card => "payout".to_string(),+ }+ ))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoFulfill>,+ _connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ let mut header = vec![(+ headers::CONTENT_TYPE.to_string(),+ types::PayoutFulfillType::get_content_type(self)+ .to_string()+ .into(),+ )];+ let auth = adyen::AdyenAuthType::try_from(&req.connector_auth_type)+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;+ let mut api_key = vec![(+ headers::X_API_KEY.to_string(),+ match req.request.payout_type {+ storage_enums::PayoutType::Bank => auth.review_key.unwrap_or(auth.api_key).into(),+ storage_enums::PayoutType::Card => auth.api_key.into(),+ },+ )];+ header.append(&mut api_key);+ Ok(header)+ }++ fn get_request_body(+ &self,+ req: &types::PayoutsRouterData<api::PoFulfill>,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let connector_req = adyen::AdyenPayoutFulfillRequest::try_from(req)?;+ let adyen_req = types::RequestBody::log_and_get_request_body(+ &connector_req,+ utils::Encode::<adyen::AdyenPayoutFulfillRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(adyen_req))+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoFulfill>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PayoutFulfillType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PayoutFulfillType::get_headers(+ self, req, connectors,+ )?)+ .body(types::PayoutFulfillType::get_request_body(self, req)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoFulfill>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> {+ let response: adyen::AdyenPayoutResponse = res+ .response+ .parse_struct("AdyenPayoutResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res)+ }+}+impl api::Refund for Adyen {}impl api::RefundExecute for Adyen {}impl api::RefundSync for Adyen {}@@ -687,7 +1076,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefOk(format!("{}v68/payments/{}/refunds",self.base_url(connectors),- connector_payment_id,+ connector_payment_id))}@@ -733,7 +1122,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref.response.parse_struct("AdyenRefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;- logger::info!(response=?res);types::RouterData::try_from(types::ResponseRouterData {response,data: data.clone(),@@ -750,7 +1138,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref.response.parse_struct("ErrorResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;- logger::info!(response=?res);Ok(types::ErrorResponse {status_code: res.status_code,code: response.error_code,diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rsindex 02300cc0e9..7e30d1020c 100644--- a/crates/router/src/connector/adyen/transformers.rs+++ b/crates/router/src/connector/adyen/transformers.rs@@ -1,3 +1,5 @@+#[cfg(feature = "payouts")]+use api_models::payouts::PayoutMethodData;use api_models::{enums, payments, webhooks};use cards::CardNumber;use masking::PeekInterface;@@ -5,6 +7,10 @@ use reqwest::Url;use serde::{Deserialize, Serialize};use time::PrimitiveDateTime;+#[cfg(feature = "payouts")]+use crate::connector::utils::AddressDetailsData;+#[cfg(feature = "payouts")]+use crate::types::api::payouts;use crate::{connector::utils::{self, BrowserInformationData, CardData, MandateReferenceData, PaymentsAuthorizeRequestData,@@ -62,16 +68,19 @@ pub struct AdditionalData {#[serde(rename = "recurring.shopperReference")]recurring_shopper_reference: Option<String>,network_tx_reference: Option<String>,+ #[cfg(feature = "payouts")]+ payout_eligible: Option<PayoutEligibility>,+ funds_availability: Option<String>,}-#[derive(Debug, Serialize)]+#[derive(Default, Debug, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ShopperName {first_name: Option<Secret<String>>,last_name: Option<Secret<String>>,}-#[derive(Default, Debug, Serialize)]+#[derive(Default, Debug, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Address {city: Option<String>,@@ -144,6 +153,15 @@ pub enum AdyenStatus {Received,RedirectShopper,Refused,+ #[cfg(feature = "payouts")]+ #[serde(rename = "[payout-confirm-received]")]+ PayoutConfirmReceived,+ #[cfg(feature = "payouts")]+ #[serde(rename = "[payout-decline-received]")]+ PayoutDeclineReceived,+ #[cfg(feature = "payouts")]+ #[serde(rename = "[payout-submit-received]")]+ PayoutSubmitReceived,}#[derive(Debug, Clone, Serialize)]@@ -170,6 +188,12 @@ impl ForeignFrom<(bool, AdyenStatus)> for storage_enums::AttemptStatus {AdyenStatus::Error | AdyenStatus::Refused => Self::Failure,AdyenStatus::Pending => Self::Pending,AdyenStatus::Received => Self::Started,+ #[cfg(feature = "payouts")]+ AdyenStatus::PayoutConfirmReceived => Self::Started,+ #[cfg(feature = "payouts")]+ AdyenStatus::PayoutSubmitReceived => Self::Pending,+ #[cfg(feature = "payouts")]+ AdyenStatus::PayoutDeclineReceived => Self::Voided,}}}@@ -723,6 +747,8 @@ pub struct AdyenRefundResponse {pub struct AdyenAuthType {pub(super) api_key: String,pub(super) merchant_account: String,+ #[allow(dead_code)]+ pub(super) review_key: Option<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -848,13 +874,22 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> {impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType {type Error = Error;fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {- if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {- Ok(Self {+ match auth_type {+ types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {api_key: api_key.to_string(),merchant_account: key1.to_string(),- })- } else {- Err(errors::ConnectorError::FailedToObtainAuthType)?+ review_key: None,+ }),+ types::ConnectorAuthType::SignatureKey {+ api_key,+ key1,+ api_secret,+ } => Ok(Self {+ api_key: api_key.to_string(),+ merchant_account: key1.to_string(),+ review_key: Some(api_secret.to_string()),+ }),+ _ => Err(errors::ConnectorError::FailedToObtainAuthType)?,}}}@@ -961,6 +996,7 @@ fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<Addirecurring_detail_reference: None,recurring_shopper_reference: None,recurring_processing_model: Some(AdyenRecurringModel::UnscheduledCardOnFile),+ ..AdditionalData::default()}),_ => None,}@@ -1039,23 +1075,32 @@ fn get_telephone_number(item: &types::PaymentsAuthorizeRouterData) -> Option<Sec})}-fn get_shopper_name(item: &types::PaymentsAuthorizeRouterData) -> Option<ShopperName> {- let address = item- .address- .billing- .as_ref()- .and_then(|billing| billing.address.as_ref());+fn get_shopper_name(address: Option<&api_models::payments::Address>) -> Option<ShopperName> {+ let billing = address.and_then(|billing| billing.address.as_ref());Some(ShopperName {- first_name: address.and_then(|address| address.first_name.clone()),- last_name: address.and_then(|address| address.last_name.clone()),+ first_name: billing.and_then(|a| a.first_name.clone()),+ last_name: billing.and_then(|a| a.last_name.clone()),})}-fn get_country_code(item: &types::PaymentsAuthorizeRouterData) -> Option<api_enums::CountryAlpha2> {- item.address- .billing- .as_ref()- .and_then(|billing| billing.address.as_ref().and_then(|address| address.country))+fn get_country_code(+ address: Option<&api_models::payments::Address>,+) -> Option<api_enums::CountryAlpha2> {+ address.and_then(|billing| billing.address.as_ref().and_then(|address| address.country))+}++#[cfg(feature = "payouts")]+fn get_payout_card_details(payout_method_data: &PayoutMethodData) -> Option<PayoutCardDetails> {+ match payout_method_data {+ PayoutMethodData::Card(card) => Some(PayoutCardDetails {+ _type: "scheme".to_string(), // FIXME: Remove hardcoding+ number: card.card_number.peek().to_string(),+ expiry_month: card.expiry_month.peek().to_string(),+ expiry_year: card.expiry_year.peek().to_string(),+ holder_name: card.card_holder_name.peek().to_string(),+ }),+ _ => None,+ }}impl<'a> TryFrom<&api_models::payments::BankDebitData> for AdyenPaymentMethod<'a> {@@ -1614,7 +1659,7 @@ impl<'a>let additional_data = get_additional_data(item);let return_url = item.request.get_return_url()?;let payment_method = AdyenPaymentMethod::try_from(bank_debit_data)?;- let country_code = get_country_code(item);+ let country_code = get_country_code(item.address.billing.as_ref());let request = AdyenPaymentRequest {amount,merchant_account: auth_type.merchant_account,@@ -1789,13 +1834,13 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::PayLaterData)>let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;let browser_info = get_browser_info(item)?;let additional_data = get_additional_data(item);- let country_code = get_country_code(item);+ let country_code = get_country_code(item.address.billing.as_ref());let payment_method = AdyenPaymentMethod::try_from((paylater_data, country_code))?;let shopper_interaction = AdyenShopperInteraction::from(item);let (recurring_processing_model, store_payment_method, shopper_reference) =get_recurring_processing_model(item)?;let return_url = item.request.get_return_url()?;- let shopper_name = get_shopper_name(item);+ let shopper_name: Option<ShopperName> = get_shopper_name(item.address.billing.as_ref());let shopper_email = item.request.email.clone();let billing_address = get_address_info(item.address.billing.as_ref());let delivery_address = get_address_info(item.address.shipping.as_ref());@@ -2355,3 +2400,354 @@ impl From<AdyenNotificationRequestItemWH> for Response {}}}++// Payouts+#[cfg(feature = "payouts")]+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AdyenPayoutCreateRequest {+ amount: Amount,+ recurring: RecurringContract,+ merchant_account: String,+ bank: PayoutBankDetails,+ reference: String,+ shopper_reference: String,+ shopper_email: Option<Email>,+ shopper_name: ShopperName,+ date_of_birth: Option<Secret<String>>,+ entity_type: Option<storage_enums::PayoutEntityType>,+ nationality: Option<storage_enums::CountryAlpha2>,+ billing_address: Option<Address>,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct PayoutBankDetails {+ bank_name: String,+ bic: Option<Secret<String>>,+ country_code: storage_enums::CountryAlpha2,+ iban: Option<Secret<String>>,+ owner_name: Option<Secret<String>>,+ bank_city: String,+ tax_id: Option<Secret<String>>,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct RecurringContract {+ contract: Contract,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+enum Contract {+ Oneclick,+ Recurring,+ Payout,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AdyenPayoutResponse {+ psp_reference: String,+ result_code: Option<AdyenStatus>,+ response: Option<AdyenStatus>,+ amount: Option<Amount>,+ merchant_reference: Option<String>,+ refusal_reason: Option<String>,+ refusal_reason_code: Option<String>,+ additional_data: Option<AdditionalData>,+ auth_code: Option<String>,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AdyenPayoutEligibilityRequest {+ amount: Amount,+ merchant_account: String,+ payment_method: PayoutCardDetails,+ reference: String,+ shopper_reference: String,+}++#[cfg(feature = "payouts")]+#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct PayoutCardDetails {+ #[serde(rename = "type")]+ _type: String,+ number: String,+ expiry_month: String,+ expiry_year: String,+ holder_name: String,+}++#[cfg(feature = "payouts")]+#[derive(Clone, Default, Debug, Serialize, Deserialize, Eq, PartialEq)]+pub enum PayoutEligibility {+ #[serde(rename = "Y")]+ Yes,+ #[serde(rename = "N")]+ #[default]+ No,+ #[serde(rename = "D")]+ Domestic,+ #[serde(rename = "U")]+ Unknown,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize, Deserialize)]+#[serde(untagged)]+pub enum AdyenPayoutFulfillRequest {+ Bank(PayoutFulfillBankRequest),+ Card(Box<PayoutFulfillCardRequest>),+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PayoutFulfillBankRequest {+ merchant_account: String,+ original_reference: String,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PayoutFulfillCardRequest {+ amount: Amount,+ card: PayoutCardDetails,+ billing_address: Option<Address>,+ merchant_account: String,+ reference: String,+ shopper_name: ShopperName,+ nationality: Option<storage_enums::CountryAlpha2>,+ entity_type: Option<storage_enums::PayoutEntityType>,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AdyenPayoutCancelRequest {+ original_reference: String,+ merchant_account: String,+}++// Payouts eligibility request transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<&types::PayoutsRouterData<F>> for AdyenPayoutEligibilityRequest {+ type Error = Error;+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {+ let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;+ let payout_method_data = get_payout_card_details(&item.get_payout_method_data()?).map_or(+ Err(errors::ConnectorError::MissingRequiredField {+ field_name: "payout_method_data",+ }),+ Ok,+ )?;+ Ok(Self {+ amount: Amount {+ currency: item.request.destination_currency.to_string(),+ value: item.request.amount,+ },+ merchant_account: auth_type.merchant_account,+ payment_method: payout_method_data,+ reference: item.request.payout_id.clone(),+ shopper_reference: item.merchant_id.clone(),+ })+ }+}++// Payouts create request transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<&types::PayoutsRouterData<F>> for AdyenPayoutCancelRequest {+ type Error = Error;+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {+ let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;++ let merchant_account = auth_type.merchant_account;+ if let Some(id) = &item.request.connector_payout_id {+ Ok(Self {+ merchant_account,+ original_reference: id.to_string(),+ })+ } else {+ Err(errors::ConnectorError::MissingRequiredField {+ field_name: "connector_payout_id",+ })?+ }+ }+}++// Payouts cancel request transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<&types::PayoutsRouterData<F>> for AdyenPayoutCreateRequest {+ type Error = Error;+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {+ let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;+ let merchant_account = auth_type.merchant_account;+ let (owner_name, customer_email) = item+ .request+ .customer_details+ .to_owned()+ .map_or((None, None), |c| (c.name, c.email));++ match item.get_payout_method_data()? {+ PayoutMethodData::Card(_) => Err(errors::ConnectorError::NotSupported {+ message: "Card payout creation is not supported".to_string(),+ connector: "Adyen",+ payment_experience: "".to_string(),+ })?,+ PayoutMethodData::Bank(bd) => {+ let bank_details = match bd {+ payouts::BankPayout::Sepa(b) => PayoutBankDetails {+ bank_name: b.bank_name,+ country_code: b.bank_country_code,+ bank_city: b.bank_city,+ owner_name,+ bic: b.bic,+ iban: Some(b.iban),+ tax_id: None,+ },+ _ => Err(errors::ConnectorError::NotSupported {+ message: "Bank transfers via ACH or Bacs are not supported".to_string(),+ connector: "Adyen",+ payment_experience: "".to_string(),+ })?,+ };+ let address: &payments::AddressDetails = item.get_billing_address()?;+ Ok(Self {+ amount: Amount {+ value: item.request.amount,+ currency: item.request.destination_currency.to_string(),+ },+ recurring: RecurringContract {+ contract: Contract::Payout,+ },+ merchant_account,+ bank: bank_details,+ reference: item.request.payout_id.to_owned(),+ shopper_reference: item.merchant_id.to_owned(),+ shopper_email: customer_email,+ shopper_name: ShopperName {+ first_name: address.get_first_name().ok().cloned(),+ last_name: address.get_last_name().ok().cloned(),+ },+ date_of_birth: None,+ entity_type: Some(item.request.entity_type),+ nationality: get_country_code(item.address.billing.as_ref()),+ billing_address: get_address_info(item.address.billing.as_ref()),+ })+ }+ }+ }+}++// Payouts fulfill request transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<&types::PayoutsRouterData<F>> for AdyenPayoutFulfillRequest {+ type Error = Error;+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {+ let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;+ let payout_type = item.request.payout_type.to_owned();+ let merchant_account = auth_type.merchant_account;+ match payout_type {+ storage_enums::PayoutType::Bank => Ok(Self::Bank(PayoutFulfillBankRequest {+ merchant_account,+ original_reference: item+ .request+ .connector_payout_id+ .clone()+ .unwrap_or("".to_string()),+ })),+ storage_enums::PayoutType::Card => {+ let address = item.get_billing_address()?;+ Ok(Self::Card(Box::new(PayoutFulfillCardRequest {+ amount: Amount {+ value: item.request.amount,+ currency: item.request.destination_currency.to_string(),+ },+ card: get_payout_card_details(&item.get_payout_method_data()?).map_or(+ Err(errors::ConnectorError::MissingRequiredField {+ field_name: "payout_method_data",+ }),+ Ok,+ )?,+ billing_address: get_address_info(item.get_billing().ok()),+ merchant_account,+ reference: item.request.payout_id.clone(),+ shopper_name: ShopperName {+ first_name: address.get_first_name().ok().cloned(),+ last_name: address.get_last_name().ok().cloned(),+ },+ nationality: get_country_code(item.address.billing.as_ref()),+ entity_type: Some(item.request.entity_type),+ })))+ }+ }+ }+}++// Payouts response transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenPayoutResponse>>+ for types::PayoutsRouterData<F>+{+ type Error = Error;+ fn try_from(+ item: types::PayoutsResponseRouterData<F, AdyenPayoutResponse>,+ ) -> Result<Self, Self::Error> {+ let response: AdyenPayoutResponse = item.response;+ let payout_eligible = response+ .additional_data+ .and_then(|pa| pa.payout_eligible)+ .map(|pe| pe == PayoutEligibility::Yes || pe == PayoutEligibility::Domestic);++ let status = payout_eligible.map_or(+ {+ response.result_code.map_or(+ response+ .response+ .map(storage_enums::PayoutStatus::foreign_from),+ |rc| Some(storage_enums::PayoutStatus::foreign_from(rc)),+ )+ },+ |pe| {+ if pe {+ Some(storage_enums::PayoutStatus::RequiresFulfillment)+ } else {+ Some(storage_enums::PayoutStatus::Ineligible)+ }+ },+ );++ Ok(Self {+ response: Ok(types::PayoutsResponseData {+ status,+ connector_payout_id: response.psp_reference,+ payout_eligible,+ }),+ ..item.data+ })+ }+}++#[cfg(feature = "payouts")]+impl ForeignFrom<AdyenStatus> for storage_enums::PayoutStatus {+ fn foreign_from(adyen_status: AdyenStatus) -> Self {+ match adyen_status {+ AdyenStatus::Authorised | AdyenStatus::PayoutConfirmReceived => Self::Success,+ AdyenStatus::Cancelled | AdyenStatus::PayoutDeclineReceived => Self::Cancelled,+ AdyenStatus::Error => Self::Failed,+ AdyenStatus::Pending => Self::Pending,+ AdyenStatus::PayoutSubmitReceived => Self::RequiresFulfillment,+ _ => Self::Ineligible,+ }+ }+}diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rsindex 321eb70624..66c980d2d3 100644--- a/crates/router/src/connector/utils.rs+++ b/crates/router/src/connector/utils.rs@@ -68,6 +68,10 @@ pub trait RouterData {fn get_customer_id(&self) -> Result<String, Error>;fn get_connector_customer_id(&self) -> Result<String, Error>;fn get_preprocessing_id(&self) -> Result<String, Error>;+ #[cfg(feature = "payouts")]+ fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>;+ #[cfg(feature = "payouts")]+ fn get_quote_id(&self) -> Result<String, Error>;}impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> {@@ -166,6 +170,18 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re.to_owned().ok_or_else(missing_field_err("preprocessing_id"))}+ #[cfg(feature = "payouts")]+ fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error> {+ self.payout_method_data+ .to_owned()+ .ok_or_else(missing_field_err("payout_method_data"))+ }+ #[cfg(feature = "payouts")]+ fn get_quote_id(&self) -> Result<String, Error> {+ self.quote_id+ .to_owned()+ .ok_or_else(missing_field_err("quote_id"))+ }}pub trait PaymentsPreProcessingData {diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rsnew file mode 100644index 0000000000..853837b58e--- /dev/null+++ b/crates/router/src/connector/wise.rs@@ -0,0 +1,688 @@+mod transformers;++use std::fmt::Debug;++use error_stack::{IntoReport, ResultExt};+#[cfg(feature = "payouts")]+use router_env::{instrument, tracing};++use self::transformers as wise;+use crate::{+ configs::settings,+ core::errors::{self, CustomResult},+ headers, services,+ services::request,+ types::{+ self,+ api::{self, ConnectorCommon, ConnectorCommonExt},+ },+ utils::BytesExt,+};+#[cfg(feature = "payouts")]+use crate::{core::payments, routes, utils};++#[derive(Debug, Clone)]+pub struct Wise;++impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wise+where+ Self: services::ConnectorIntegration<Flow, Request, Response>,+{+ #[cfg(feature = "payouts")]+ fn build_headers(+ &self,+ req: &types::RouterData<Flow, Request, Response>,+ _connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ let mut header = vec![(+ headers::CONTENT_TYPE.to_string(),+ types::PayoutQuoteType::get_content_type(self)+ .to_string()+ .into(),+ )];+ let auth = wise::WiseAuthType::try_from(&req.connector_auth_type)+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;+ let mut api_key = vec![(headers::AUTHORIZATION.to_string(), auth.api_key.into())];+ header.append(&mut api_key);+ Ok(header)+ }+}++impl ConnectorCommon for Wise {+ fn id(&self) -> &'static str {+ "wise"+ }++ fn get_auth_header(+ &self,+ auth_type: &types::ConnectorAuthType,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ let auth = wise::WiseAuthType::try_from(auth_type)+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;+ Ok(vec![(+ headers::AUTHORIZATION.to_string(),+ auth.api_key.into(),+ )])+ }++ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {+ connectors.wise.base_url.as_ref()+ }++ fn build_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ let response: wise::ErrorResponse = res+ .response+ .parse_struct("ErrorResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ let default_status = response.status.unwrap_or_default().to_string();+ match response.errors {+ Some(errs) => {+ if let Some(e) = errs.get(0) {+ Ok(types::ErrorResponse {+ status_code: res.status_code,+ code: e.code.clone(),+ message: e.message.clone(),+ reason: None,+ })+ } else {+ Ok(types::ErrorResponse {+ status_code: res.status_code,+ code: default_status,+ message: response.message.unwrap_or_default(),+ reason: None,+ })+ }+ }+ None => Ok(types::ErrorResponse {+ status_code: res.status_code,+ code: default_status,+ message: response.message.unwrap_or_default(),+ reason: None,+ }),+ }+ }+}++impl api::Payment for Wise {}+impl api::PaymentAuthorize for Wise {}+impl api::PaymentSync for Wise {}+impl api::PaymentVoid for Wise {}+impl api::PaymentCapture for Wise {}+impl api::PreVerify for Wise {}+impl api::ConnectorAccessToken for Wise {}+impl api::PaymentToken for Wise {}++impl+ services::ConnectorIntegration<+ api::PaymentMethodToken,+ types::PaymentMethodTokenizationData,+ types::PaymentsResponseData,+ > for Wise+{+}++impl+ services::ConnectorIntegration<+ api::AccessTokenAuth,+ types::AccessTokenRequestData,+ types::AccessToken,+ > for Wise+{+}++impl+ services::ConnectorIntegration<+ api::Verify,+ types::VerifyRequestData,+ types::PaymentsResponseData,+ > for Wise+{+}++impl api::PaymentSession for Wise {}++impl+ services::ConnectorIntegration<+ api::Session,+ types::PaymentsSessionData,+ types::PaymentsResponseData,+ > for Wise+{+}++impl+ services::ConnectorIntegration<+ api::Capture,+ types::PaymentsCaptureData,+ types::PaymentsResponseData,+ > for Wise+{+}++impl+ services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>+ for Wise+{+}++impl+ services::ConnectorIntegration<+ api::Authorize,+ types::PaymentsAuthorizeData,+ types::PaymentsResponseData,+ > for Wise+{+}++impl+ services::ConnectorIntegration<+ api::Void,+ types::PaymentsCancelData,+ types::PaymentsResponseData,+ > for Wise+{+}++impl api::Payouts for Wise {}+#[cfg(feature = "payouts")]+impl api::PayoutCancel for Wise {}+#[cfg(feature = "payouts")]+impl api::PayoutCreate for Wise {}+#[cfg(feature = "payouts")]+impl api::PayoutEligibility for Wise {}+#[cfg(feature = "payouts")]+impl api::PayoutQuote for Wise {}+#[cfg(feature = "payouts")]+impl api::PayoutRecipient for Wise {}+#[cfg(feature = "payouts")]+impl api::PayoutFulfill for Wise {}++#[cfg(feature = "payouts")]+impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData>+ for Wise+{+ fn get_url(+ &self,+ req: &types::PayoutsRouterData<api::PoCancel>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ let transfer_id = req.request.connector_payout_id.clone().ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "transfer_id",+ },+ )?;+ Ok(format!(+ "{}v1/transfers/{}/cancel",+ connectors.wise.base_url, transfer_id+ ))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoCancel>,+ _connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ self.build_headers(req, _connectors)+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoCancel>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Put)+ .url(&types::PayoutCancelType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PayoutCancelType::get_headers(self, req, connectors)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoCancel>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> {+ let response: wise::WisePayoutResponse = res+ .response+ .parse_struct("WisePayoutResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ let response: wise::ErrorResponse = res+ .response+ .parse_struct("ErrorResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ let def_res = response.status.unwrap_or_default().to_string();+ let errors = response.errors.unwrap_or_default();+ let (code, message) = if let Some(e) = errors.get(0) {+ (e.code.clone(), e.message.clone())+ } else {+ (def_res, response.message.unwrap_or_default())+ };+ Ok(types::ErrorResponse {+ status_code: res.status_code,+ code,+ message,+ reason: None,+ })+ }+}++#[cfg(feature = "payouts")]+impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData>+ for Wise+{+ fn get_url(+ &self,+ req: &types::PayoutsRouterData<api::PoQuote>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ let auth = wise::WiseAuthType::try_from(&req.connector_auth_type)+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;+ Ok(format!(+ "{}v3/profiles/{}/quotes",+ connectors.wise.base_url, auth.profile_id+ ))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoQuote>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ self.build_headers(req, connectors)+ }++ fn get_request_body(+ &self,+ req: &types::PayoutsRouterData<api::PoQuote>,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let connector_req = wise::WisePayoutQuoteRequest::try_from(req)?;+ let wise_req = types::RequestBody::log_and_get_request_body(+ &connector_req,+ utils::Encode::<wise::WisePayoutQuoteRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(wise_req))+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoQuote>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PayoutQuoteType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PayoutQuoteType::get_headers(self, req, connectors)?)+ .body(types::PayoutQuoteType::get_request_body(self, req)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoQuote>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoQuote>, errors::ConnectorError> {+ let response: wise::WisePayoutQuoteResponse = res+ .response+ .parse_struct("WisePayoutQuoteResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res)+ }+}++#[cfg(feature = "payouts")]+impl+ services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData>+ for Wise+{+ fn get_url(+ &self,+ _req: &types::PayoutsRouterData<api::PoRecipient>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!("{}v1/accounts", connectors.wise.base_url))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoRecipient>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ self.build_headers(req, connectors)+ }++ fn get_request_body(+ &self,+ req: &types::PayoutsRouterData<api::PoRecipient>,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let connector_req = wise::WiseRecipientCreateRequest::try_from(req)?;+ let wise_req = types::RequestBody::log_and_get_request_body(+ &connector_req,+ utils::Encode::<wise::WiseRecipientCreateRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(wise_req))+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoRecipient>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PayoutRecipientType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PayoutRecipientType::get_headers(+ self, req, connectors,+ )?)+ .body(types::PayoutRecipientType::get_request_body(self, req)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoRecipient>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> {+ let response: wise::WiseRecipientCreateResponse = res+ .response+ .parse_struct("WiseRecipientCreateResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res)+ }+}++#[async_trait::async_trait]+#[cfg(feature = "payouts")]+impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData>+ for Wise+{+ async fn execute_pretasks(+ &self,+ router_data: &mut types::PayoutsRouterData<api::PoCreate>,+ app_state: &routes::AppState,+ ) -> CustomResult<(), errors::ConnectorError> {+ // Create a quote+ let quote_router_data =+ &types::PayoutsRouterData::from((&router_data, router_data.request.clone()));+ let quote_connector_integration: Box<+ &(dyn services::ConnectorIntegration<+ api::PoQuote,+ types::PayoutsData,+ types::PayoutsResponseData,+ > + Send+ + Sync+ + 'static),+ > = Box::new(self);+ let quote_router_resp = services::execute_connector_processing_step(+ app_state,+ quote_connector_integration,+ quote_router_data,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await?;++ match quote_router_resp.response.to_owned() {+ Ok(resp) => {+ router_data.quote_id = Some(resp.connector_payout_id);+ Ok(())+ }+ Err(_err) => {+ router_data.response = quote_router_resp.response;+ Ok(())+ }+ }+ }++ fn get_url(+ &self,+ _req: &types::PayoutsRouterData<api::PoCreate>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!("{}/v1/transfers", connectors.wise.base_url))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoCreate>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ self.build_headers(req, connectors)+ }++ fn get_request_body(+ &self,+ req: &types::PayoutsRouterData<api::PoCreate>,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let connector_req = wise::WisePayoutCreateRequest::try_from(req)?;+ let wise_req = types::RequestBody::log_and_get_request_body(+ &connector_req,+ utils::Encode::<wise::WisePayoutCreateRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(wise_req))+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoCreate>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PayoutCreateType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PayoutCreateType::get_headers(self, req, connectors)?)+ .body(types::PayoutCreateType::get_request_body(self, req)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoCreate>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> {+ let response: wise::WisePayoutResponse = res+ .response+ .parse_struct("WisePayoutResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res)+ }+}++#[cfg(feature = "payouts")]+impl+ services::ConnectorIntegration<+ api::PoEligibility,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for Wise+{+}++#[cfg(feature = "payouts")]+impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData>+ for Wise+{+ fn get_url(+ &self,+ req: &types::PayoutsRouterData<api::PoFulfill>,+ connectors: &settings::Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ let auth = wise::WiseAuthType::try_from(&req.connector_auth_type)+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;+ let transfer_id = req.request.connector_payout_id.to_owned().ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "transfer_id",+ },+ )?;+ Ok(format!(+ "{}v3/profiles/{}/transfers/{}/payments",+ connectors.wise.base_url, auth.profile_id, transfer_id+ ))+ }++ fn get_headers(+ &self,+ req: &types::PayoutsRouterData<api::PoFulfill>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {+ self.build_headers(req, connectors)+ }++ fn get_request_body(+ &self,+ req: &types::PayoutsRouterData<api::PoFulfill>,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let connector_req = wise::WisePayoutFulfillRequest::try_from(req)?;+ let wise_req = types::RequestBody::log_and_get_request_body(+ &connector_req,+ utils::Encode::<wise::WisePayoutFulfillRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(wise_req))+ }++ fn build_request(+ &self,+ req: &types::PayoutsRouterData<api::PoFulfill>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ let request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PayoutFulfillType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PayoutFulfillType::get_headers(+ self, req, connectors,+ )?)+ .body(types::PayoutFulfillType::get_request_body(self, req)?)+ .build();++ Ok(Some(request))+ }++ #[instrument(skip_all)]+ fn handle_response(+ &self,+ data: &types::PayoutsRouterData<api::PoFulfill>,+ res: types::Response,+ ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> {+ let response: wise::WiseFulfillResponse = res+ .response+ .parse_struct("WiseFulfillResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ types::RouterData::try_from(types::ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ }++ fn get_error_response(+ &self,+ res: types::Response,+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res)+ }+}++impl api::Refund for Wise {}+impl api::RefundExecute for Wise {}+impl api::RefundSync for Wise {}++impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>+ for Wise+{+}++impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>+ for Wise+{+}++#[async_trait::async_trait]+impl api::IncomingWebhook for Wise {+ fn get_webhook_object_reference_id(+ &self,+ _request: &api::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()+ }++ fn get_webhook_event_type(+ &self,+ _request: &api::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()+ }++ fn get_webhook_resource_object(+ &self,+ _request: &api::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()+ }+}diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rsnew file mode 100644index 0000000000..e9513873cd--- /dev/null+++ b/crates/router/src/connector/wise/transformers.rs@@ -0,0 +1,616 @@+#[cfg(feature = "payouts")]+use api_models::payouts::PayoutMethodData;+#[cfg(feature = "payouts")]+use common_utils::pii::Email;+#[cfg(feature = "payouts")]+use masking::Secret;+use serde::Deserialize;+#[cfg(feature = "payouts")]+use serde::Serialize;++type Error = error_stack::Report<errors::ConnectorError>;++#[cfg(feature = "payouts")]+use crate::{+ connector::utils::RouterData,+ types::{+ api::payouts,+ storage::enums::{self as storage_enums, PayoutEntityType},+ transformers::ForeignFrom,+ },+};+use crate::{core::errors, types};++pub struct WiseAuthType {+ pub(super) api_key: String,+ #[allow(dead_code)]+ pub(super) profile_id: String,+}++impl TryFrom<&types::ConnectorAuthType> for WiseAuthType {+ type Error = Error;+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {+ match auth_type {+ types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {+ api_key: api_key.to_string(),+ profile_id: key1.to_string(),+ }),+ _ => Err(errors::ConnectorError::FailedToObtainAuthType)?,+ }+ }+}++// Wise error response+#[derive(Debug, Deserialize)]+pub struct ErrorResponse {+ pub timestamp: Option<String>,+ pub errors: Option<Vec<SubError>>,+ pub status: Option<i32>,+ pub error: Option<String>,+ pub error_description: Option<String>,+ pub message: Option<String>,+ pub path: Option<String>,+}++#[derive(Debug, Deserialize)]+pub struct SubError {+ pub code: String,+ pub message: String,+ pub path: Option<String>,+ pub field: Option<String>,+ pub arguments: Option<Vec<String>>,+}++// Payouts+#[cfg(feature = "payouts")]+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WiseRecipientCreateRequest {+ currency: String,+ #[serde(rename = "type")]+ recipient_type: RecipientType,+ profile: String,+ account_holder_name: Secret<String>,+ details: WiseBankDetails,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize)]+#[serde(rename_all = "snake_case")]+#[allow(dead_code)]+pub enum RecipientType {+ Aba,+ Iban,+ SortCode,+ SwiftCode,+}+#[cfg(feature = "payouts")]+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+pub enum AccountType {+ Checking,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WiseBankDetails {+ legal_type: LegalType,+ account_type: Option<AccountType>,+ address: WiseAddressDetails,+ post_code: Option<String>,+ nationality: Option<String>,+ account_holder_name: Option<Secret<String>>,+ email: Option<Email>,+ account_number: Option<Secret<String>>,+ city: Option<String>,+ sort_code: Option<Secret<String>>,+ iban: Option<Secret<String>>,+ bic: Option<Secret<String>>,+ transit_number: Option<Secret<String>>,+ routing_number: Option<Secret<String>>,+ abartn: Option<Secret<String>>,+ swift_code: Option<Secret<String>>,+ payin_reference: Option<String>,+ psp_reference: Option<String>,+ tax_id: Option<String>,+ order_id: Option<String>,+ job: Option<String>,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Default, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+pub enum LegalType {+ Business,+ #[default]+ Private,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WiseAddressDetails {+ country: Option<storage_enums::CountryAlpha2>,+ country_code: Option<storage_enums::CountryAlpha2>,+ first_line: Option<Secret<String>>,+ post_code: Option<Secret<String>>,+ city: Option<String>,+ state: Option<Secret<String>>,+}++#[allow(dead_code)]+#[cfg(feature = "payouts")]+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WiseRecipientCreateResponse {+ id: i64,+ business: Option<i64>,+ profile: Option<i64>,+ account_holder_name: Secret<String>,+ currency: String,+ country: String,+ #[serde(rename = "type")]+ request_type: String,+ details: WiseBankDetails,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WisePayoutQuoteRequest {+ source_currency: String,+ target_currency: String,+ source_amount: Option<i64>,+ target_amount: Option<i64>,+ pay_out: WisePayOutOption,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Default, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum WisePayOutOption {+ Balance,+ #[default]+ BankTransfer,+ Swift,+ SwiftOur,+ Interac,+}++#[allow(dead_code)]+#[cfg(feature = "payouts")]+#[derive(Debug, Default, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WisePayoutQuoteResponse {+ source_amount: f64,+ client_id: String,+ id: String,+ status: WiseStatus,+ profile: i64,+ rate: i8,+ source_currency: String,+ target_currency: String,+ user: i64,+ rate_type: WiseRateType,+ pay_out: WisePayOutOption,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Default, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum WiseRateType {+ #[default]+ Fixed,+ Floating,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WisePayoutCreateRequest {+ target_account: i64,+ quote_uuid: String,+ customer_transaction_id: String,+ details: WiseTransferDetails,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WiseTransferDetails {+ transfer_purpose: Option<String>,+ source_of_funds: Option<String>,+ transfer_purpose_sub_transfer_purpose: Option<String>,+}++#[allow(dead_code)]+#[cfg(feature = "payouts")]+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WisePayoutResponse {+ id: i64,+ user: i64,+ target_account: i64,+ source_account: Option<i64>,+ quote_uuid: String,+ status: WiseStatus,+ reference: String,+ rate: f32,+ business: Option<i64>,+ details: WiseTransferDetails,+ has_active_issues: bool,+ source_currency: String,+ source_value: f64,+ target_currency: String,+ target_value: f64,+ customer_transaction_id: String,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WisePayoutFulfillRequest {+ #[serde(rename = "type")]+ fund_type: FundType,+}++// NOTE - Only balance is allowed as time of incorporating this field - https://api-docs.transferwise.com/api-reference/transfer#fund+#[cfg(feature = "payouts")]+#[derive(Debug, Default, Serialize)]+#[serde(rename_all = "UPPERCASE")]+pub enum FundType {+ #[default]+ Balance,+}++#[allow(dead_code)]+#[cfg(feature = "payouts")]+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WiseFulfillResponse {+ status: WiseStatus,+ error_code: Option<String>,+ error_message: Option<String>,+ balance_transaction_id: Option<i64>,+}++#[cfg(feature = "payouts")]+#[derive(Debug, Default, Clone, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+pub enum WiseStatus {+ Completed,+ Pending,+ Rejected,++ #[serde(rename = "cancelled")]+ Cancelled,++ #[serde(rename = "processing")]+ #[default]+ Processing,++ #[serde(rename = "incoming_payment_waiting")]+ IncomingPaymentWaiting,+}++#[cfg(feature = "payouts")]+fn get_payout_address_details(+ address: &Option<api_models::payments::Address>,+) -> Option<WiseAddressDetails> {+ address.as_ref().and_then(|add| {+ add.address.as_ref().map(|a| WiseAddressDetails {+ country: a.country,+ country_code: a.country,+ first_line: a.line1.clone(),+ post_code: a.zip.clone(),+ city: a.city.clone(),+ state: a.state.clone(),+ })+ })+}++#[cfg(feature = "payouts")]+fn get_payout_bank_details(+ payout_method_data: PayoutMethodData,+ address: &Option<api_models::payments::Address>,+ entity_type: PayoutEntityType,+) -> Result<WiseBankDetails, errors::ConnectorError> {+ let wise_address_details = match get_payout_address_details(address) {+ Some(a) => Ok(a),+ None => Err(errors::ConnectorError::MissingRequiredField {+ field_name: "address",+ }),+ }?;+ match payout_method_data {+ PayoutMethodData::Bank(payouts::BankPayout::Ach(b)) => Ok(WiseBankDetails {+ legal_type: LegalType::foreign_from(entity_type),+ address: wise_address_details,+ account_number: Some(b.bank_account_number.to_owned()),+ abartn: Some(b.bank_routing_number),+ account_type: Some(AccountType::Checking),+ ..WiseBankDetails::default()+ }),+ PayoutMethodData::Bank(payouts::BankPayout::Bacs(b)) => Ok(WiseBankDetails {+ legal_type: LegalType::foreign_from(entity_type),+ address: wise_address_details,+ account_number: Some(b.bank_account_number.to_owned()),+ sort_code: Some(b.bank_sort_code),+ ..WiseBankDetails::default()+ }),+ PayoutMethodData::Bank(payouts::BankPayout::Sepa(b)) => Ok(WiseBankDetails {+ legal_type: LegalType::foreign_from(entity_type),+ address: wise_address_details,+ iban: Some(b.iban.to_owned()),+ bic: b.bic,+ ..WiseBankDetails::default()+ }),+ _ => Err(errors::ConnectorError::NotSupported {+ message: "Card payout creation is not supported".to_string(),+ connector: "Wise",+ payment_experience: "".to_string(),+ }),+ }+}++// Payouts recipient create request transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<&types::PayoutsRouterData<F>> for WiseRecipientCreateRequest {+ type Error = Error;+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {+ let request = item.request.to_owned();+ let customer_details = request.customer_details;+ let payout_method_data = item.get_payout_method_data()?;+ let bank_details = get_payout_bank_details(+ payout_method_data.to_owned(),+ &item.address.billing,+ item.request.entity_type,+ )?;+ let source_id = match item.connector_auth_type.to_owned() {+ types::ConnectorAuthType::BodyKey { api_key: _, key1 } => Ok(key1),+ _ => Err(errors::ConnectorError::MissingRequiredField {+ field_name: "source_id for PayoutRecipient creation",+ }),+ }?;+ match request.payout_type.to_owned() {+ storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported {+ message: "Card payout creation is not supported".to_string(),+ connector: "Wise",+ payment_experience: "".to_string(),+ })?,+ storage_enums::PayoutType::Bank => {+ let account_holder_name = customer_details+ .ok_or(errors::ConnectorError::MissingRequiredField {+ field_name: "customer_details for PayoutRecipient creation",+ })?+ .name+ .ok_or(errors::ConnectorError::MissingRequiredField {+ field_name: "customer_details.name for PayoutRecipient creation",+ })?;+ Ok(Self {+ profile: source_id,+ currency: request.destination_currency.to_string(),+ recipient_type: RecipientType::try_from(payout_method_data)?,+ account_holder_name,+ details: bank_details,+ })+ }+ }+ }+}++// Payouts recipient fulfill response transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse>>+ for types::PayoutsRouterData<F>+{+ type Error = Error;+ fn try_from(+ item: types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse>,+ ) -> Result<Self, Self::Error> {+ let response: WiseRecipientCreateResponse = item.response;++ Ok(Self {+ response: Ok(types::PayoutsResponseData {+ status: Some(storage_enums::PayoutStatus::RequiresCreation),+ connector_payout_id: response.id.to_string(),+ payout_eligible: None,+ }),+ ..item.data+ })+ }+}++// Payouts quote request transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutQuoteRequest {+ type Error = Error;+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {+ let request = item.request.to_owned();+ match request.payout_type.to_owned() {+ storage_enums::PayoutType::Bank => Ok(Self {+ source_amount: Some(request.amount),+ source_currency: request.source_currency.to_string(),+ target_amount: None,+ target_currency: request.destination_currency.to_string(),+ pay_out: WisePayOutOption::default(),+ }),+ storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported {+ message: "Card payout fulfillment is not supported".to_string(),+ connector: "Wise",+ payment_experience: "".to_string(),+ })?,+ }+ }+}++// Payouts quote response transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>>+ for types::PayoutsRouterData<F>+{+ type Error = Error;+ fn try_from(+ item: types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>,+ ) -> Result<Self, Self::Error> {+ let response: WisePayoutQuoteResponse = item.response;++ Ok(Self {+ response: Ok(types::PayoutsResponseData {+ status: Some(storage_enums::PayoutStatus::RequiresCreation),+ connector_payout_id: response.id,+ payout_eligible: None,+ }),+ ..item.data+ })+ }+}++// Payouts transfer creation request+#[cfg(feature = "payouts")]+impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutCreateRequest {+ type Error = Error;+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {+ let request = item.request.to_owned();+ match request.payout_type.to_owned() {+ storage_enums::PayoutType::Bank => {+ let connector_customer_id = item.get_connector_customer_id()?;+ let quote_uuid = item.get_quote_id()?;+ let wise_transfer_details = WiseTransferDetails {+ transfer_purpose: None,+ source_of_funds: None,+ transfer_purpose_sub_transfer_purpose: None,+ };+ let target_account: i64 = connector_customer_id.trim().parse().map_err(|_| {+ errors::ConnectorError::MissingRequiredField {+ field_name: "profile",+ }+ })?;+ Ok(Self {+ target_account,+ quote_uuid,+ customer_transaction_id: request.payout_id,+ details: wise_transfer_details,+ })+ }+ storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported {+ message: "Card payout fulfillment is not supported".to_string(),+ connector: "Wise",+ payment_experience: "".to_string(),+ })?,+ }+ }+}++// Payouts transfer creation response+#[cfg(feature = "payouts")]+impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutResponse>>+ for types::PayoutsRouterData<F>+{+ type Error = Error;+ fn try_from(+ item: types::PayoutsResponseRouterData<F, WisePayoutResponse>,+ ) -> Result<Self, Self::Error> {+ let response: WisePayoutResponse = item.response;+ let status = match storage_enums::PayoutStatus::foreign_from(response.status) {+ storage_enums::PayoutStatus::Cancelled => storage_enums::PayoutStatus::Cancelled,+ _ => storage_enums::PayoutStatus::RequiresFulfillment,+ };++ Ok(Self {+ response: Ok(types::PayoutsResponseData {+ status: Some(status),+ connector_payout_id: response.id.to_string(),+ payout_eligible: None,+ }),+ ..item.data+ })+ }+}++// Payouts fulfill request transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutFulfillRequest {+ type Error = Error;+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {+ let request = item.request.to_owned();+ match request.payout_type.to_owned() {+ storage_enums::PayoutType::Bank => Ok(Self {+ fund_type: FundType::default(),+ }),+ storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported {+ message: "Card payout fulfillment is not supported".to_string(),+ connector: "Wise",+ payment_experience: "".to_string(),+ })?,+ }+ }+}++// Payouts fulfill response transform+#[cfg(feature = "payouts")]+impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseFulfillResponse>>+ for types::PayoutsRouterData<F>+{+ type Error = Error;+ fn try_from(+ item: types::PayoutsResponseRouterData<F, WiseFulfillResponse>,+ ) -> Result<Self, Self::Error> {+ let response: WiseFulfillResponse = item.response;++ Ok(Self {+ response: Ok(types::PayoutsResponseData {+ status: Some(storage_enums::PayoutStatus::foreign_from(response.status)),+ connector_payout_id: "".to_string(),+ payout_eligible: None,+ }),+ ..item.data+ })+ }+}++#[cfg(feature = "payouts")]+impl ForeignFrom<WiseStatus> for storage_enums::PayoutStatus {+ fn foreign_from(wise_status: WiseStatus) -> Self {+ match wise_status {+ WiseStatus::Completed => Self::Success,+ WiseStatus::Rejected => Self::Failed,+ WiseStatus::Cancelled => Self::Cancelled,+ WiseStatus::Pending | WiseStatus::Processing | WiseStatus::IncomingPaymentWaiting => {+ Self::Pending+ }+ }+ }+}++#[cfg(feature = "payouts")]+impl ForeignFrom<PayoutEntityType> for LegalType {+ fn foreign_from(entity_type: PayoutEntityType) -> Self {+ match entity_type {+ PayoutEntityType::Individual+ | PayoutEntityType::Personal+ | PayoutEntityType::NonProfit => Self::Private,+ PayoutEntityType::Company+ | PayoutEntityType::PublicSector+ | PayoutEntityType::Business => Self::Business,+ }+ }+}++#[cfg(feature = "payouts")]+impl TryFrom<PayoutMethodData> for RecipientType {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(payout_method_type: PayoutMethodData) -> Result<Self, Self::Error> {+ match payout_method_type {+ PayoutMethodData::Bank(api_models::payouts::Bank::Ach(_)) => Ok(Self::Aba),+ PayoutMethodData::Bank(api_models::payouts::Bank::Bacs(_)) => Ok(Self::SortCode),+ PayoutMethodData::Bank(api_models::payouts::Bank::Sepa(_)) => Ok(Self::Iban),+ _ => Err(errors::ConnectorError::NotSupported {+ message: "Requested payout_method_type is not supported".to_string(),+ connector: "Wise",+ payment_experience: "".to_string(),+ }+ .into()),+ }+ }+}diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex 3ade4a3346..c01bdf6fb7 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -11,6 +11,8 @@ pub mod mandate;pub mod metrics;pub mod payment_methods;pub mod payments;+#[cfg(feature = "payouts")]+pub mod payouts;pub mod refunds;pub mod utils;pub mod webhooks;diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex 1a21b95a5d..6db72e93f4 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -171,6 +171,7 @@ pub async fn create_merchant_account(modified_at: date_time::now(),frm_routing_algorithm: req.frm_routing_algorithm,intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from),+ payout_routing_algorithm: req.payout_routing_algorithm,id: None,organization_id: req.organization_id,is_recon_enabled: false,@@ -313,6 +314,7 @@ pub async fn merchant_account_update(primary_business_details,frm_routing_algorithm: req.frm_routing_algorithm,intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from),+ payout_routing_algorithm: req.payout_routing_algorithm,};let response = dbdiff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rsindex 2ab8aff3a0..d06646d5f6 100644--- a/crates/router/src/core/errors.rs+++ b/crates/router/src/core/errors.rs@@ -309,6 +309,8 @@ pub enum ConnectorError {FileValidationFailed { reason: String },#[error("Missing 3DS redirection payload: {field_name}")]MissingConnectorRedirectionPayload { field_name: &'static str },+ #[error("Failed at connector's end with code '{code}'")]+ FailedAtConnector { message: String, code: String },#[error("Payment Method Type not found")]MissingPaymentMethodType,}@@ -327,12 +329,18 @@ pub enum VaultError {PaymentMethodCreationFailed,#[error("The given payment method is currently not supported in vault")]PaymentMethodNotSupported,+ #[error("The given payout method is currently not supported in vault")]+ PayoutMethodNotSupported,#[error("Missing required field: {field_name}")]MissingRequiredField { field_name: &'static str },#[error("The card vault returned an unexpected response: {0:?}")]UnexpectedResponseError(bytes::Bytes),#[error("Failed to update in PMD table")]UpdateInPaymentMethodDataTableFailed,+ #[error("Failed to fetch payment method in vault")]+ FetchPaymentMethodFailed,+ #[error("Failed to save payment method in vault")]+ SavePaymentMethodFailed,}#[derive(Debug, thiserror::Error)]diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rsindex 7cdf2ab6c0..70f2d982b0 100644--- a/crates/router/src/core/errors/api_error_response.rs+++ b/crates/router/src/core/errors/api_error_response.rs@@ -110,6 +110,8 @@ pub enum ApiErrorResponse {PaymentCaptureFailed { data: Option<serde_json::Value> },#[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")]InvalidCardData { data: Option<serde_json::Value> },+ #[error(error_type = ErrorType::InvalidRequestError, code = "CE_04", message = "Payout validation failed")]+ PayoutFailed { data: Option<serde_json::Value> },#[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")]CardExpired { data: Option<serde_json::Value> },#[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")]@@ -133,6 +135,8 @@ pub enum ApiErrorResponse {DuplicatePaymentMethod,#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id '{payment_id}' already exists in our records")]DuplicatePayment { payment_id: String },+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id}' already exists in our records")]+ DuplicatePayout { payout_id: String },#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Refund does not exist in our records")]RefundNotFound,#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")]@@ -155,6 +159,8 @@ pub enum ApiErrorResponse {MandateUpdateFailed,#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")]ApiKeyNotFound,+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")]+ PayoutNotFound,#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")]MandateSerializationFailed,#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")]diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rsindex facc453c58..7e2afab018 100644--- a/crates/router/src/core/errors/transformers.rs+++ b/crates/router/src/core/errors/transformers.rs@@ -119,6 +119,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponSelf::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | Self::InternalServerError => {AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))}+ Self::PayoutFailed { data } => {+ AER::BadRequest(ApiError::new("CE", 4, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()})))+ },Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),@@ -129,6 +132,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponSelf::DuplicatePayment { payment_id } => {AER::BadRequest(ApiError::new("HE", 1, format!("The payment with the specified payment_id '{payment_id}' already exists in our records"), None))}+ Self::DuplicatePayout { payout_id } => {+ AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id}' already exists in our records"), None))+ }Self::RefundNotFound => {AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))}@@ -159,6 +165,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponSelf::MandateNotFound => {AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))}+ Self::PayoutNotFound => {+ AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None))+ }Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),Self::RefundNotPossible { connector } => {AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rsindex 3d03a3bc50..118b5320ad 100644--- a/crates/router/src/core/errors/utils.rs+++ b/crates/router/src/core/errors/utils.rs@@ -52,6 +52,9 @@ pub trait ConnectorErrorExt<T> {fn to_verify_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;#[track_caller]fn to_dispute_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;+ #[cfg(feature = "payouts")]+ #[track_caller]+ fn to_payout_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;}impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> {@@ -194,4 +197,37 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>err.change_context(error)})}++ #[cfg(feature = "payouts")]+ fn to_payout_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {+ self.map_err(|err| {+ let error = match err.current_context() {+ errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {+ let response_str = std::str::from_utf8(bytes);+ let data = match response_str {+ Ok(s) => serde_json::from_str(s)+ .map_err(+ |error| logger::error!(%error,"Failed to convert response to JSON"),+ )+ .ok(),+ Err(error) => {+ logger::error!(%error,"Failed to convert response to UTF8 string");+ None+ }+ };+ errors::ApiErrorResponse::PayoutFailed { data }+ }+ errors::ConnectorError::MissingRequiredField { field_name } => {+ errors::ApiErrorResponse::MissingRequiredField { field_name }+ }+ errors::ConnectorError::MissingRequiredFields { field_names } => {+ errors::ApiErrorResponse::MissingRequiredFields {+ field_names: field_names.to_vec(),+ }+ }+ _ => errors::ApiErrorResponse::InternalServerError,+ };+ err.change_context(error)+ })+ }}diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 14d699eb06..cc734362b8 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -13,13 +13,16 @@ use api_models::{},payments::BankCodeResponse,};+#[cfg(feature = "payouts")]+use common_utils::ext_traits::ByteSliceExt;use common_utils::{consts,ext_traits::{AsyncExt, StringExt, ValueExt},generate_id,};-use diesel_models::{enums as storage_enums, payment_method};-use error_stack::{IntoReport, ResultExt};+use diesel_models::{encryption::Encryption, enums as storage_enums, payment_method};+use error_stack::{report, IntoReport, ResultExt};+use masking::Secret;use router_env::{instrument, tracing};#[cfg(feature = "basilisk")]@@ -43,7 +46,7 @@ use crate::{services,types::{api::{self, PaymentMethodCreateExt},- domain::{self},+ domain::{self, types::decrypt},storage::{self, enums},transformers::ForeignInto,},@@ -253,6 +256,83 @@ pub async fn add_card_hs(customer_id: String,merchant_account: &domain::MerchantAccount,) -> errors::CustomResult<(api::PaymentMethodResponse, bool), errors::VaultError> {+ let store_card_payload =+ call_to_card_hs(state, &card, None, &customer_id, merchant_account).await?;++ let payment_method_resp = payment_methods::mk_add_card_response_hs(+ card,+ store_card_payload.card_reference,+ req,+ &merchant_account.merchant_id,+ );+ Ok((+ payment_method_resp,+ store_card_payload.duplicate.unwrap_or(false),+ ))+}++#[instrument(skip_all)]+pub async fn get_payment_method_from_hs_locker<'a>(+ state: &'a routes::AppState,+ key_store: &domain::MerchantKeyStore,+ customer_id: &str,+ merchant_id: &str,+ payment_method_reference: &'a str,+) -> errors::CustomResult<Secret<String>, errors::VaultError> {+ let locker = &state.conf.locker;+ #[cfg(not(feature = "kms"))]+ let jwekey = &state.conf.jwekey;+ #[cfg(feature = "kms")]+ let jwekey = &state.kms_secrets;++ if !locker.mock_locker {+ let request = payment_methods::mk_get_card_request_hs(+ jwekey,+ locker,+ customer_id,+ merchant_id,+ payment_method_reference,+ )+ .await+ .change_context(errors::VaultError::FetchPaymentMethodFailed)+ .attach_printable("Making get payment method request failed")?;+ let response = services::call_connector_api(state, request)+ .await+ .change_context(errors::VaultError::FetchPaymentMethodFailed)+ .attach_printable("Failed while executing call_connector_api for get_card");+ let jwe_body: services::JweBody = response+ .get_response_inner("JweBody")+ .change_context(errors::VaultError::FetchPaymentMethodFailed)?;+ let decrypted_payload = payment_methods::get_decrypted_response_payload(jwekey, jwe_body)+ .await+ .change_context(errors::VaultError::FetchPaymentMethodFailed)+ .attach_printable("Error getting decrypted response payload for get card")?;+ let get_card_resp: payment_methods::RetrieveCardResp = decrypted_payload+ .parse_struct("RetrieveCardResp")+ .change_context(errors::VaultError::FetchPaymentMethodFailed)?;+ let retrieve_card_resp = get_card_resp+ .payload+ .get_required_value("RetrieveCardRespPayload")+ .change_context(errors::VaultError::FetchPaymentMethodFailed)?;+ retrieve_card_resp+ .enc_card_data+ .get_required_value("enc_card_data")+ .change_context(errors::VaultError::FetchPaymentMethodFailed)+ } else {+ let get_card_resp =+ mock_get_payment_method(&*state.store, key_store, payment_method_reference).await?;+ Ok(get_card_resp.payment_method.payment_method_data)+ }+}++#[instrument(skip_all)]+pub async fn call_to_card_hs(+ state: &routes::AppState,+ card: &api::CardDetail,+ enc_value: Option<&str>,+ customer_id: &str,+ merchant_account: &domain::MerchantAccount,+) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> {let locker = &state.conf.locker;#[cfg(not(feature = "kms"))]let jwekey = &state.conf.jwekey;@@ -266,8 +346,9 @@ pub async fn add_card_hs(let request = payment_methods::mk_add_card_request_hs(jwekey,locker,- &card,- &customer_id,+ card,+ enc_value,+ customer_id,merchant_id,).await?;@@ -289,24 +370,14 @@ pub async fn add_card_hs(stored_card_resp} else {let card_id = generate_id(consts::ID_LENGTH, "card");- mock_add_card_hs(db, &card_id, &card, None, None, Some(&customer_id)).await?+ mock_add_card_hs(db, &card_id, card, None, enc_value, None, Some(customer_id)).await?};- let store_card_payload = stored_card_response+ let stored_card = stored_card_response.payload.get_required_value("StoreCardRespPayload").change_context(errors::VaultError::SaveCardFailed)?;-- let payment_method_resp = payment_methods::mk_add_card_response_hs(- card,- store_card_payload.card_reference,- req,- merchant_id,- );- Ok((- payment_method_resp,- store_card_payload.duplicate.unwrap_or(false),- ))+ Ok(stored_card)}pub async fn update_payment_method(@@ -429,6 +500,7 @@ pub async fn mock_add_card_hs(card_id: &str,card: &api::CardDetail,card_cvc: Option<String>,+ enc_val: Option<&str>,payment_method_id: Option<String>,customer_id: Option<&str>,) -> errors::CustomResult<payment_methods::StoreCardResp, errors::VaultError> {@@ -446,6 +518,7 @@ pub async fn mock_add_card_hs(customer_id: customer_id.map(str::to_string),name_on_card: card.card_holder_name.to_owned().expose_option(),nickname: card.nick_name.to_owned().map(masking::Secret::expose),+ enc_card_data: enc_val.map(|e| e.to_string()),};let response = db@@ -503,6 +576,51 @@ pub async fn mock_get_card<'a>())}+#[instrument(skip_all)]+pub async fn mock_get_payment_method<'a>(+ db: &dyn db::StorageInterface,+ key_store: &domain::MerchantKeyStore,+ card_id: &'a str,+) -> errors::CustomResult<payment_methods::GetPaymentMethodResponse, errors::VaultError> {+ let locker_mock_up = db+ .find_locker_by_card_id(card_id)+ .await+ .change_context(errors::VaultError::FetchPaymentMethodFailed)?;+ let dec_data = if let Some(e) = locker_mock_up.enc_card_data {+ // Fetch key+ let key = key_store.key.get_inner().peek();+ // Decode+ let decoded_bytes = hex::decode(e)+ .into_report()+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Failed to decode hex string into bytes")?;+ // Decrypt+ async { decrypt(Some(Encryption::new(decoded_bytes.into())), key).await }+ .await+ .change_context(errors::VaultError::FetchPaymentMethodFailed)?+ .map_or(+ Err(report!(errors::VaultError::FetchPaymentMethodFailed)),+ |d| Ok(d.into_inner()),+ )+ } else {+ Err(report!(errors::VaultError::FetchPaymentMethodFailed))+ }?;+ let payment_method_response = payment_methods::AddPaymentMethodResponse {+ payment_method_id: locker_mock_up+ .payment_method_id+ .unwrap_or(locker_mock_up.card_id),+ external_id: locker_mock_up.external_id,+ merchant_id: Some(locker_mock_up.merchant_id),+ nickname: locker_mock_up.nickname,+ customer_id: locker_mock_up.customer_id,+ duplicate: locker_mock_up.duplicate,+ payment_method_data: dec_data,+ };+ Ok(payment_methods::GetPaymentMethodResponse {+ payment_method: payment_method_response,+ })+}+#[instrument(skip_all)]pub async fn mock_delete_card_hs<'a>(db: &dyn db::StorageInterface,@@ -1565,6 +1683,15 @@ pub async fn list_customer_payment_method(} else {None};+ #[cfg(feature = "payouts")]+ let pmd = if pm.payment_method == enums::PaymentMethod::BankTransfer {+ Some(+ get_lookup_key_for_payout_method(state, &key_store, &hyperswitch_token, &pm)+ .await?,+ )+ } else {+ None+ };//Need validation for enabled payment method ,querying MCAlet pma = api::CustomerPaymentMethod {payment_token: parent_payment_method_token.to_owned(),@@ -1579,6 +1706,10 @@ pub async fn list_customer_payment_method(installment_payment_enabled: false,payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),created: Some(pm.created_at),+ #[cfg(feature = "payouts")]+ bank_transfer: pmd,+ #[cfg(not(feature = "payouts"))]+ bank_transfer: None,};customer_pms.push(pma.to_owned());@@ -1671,6 +1802,49 @@ pub async fn get_lookup_key_from_locker(Ok(resp)}+#[cfg(feature = "payouts")]+pub async fn get_lookup_key_for_payout_method(+ state: &routes::AppState,+ key_store: &domain::MerchantKeyStore,+ payout_token: &str,+ pm: &storage::PaymentMethod,+) -> errors::RouterResult<api::BankPayout> {+ let payment_method = get_payment_method_from_hs_locker(+ state,+ key_store,+ &pm.customer_id,+ &pm.merchant_id,+ &pm.payment_method_id,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error getting payment method from locker")?;+ let pm_parsed: api::PayoutMethodData = payment_method+ .peek()+ .as_bytes()+ .to_vec()+ .parse_struct("PayoutMethodData")+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ match &pm_parsed {+ api::PayoutMethodData::Bank(bank) => {+ vault::Vault::store_payout_method_data_in_locker(+ state,+ Some(payout_token.to_string()),+ &pm_parsed,+ Some(pm.customer_id.to_owned()),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error storing payout method data in temporary locker")?;+ Ok(bank.to_owned())+ }+ api::PayoutMethodData::Card(_) => Err(errors::ApiErrorResponse::InvalidRequestData {+ message: "Expected bank details, found card details instead".to_string(),+ }+ .into()),+ }+}+pub struct BasiliskCardSupport;#[cfg(not(feature = "basilisk"))]diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex b5ee91131a..f5a7babf2a 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -20,6 +20,7 @@ pub struct StoreCardReq<'a> {pub merchant_id: &'a str,pub merchant_customer_id: String,pub card: Card,+ pub enc_card_data: Option<String>,}#[derive(Debug, Deserialize, Serialize)]@@ -65,7 +66,7 @@ pub struct RetrieveCardResp {#[derive(Debug, Deserialize, Serialize)]pub struct RetrieveCardRespPayload {pub card: Option<Card>,- pub enc_card_data: Option<String>,+ pub enc_card_data: Option<Secret<String>>,}#[derive(Debug, Deserialize, Serialize)]@@ -106,6 +107,24 @@ pub struct AddCardResponse {pub duplicate: Option<bool>,}+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct AddPaymentMethodResponse {+ pub payment_method_id: String,+ pub external_id: String,+ #[serde(rename = "merchant_id")]+ pub merchant_id: Option<String>,+ pub nickname: Option<String>,+ pub customer_id: Option<String>,+ pub duplicate: Option<bool>,+ pub payment_method_data: Secret<String>,+}++#[derive(Debug, Deserialize, Serialize)]+pub struct GetPaymentMethodResponse {+ pub payment_method: AddPaymentMethodResponse,+}+#[derive(Debug, Deserialize, Serialize)]pub struct GetCardResponse {pub card: AddCardResponse,@@ -238,6 +257,7 @@ pub async fn mk_add_card_request_hs(#[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets,locker: &settings::Locker,card: &api::CardDetail,+ enc_value: Option<&str>,customer_id: &str,merchant_id: &str,) -> CustomResult<services::Request, errors::VaultError> {@@ -255,6 +275,7 @@ pub async fn mk_add_card_request_hs(merchant_id,merchant_customer_id,card,+ enc_card_data: enc_value.map(|e| e.to_string()),};let payload = utils::Encode::<StoreCardReq<'_>>::encode_to_vec(&store_card_req).change_context(errors::VaultError::RequestEncodingFailed)?;diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 27500aaeb9..c93d83e0bb 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -9,12 +9,14 @@ use router_env::{instrument, tracing};#[cfg(feature = "basilisk")]use crate::routes::metrics;+#[cfg(feature = "payouts")]+use crate::types::api::payouts;use crate::{configs::settings,core::errors::{self, CustomResult, RouterResult},logger, routes,types::{- api,+ api::{self},storage::{self, enums},},utils::{self, StringExt},@@ -290,6 +292,269 @@ impl Vaultable for api::PaymentMethodData {}}+#[cfg(feature = "payouts")]+impl Vaultable for api::CardPayout {+ fn get_value1(&self, _customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {+ let value1 = api::TokenizedCardValue1 {+ card_number: self.card_number.peek().clone(),+ exp_year: self.expiry_year.peek().clone(),+ exp_month: self.expiry_month.peek().clone(),+ name_on_card: Some(self.card_holder_name.peek().clone()),+ nickname: None,+ card_last_four: None,+ card_token: None,+ };++ utils::Encode::<api::TokenizedCardValue1>::encode_to_string_of_json(&value1)+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode card value1")+ }++ fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {+ let value2 = api::TokenizedCardValue2 {+ card_security_code: None,+ card_fingerprint: None,+ external_id: None,+ customer_id,+ payment_method_id: None,+ };++ utils::Encode::<api::TokenizedCardValue2>::encode_to_string_of_json(&value2)+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode card value2")+ }++ fn from_values(+ value1: String,+ value2: String,+ ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {+ let value1: api::TokenizedCardValue1 = value1+ .parse_struct("TokenizedCardValue1")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Could not deserialize into card value1")?;++ let value2: api::TokenizedCardValue2 = value2+ .parse_struct("TokenizedCardValue2")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Could not deserialize into card value2")?;++ let card = Self {+ card_number: value1+ .card_number+ .parse()+ .map_err(|_| errors::VaultError::FetchCardFailed)?,+ expiry_month: value1.exp_month.into(),+ expiry_year: value1.exp_year.into(),+ card_holder_name: value1.name_on_card.unwrap_or_default().into(),+ };++ let supp_data = SupplementaryVaultData {+ customer_id: value2.customer_id,+ payment_method_id: value2.payment_method_id,+ };++ Ok((card, supp_data))+ }+}++#[derive(Debug, serde::Serialize, serde::Deserialize)]+pub struct TokenizedBankSensitiveValues {+ pub bank_account_number: Option<masking::Secret<String>>,+ pub bank_routing_number: Option<masking::Secret<String>>,+ pub bic: Option<masking::Secret<String>>,+ pub bank_sort_code: Option<masking::Secret<String>>,+ pub iban: Option<masking::Secret<String>>,+}++#[derive(Debug, serde::Serialize, serde::Deserialize)]+pub struct TokenizedBankInsensitiveValues {+ pub customer_id: Option<String>,+ pub bank_name: String,+ pub bank_country_code: api::enums::CountryAlpha2,+ pub bank_city: String,+}++#[cfg(feature = "payouts")]+impl Vaultable for api::BankPayout {+ fn get_value1(&self, _customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {+ let bank_sensitive_data = match self {+ Self::Ach(b) => TokenizedBankSensitiveValues {+ bank_account_number: Some(b.bank_account_number.clone()),+ bank_routing_number: Some(b.bank_routing_number.to_owned()),+ bic: None,+ bank_sort_code: None,+ iban: None,+ },+ Self::Bacs(b) => TokenizedBankSensitiveValues {+ bank_account_number: Some(b.bank_account_number.to_owned()),+ bank_routing_number: None,+ bic: None,+ bank_sort_code: Some(b.bank_sort_code.to_owned()),+ iban: None,+ },+ Self::Sepa(b) => TokenizedBankSensitiveValues {+ bank_account_number: None,+ bank_routing_number: None,+ bic: b.bic.to_owned(),+ bank_sort_code: None,+ iban: Some(b.iban.to_owned()),+ },+ };++ utils::Encode::<TokenizedBankSensitiveValues>::encode_to_string_of_json(+ &bank_sensitive_data,+ )+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode wallet data bank_sensitive_data")+ }++ fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {+ let bank_insensitive_data = match self {+ Self::Ach(b) => TokenizedBankInsensitiveValues {+ customer_id,+ bank_name: b.bank_name.to_owned(),+ bank_country_code: b.bank_country_code.to_owned(),+ bank_city: b.bank_city.to_owned(),+ },+ Self::Bacs(b) => TokenizedBankInsensitiveValues {+ customer_id,+ bank_name: b.bank_name.to_owned(),+ bank_country_code: b.bank_country_code.to_owned(),+ bank_city: b.bank_city.to_owned(),+ },+ Self::Sepa(b) => TokenizedBankInsensitiveValues {+ customer_id,+ bank_name: b.bank_name.to_owned(),+ bank_country_code: b.bank_country_code.to_owned(),+ bank_city: b.bank_city.to_owned(),+ },+ };++ utils::Encode::<TokenizedBankInsensitiveValues>::encode_to_string_of_json(+ &bank_insensitive_data,+ )+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode wallet data bank_insensitive_data")+ }++ fn from_values(+ bank_sensitive_data: String,+ bank_insensitive_data: String,+ ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {+ let bank_sensitive_data: TokenizedBankSensitiveValues = bank_sensitive_data+ .parse_struct("TokenizedBankValue1")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Could not deserialize into bank data bank_sensitive_data")?;++ let bank_insensitive_data: TokenizedBankInsensitiveValues = bank_insensitive_data+ .parse_struct("TokenizedBankValue2")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Could not deserialize into wallet data bank_insensitive_data")?;++ let bank = match (+ // ACH + BACS+ bank_sensitive_data.bank_account_number.to_owned(),+ bank_sensitive_data.bank_routing_number.to_owned(), // ACH+ bank_sensitive_data.bank_sort_code.to_owned(), // BACS+ // SEPA+ bank_sensitive_data.iban.to_owned(),+ bank_sensitive_data.bic,+ ) {+ (Some(ban), Some(brn), None, None, None) => Self::Ach(payouts::AchBankTransfer {+ bank_account_number: ban,+ bank_routing_number: brn,+ bank_name: bank_insensitive_data.bank_name,+ bank_country_code: bank_insensitive_data.bank_country_code,+ bank_city: bank_insensitive_data.bank_city,+ }),+ (Some(ban), None, Some(bsc), None, None) => Self::Bacs(payouts::BacsBankTransfer {+ bank_account_number: ban,+ bank_sort_code: bsc,+ bank_name: bank_insensitive_data.bank_name,+ bank_country_code: bank_insensitive_data.bank_country_code,+ bank_city: bank_insensitive_data.bank_city,+ }),+ (None, None, None, Some(iban), bic) => Self::Sepa(payouts::SepaBankTransfer {+ iban,+ bic,+ bank_name: bank_insensitive_data.bank_name,+ bank_country_code: bank_insensitive_data.bank_country_code,+ bank_city: bank_insensitive_data.bank_city,+ }),+ _ => Err(errors::VaultError::ResponseDeserializationFailed)?,+ };++ let supp_data = SupplementaryVaultData {+ customer_id: bank_insensitive_data.customer_id,+ payment_method_id: None,+ };++ Ok((bank, supp_data))+ }+}++#[cfg(feature = "payouts")]+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+#[serde(tag = "type", content = "value", rename_all = "snake_case")]+pub enum VaultPayoutMethod {+ Card(String),+ Bank(String),+}++#[cfg(feature = "payouts")]+impl Vaultable for api::PayoutMethodData {+ fn get_value1(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {+ let value1 = match self {+ Self::Card(card) => VaultPayoutMethod::Card(card.get_value1(customer_id)?),+ Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value1(customer_id)?),+ };++ utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value1)+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode payout method value1")+ }++ fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {+ let value2 = match self {+ Self::Card(card) => VaultPayoutMethod::Card(card.get_value2(customer_id)?),+ Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value2(customer_id)?),+ };++ utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value2)+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode payout method value2")+ }++ fn from_values(+ value1: String,+ value2: String,+ ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {+ let value1: VaultPayoutMethod = value1+ .parse_struct("VaultMethodValue1")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Could not deserialize into vault method value 1")?;++ let value2: VaultPayoutMethod = value2+ .parse_struct("VaultMethodValue2")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Could not deserialize into vault method value 2")?;++ match (value1, value2) {+ (VaultPayoutMethod::Card(mvalue1), VaultPayoutMethod::Card(mvalue2)) => {+ let (card, supp_data) = api::CardPayout::from_values(mvalue1, mvalue2)?;+ Ok((Self::Card(card), supp_data))+ }+ (VaultPayoutMethod::Bank(mvalue1), VaultPayoutMethod::Bank(mvalue2)) => {+ let (bank, supp_data) = api::BankPayout::from_values(mvalue1, mvalue2)?;+ Ok((Self::Bank(bank), supp_data))+ }+ _ => Err(errors::VaultError::PayoutMethodNotSupported)+ .into_report()+ .attach_printable("Payout method not supported"),+ }+ }+}+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct MockTokenizeDBValue {pub value1: String,@@ -326,6 +591,89 @@ impl Vault {Ok((Some(payment_method), supp_data))}+ #[cfg(feature = "payouts")]+ #[instrument(skip_all)]+ pub async fn get_payout_method_data_from_temporary_locker(+ state: &routes::AppState,+ lookup_key: &str,+ ) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> {+ let config = state+ .store+ .find_config_by_key(lookup_key)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Could not find payment method in vault")?;++ let tokenize_value: MockTokenizeDBValue = config+ .config+ .parse_struct("MockTokenizeDBValue")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to deserialize Mock tokenize db value")?;++ let (payout_method, supp_data) =+ api::PayoutMethodData::from_values(tokenize_value.value1, tokenize_value.value2)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error parsing Payout Method from Values")?;++ Ok((Some(payout_method), supp_data))+ }++ #[cfg(feature = "payouts")]+ #[instrument(skip_all)]+ pub async fn store_payout_method_data_in_locker(+ state: &routes::AppState,+ token_id: Option<String>,+ payout_method: &api::PayoutMethodData,+ customer_id: Option<String>,+ ) -> RouterResult<String> {+ let value1 = payout_method+ .get_value1(customer_id.clone())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error getting Value1 for locker")?;++ let value2 = payout_method+ .get_value2(customer_id)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error getting Value2 for locker")?;++ let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));++ let db_value = MockTokenizeDBValue { value1, value2 };++ let value_string =+ utils::Encode::<MockTokenizeDBValue>::encode_to_string_of_json(&db_value)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encode payout method as mock tokenize db value")?;++ let already_present = state.store.find_config_by_key(&lookup_key).await;++ if already_present.is_err() {+ let config = storage::ConfigNew {+ key: lookup_key.clone(),+ config: value_string,+ };++ state+ .store+ .insert_config(config)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Mock tokenization save to db failed insert")?;+ } else {+ let config_update = storage::ConfigUpdate::Update {+ config: Some(value_string),+ };+ state+ .store+ .update_config_by_key(&lookup_key, config_update)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Mock tokenization save to db failed update")?;+ }++ Ok(lookup_key)+ }+#[instrument(skip_all)]pub async fn store_payment_method_data_in_locker(state: &routes::AppState,@@ -439,6 +787,47 @@ impl Vault {Ok(lookup_key)}+ #[cfg(feature = "payouts")]+ #[instrument(skip_all)]+ pub async fn get_payout_method_data_from_temporary_locker(+ state: &routes::AppState,+ lookup_key: &str,+ ) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> {+ let de_tokenize = get_tokenized_data(state, lookup_key, true).await?;+ let (payout_method, supp_data) =+ api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error parsing Payout Method from Values")?;++ Ok((Some(payout_method), supp_data))+ }++ #[cfg(feature = "payouts")]+ #[instrument(skip_all)]+ pub async fn store_payout_method_data_in_locker(+ state: &routes::AppState,+ token_id: Option<String>,+ payout_method: &api::PayoutMethodData,+ customer_id: Option<String>,+ ) -> RouterResult<String> {+ let value1 = payout_method+ .get_value1(customer_id.clone())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error getting Value1 for locker")?;++ let value2 = payout_method+ .get_value2(customer_id)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error getting Value2 for locker")?;++ let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));++ let lookup_key = create_tokenize(state, value1, Some(value2), lookup_key).await?;+ // add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;+ // scheduler_metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);+ Ok(lookup_key)+ }+#[instrument(skip_all)]pub async fn delete_locker_payment_method_by_lookup_key(state: &routes::AppState,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 24c6ac5340..5ca40b3985 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -1099,7 +1099,7 @@ pub struct RecurringMandatePaymentData {pub payment_method_type: Option<storage_enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe}-#[derive(Debug, Default)]+#[derive(Debug, Default, Clone)]pub struct CustomerDetails {pub customer_id: Option<String>,pub name: Option<Secret<String, masking::WithType>>,diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rsindex 022c4d4801..c3347f84e7 100644--- a/crates/router/src/core/payments/flows.rs+++ b/crates/router/src/core/payments/flows.rs@@ -109,8 +109,8 @@ pub trait Feature<F, T> {}}-macro_rules! default_imp_for_complete_authorize{- ($($path:ident::$connector:ident),*)=> {+macro_rules! default_imp_for_complete_authorize {+ ($($path:ident::$connector:ident),*) => {$(impl api::PaymentsCompleteAuthorize for $path::$connector {}impl@@ -166,13 +166,14 @@ default_imp_for_complete_authorize!(connector::Stripe,connector::Trustpay,connector::Tsys,+ connector::Wise,connector::Worldline,connector::Worldpay,connector::Zen);-macro_rules! default_imp_for_create_customer{- ($($path:ident::$connector:ident),*)=> {+macro_rules! default_imp_for_create_customer {+ ($($path:ident::$connector:ident),*) => {$(impl api::ConnectorCustomer for $path::$connector {}impl@@ -236,13 +237,14 @@ default_imp_for_create_customer!(connector::Shift4,connector::Trustpay,connector::Tsys,+ connector::Wise,connector::Worldline,connector::Worldpay,connector::Zen);-macro_rules! default_imp_for_connector_redirect_response{- ($($path:ident::$connector:ident),*)=> {+macro_rules! default_imp_for_connector_redirect_response {+ ($($path:ident::$connector:ident),*) => {$(impl services::ConnectorRedirectResponse for $path::$connector {fn get_flow_type(@@ -298,12 +300,13 @@ default_imp_for_connector_redirect_response!(connector::Rapyd,connector::Shift4,connector::Tsys,+ connector::Wise,connector::Worldline,connector::Worldpay);-macro_rules! default_imp_for_connector_request_id{- ($($path:ident::$connector:ident),*)=> {+macro_rules! default_imp_for_connector_request_id {+ ($($path:ident::$connector:ident),*) => {$(impl api::ConnectorTransactionId for $path::$connector {})*@@ -351,13 +354,14 @@ default_imp_for_connector_request_id!(connector::Stripe,connector::Trustpay,connector::Tsys,+ connector::Wise,connector::Worldline,connector::Worldpay,connector::Zen);-macro_rules! default_imp_for_accept_dispute{- ($($path:ident::$connector:ident),*)=> {+macro_rules! default_imp_for_accept_dispute {+ ($($path:ident::$connector:ident),*) => {$(impl api::Dispute for $path::$connector {}impl api::AcceptDispute for $path::$connector {}@@ -425,13 +429,14 @@ default_imp_for_accept_dispute!(connector::Trustpay,connector::Tsys,connector::Opennode,+ connector::Wise,connector::Worldline,connector::Worldpay,connector::Zen);-macro_rules! default_imp_for_file_upload{- ($($path:ident::$connector:ident),*)=> {+macro_rules! default_imp_for_file_upload {+ ($($path:ident::$connector:ident),*) => {$(impl api::FileUpload for $path::$connector {}impl api::UploadFile for $path::$connector {}@@ -517,13 +522,14 @@ default_imp_for_file_upload!(connector::Trustpay,connector::Tsys,connector::Opennode,+ connector::Wise,connector::Worldline,connector::Worldpay,connector::Zen);-macro_rules! default_imp_for_submit_evidence{- ($($path:ident::$connector:ident),*)=> {+macro_rules! default_imp_for_submit_evidence {+ ($($path:ident::$connector:ident),*) => {$(impl api::SubmitEvidence for $path::$connector {}impl@@ -587,13 +593,14 @@ default_imp_for_submit_evidence!(connector::Trustpay,connector::Tsys,connector::Opennode,+ connector::Wise,connector::Worldline,connector::Worldpay,connector::Zen);-macro_rules! default_imp_for_defend_dispute{- ($($path:ident::$connector:ident),*)=> {+macro_rules! default_imp_for_defend_dispute {+ ($($path:ident::$connector:ident),*) => {$(impl api::DefendDispute for $path::$connector {}impl@@ -603,7 +610,7 @@ macro_rules! default_imp_for_defend_dispute{types::DefendDisputeResponse,> for $path::$connector{}- )*+ )*};}@@ -658,6 +665,7 @@ default_imp_for_defend_dispute!(connector::Trustpay,connector::Tsys,connector::Opennode,+ connector::Wise,connector::Worldline,connector::Worldpay,connector::Zen@@ -728,6 +736,499 @@ default_imp_for_pre_processing_steps!(connector::Rapyd,connector::Shift4,connector::Tsys,+ connector::Wise,+ connector::Worldline,+ connector::Worldpay,+ connector::Zen+);++macro_rules! default_imp_for_payouts {+ ($($path:ident::$connector:ident),*) => {+ $(+ impl api::Payouts for $path::$connector {}+ )*+ };+}++#[cfg(feature = "dummy_connector")]+impl<const T: u8> api::Payouts for connector::DummyConnector<T> {}++default_imp_for_payouts!(+ connector::Aci,+ connector::Airwallex,+ connector::Authorizedotnet,+ connector::Bambora,+ connector::Bitpay,+ connector::Bluesnap,+ connector::Braintree,+ connector::Cashtocode,+ connector::Checkout,+ connector::Cryptopay,+ connector::Cybersource,+ connector::Coinbase,+ connector::Dlocal,+ connector::Fiserv,+ connector::Forte,+ connector::Globalpay,+ connector::Globepay,+ connector::Iatapay,+ connector::Klarna,+ connector::Mollie,+ connector::Multisafepay,+ connector::Nexinets,+ connector::Nmi,+ connector::Noon,+ connector::Nuvei,+ connector::Opayo,+ connector::Opennode,+ connector::Payeezy,+ connector::Payme,+ connector::Paypal,+ connector::Payu,+ connector::Powertranz,+ connector::Rapyd,+ connector::Stax,+ connector::Stripe,+ connector::Shift4,+ connector::Trustpay,+ connector::Tsys,+ connector::Worldline,+ connector::Worldpay,+ connector::Zen+);++#[cfg(feature = "payouts")]+macro_rules! default_imp_for_payouts_create {+ ($($path:ident::$connector:ident),*) => {+ $(+ impl api::PayoutCreate for $path::$connector {}+ impl+ services::ConnectorIntegration<+ api::PoCreate,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for $path::$connector+ {}+ )*+ };+}++#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8> api::PayoutCreate for connector::DummyConnector<T> {}+#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData>+ for connector::DummyConnector<T>+{+}++#[cfg(feature = "payouts")]+default_imp_for_payouts_create!(+ connector::Aci,+ connector::Airwallex,+ connector::Authorizedotnet,+ connector::Bambora,+ connector::Bitpay,+ connector::Bluesnap,+ connector::Braintree,+ connector::Cashtocode,+ connector::Checkout,+ connector::Cryptopay,+ connector::Cybersource,+ connector::Coinbase,+ connector::Dlocal,+ connector::Fiserv,+ connector::Forte,+ connector::Globalpay,+ connector::Globepay,+ connector::Iatapay,+ connector::Klarna,+ connector::Mollie,+ connector::Multisafepay,+ connector::Nexinets,+ connector::Nmi,+ connector::Noon,+ connector::Nuvei,+ connector::Opayo,+ connector::Opennode,+ connector::Payeezy,+ connector::Payme,+ connector::Paypal,+ connector::Payu,+ connector::Powertranz,+ connector::Rapyd,+ connector::Stax,+ connector::Stripe,+ connector::Shift4,+ connector::Trustpay,+ connector::Tsys,+ connector::Worldline,+ connector::Worldpay,+ connector::Zen+);++#[cfg(feature = "payouts")]+macro_rules! default_imp_for_payouts_eligibility {+ ($($path:ident::$connector:ident),*) => {+ $(+ impl api::PayoutEligibility for $path::$connector {}+ impl+ services::ConnectorIntegration<+ api::PoEligibility,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for $path::$connector+ {}+ )*+ };+}++#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8> api::PayoutEligibility for connector::DummyConnector<T> {}+#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ services::ConnectorIntegration<+ api::PoEligibility,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for connector::DummyConnector<T>+{+}++#[cfg(feature = "payouts")]+default_imp_for_payouts_eligibility!(+ connector::Aci,+ connector::Airwallex,+ connector::Authorizedotnet,+ connector::Bambora,+ connector::Bitpay,+ connector::Bluesnap,+ connector::Braintree,+ connector::Cashtocode,+ connector::Checkout,+ connector::Cryptopay,+ connector::Cybersource,+ connector::Coinbase,+ connector::Dlocal,+ connector::Fiserv,+ connector::Forte,+ connector::Globalpay,+ connector::Globepay,+ connector::Iatapay,+ connector::Klarna,+ connector::Mollie,+ connector::Multisafepay,+ connector::Nexinets,+ connector::Nmi,+ connector::Noon,+ connector::Nuvei,+ connector::Opayo,+ connector::Opennode,+ connector::Payeezy,+ connector::Payme,+ connector::Paypal,+ connector::Payu,+ connector::Powertranz,+ connector::Rapyd,+ connector::Stax,+ connector::Stripe,+ connector::Shift4,+ connector::Trustpay,+ connector::Tsys,+ connector::Worldline,+ connector::Worldpay,+ connector::Zen+);++#[cfg(feature = "payouts")]+macro_rules! default_imp_for_payouts_fulfill {+ ($($path:ident::$connector:ident),*) => {+ $(+ impl api::PayoutFulfill for $path::$connector {}+ impl+ services::ConnectorIntegration<+ api::PoFulfill,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for $path::$connector+ {}+ )*+ };+}++#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8> api::PayoutFulfill for connector::DummyConnector<T> {}+#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData>+ for connector::DummyConnector<T>+{+}++#[cfg(feature = "payouts")]+default_imp_for_payouts_fulfill!(+ connector::Aci,+ connector::Airwallex,+ connector::Authorizedotnet,+ connector::Bambora,+ connector::Bitpay,+ connector::Bluesnap,+ connector::Braintree,+ connector::Cashtocode,+ connector::Checkout,+ connector::Cryptopay,+ connector::Cybersource,+ connector::Coinbase,+ connector::Dlocal,+ connector::Fiserv,+ connector::Forte,+ connector::Globalpay,+ connector::Globepay,+ connector::Iatapay,+ connector::Klarna,+ connector::Mollie,+ connector::Multisafepay,+ connector::Nexinets,+ connector::Nmi,+ connector::Noon,+ connector::Nuvei,+ connector::Opayo,+ connector::Opennode,+ connector::Payeezy,+ connector::Payme,+ connector::Paypal,+ connector::Payu,+ connector::Powertranz,+ connector::Rapyd,+ connector::Stax,+ connector::Stripe,+ connector::Shift4,+ connector::Trustpay,+ connector::Tsys,+ connector::Worldline,+ connector::Worldpay,+ connector::Zen+);++#[cfg(feature = "payouts")]+macro_rules! default_imp_for_payouts_cancel {+ ($($path:ident::$connector:ident),*) => {+ $(+ impl api::PayoutCancel for $path::$connector {}+ impl+ services::ConnectorIntegration<+ api::PoCancel,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for $path::$connector+ {}+ )*+ };+}++#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8> api::PayoutCancel for connector::DummyConnector<T> {}+#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData>+ for connector::DummyConnector<T>+{+}++#[cfg(feature = "payouts")]+default_imp_for_payouts_cancel!(+ connector::Aci,+ connector::Airwallex,+ connector::Authorizedotnet,+ connector::Bambora,+ connector::Bitpay,+ connector::Bluesnap,+ connector::Braintree,+ connector::Cashtocode,+ connector::Checkout,+ connector::Cryptopay,+ connector::Cybersource,+ connector::Coinbase,+ connector::Dlocal,+ connector::Fiserv,+ connector::Forte,+ connector::Globalpay,+ connector::Globepay,+ connector::Iatapay,+ connector::Klarna,+ connector::Mollie,+ connector::Multisafepay,+ connector::Nexinets,+ connector::Nmi,+ connector::Noon,+ connector::Nuvei,+ connector::Opayo,+ connector::Opennode,+ connector::Payeezy,+ connector::Payme,+ connector::Paypal,+ connector::Payu,+ connector::Powertranz,+ connector::Rapyd,+ connector::Stax,+ connector::Stripe,+ connector::Shift4,+ connector::Trustpay,+ connector::Tsys,+ connector::Worldline,+ connector::Worldpay,+ connector::Zen+);++#[cfg(feature = "payouts")]+macro_rules! default_imp_for_payouts_quote {+ ($($path:ident::$connector:ident),*) => {+ $(+ impl api::PayoutQuote for $path::$connector {}+ impl+ services::ConnectorIntegration<+ api::PoQuote,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for $path::$connector+ {}+ )*+ };+}++#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8> api::PayoutQuote for connector::DummyConnector<T> {}+#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData>+ for connector::DummyConnector<T>+{+}++#[cfg(feature = "payouts")]+default_imp_for_payouts_quote!(+ connector::Aci,+ connector::Adyen,+ connector::Airwallex,+ connector::Authorizedotnet,+ connector::Bambora,+ connector::Bitpay,+ connector::Bluesnap,+ connector::Braintree,+ connector::Cashtocode,+ connector::Checkout,+ connector::Cryptopay,+ connector::Cybersource,+ connector::Coinbase,+ connector::Dlocal,+ connector::Fiserv,+ connector::Forte,+ connector::Globalpay,+ connector::Globepay,+ connector::Iatapay,+ connector::Klarna,+ connector::Mollie,+ connector::Multisafepay,+ connector::Nexinets,+ connector::Nmi,+ connector::Noon,+ connector::Nuvei,+ connector::Opayo,+ connector::Opennode,+ connector::Payeezy,+ connector::Payme,+ connector::Paypal,+ connector::Payu,+ connector::Powertranz,+ connector::Rapyd,+ connector::Stax,+ connector::Stripe,+ connector::Shift4,+ connector::Trustpay,+ connector::Tsys,+ connector::Worldline,+ connector::Worldpay,+ connector::Zen+);++#[cfg(feature = "payouts")]+macro_rules! default_imp_for_payouts_recipient {+ ($($path:ident::$connector:ident),*) => {+ $(+ impl api::PayoutRecipient for $path::$connector {}+ impl+ services::ConnectorIntegration<+ api::PoRecipient,+ types::PayoutsData,+ types::PayoutsResponseData,+ > for $path::$connector+ {}+ )*+ };+}++#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8> api::PayoutRecipient for connector::DummyConnector<T> {}+#[cfg(feature = "payouts")]+#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData>+ for connector::DummyConnector<T>+{+}++#[cfg(feature = "payouts")]+default_imp_for_payouts_recipient!(+ connector::Aci,+ connector::Adyen,+ connector::Airwallex,+ connector::Authorizedotnet,+ connector::Bambora,+ connector::Bitpay,+ connector::Bluesnap,+ connector::Braintree,+ connector::Cashtocode,+ connector::Checkout,+ connector::Cryptopay,+ connector::Cybersource,+ connector::Coinbase,+ connector::Dlocal,+ connector::Fiserv,+ connector::Forte,+ connector::Globalpay,+ connector::Globepay,+ connector::Iatapay,+ connector::Klarna,+ connector::Mollie,+ connector::Multisafepay,+ connector::Nexinets,+ connector::Nmi,+ connector::Noon,+ connector::Nuvei,+ connector::Opayo,+ connector::Opennode,+ connector::Payeezy,+ connector::Payme,+ connector::Paypal,+ connector::Payu,+ connector::Powertranz,+ connector::Rapyd,+ connector::Stax,+ connector::Stripe,+ connector::Shift4,+ connector::Trustpay,+ connector::Tsys,connector::Worldline,connector::Worldpay,connector::Zendiff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 9faebe9d1a..2323056991 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2057,6 +2057,7 @@ pub async fn insert_merchant_connector_creds_to_config(}}+#[derive(Clone)]pub enum MerchantConnectorAccountType {DbVal(domain::MerchantConnectorAccount),CacheVal(api_models::admin::MerchantConnectorDetails),@@ -2187,6 +2188,10 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(preprocessing_id: router_data.preprocessing_id,recurring_mandate_payment_data: router_data.recurring_mandate_payment_data,connector_request_reference_id: router_data.connector_request_reference_id,+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode: router_data.test_mode,}}diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex f7423ee60c..4e4a5e2614 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -133,6 +133,10 @@ where&payment_data.payment_attempt,),preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode,};diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsnew file mode 100644index 0000000000..2ad4f43ca7--- /dev/null+++ b/crates/router/src/core/payouts.rs@@ -0,0 +1,1325 @@+pub mod helpers;+pub mod validator;++use api_models::enums as api_enums;+use common_utils::{crypto::Encryptable, ext_traits::ValueExt};+use diesel_models::enums as storage_enums;+use error_stack::{report, ResultExt};+use router_env::{instrument, tracing};+use serde_json::{self};++use super::errors::{ConnectorErrorExt, StorageErrorExt};+use crate::{+ core::{+ errors::{self, RouterResponse, RouterResult},+ payments::{self, helpers as payment_helpers},+ utils as core_utils,+ },+ routes::AppState,+ services,+ types::{+ self,+ api::{self, payouts},+ domain, storage,+ },+ utils::{self, OptionExt},+};++// ********************************************** TYPES **********************************************+#[cfg(feature = "payouts")]+#[derive(Clone)]+pub struct PayoutData {+ pub billing_address: Option<domain::Address>,+ pub customer_details: Option<domain::Customer>,+ pub payouts: storage::Payouts,+ pub payout_attempt: storage::PayoutAttempt,+ pub payout_method_data: Option<payouts::PayoutMethodData>,+ pub merchant_connector_account: Option<payment_helpers::MerchantConnectorAccountType>,+}++// ********************************************** CORE FLOWS **********************************************+#[cfg(feature = "payouts")]+pub async fn get_connector_data(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ routed_through: Option<String>,+ routing_algorithm: Option<serde_json::Value>,+) -> RouterResult<api::PayoutConnectorData> {+ let mut routing_data = storage::PayoutRoutingData {+ routed_through,+ algorithm: None,+ };+ let connector_choice = helpers::get_default_payout_connector(state, routing_algorithm).await?;+ let connector_details = match connector_choice {+ api::PayoutConnectorChoice::SessionMultiple(session_connectors) => {+ api::PayoutConnectorCallType::Multiple(session_connectors)+ }++ api::PayoutConnectorChoice::StraightThrough(straight_through) => {+ let request_straight_through: Option<api::PayoutStraightThroughAlgorithm> =+ Some(straight_through)+ .map(|val| val.parse_value("StraightThroughAlgorithm"))+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid straight through routing rules format")?;+ helpers::decide_payout_connector(+ state,+ merchant_account,+ request_straight_through,+ &mut routing_data,+ )?+ }++ api::PayoutConnectorChoice::Decide => {+ helpers::decide_payout_connector(state, merchant_account, None, &mut routing_data)?+ }+ };+ let connector_data = match connector_details {+ api::PayoutConnectorCallType::Single(connector) => connector,++ api::PayoutConnectorCallType::Multiple(connectors) => {+ // TODO: route through actual multiple connectors.+ connectors.first().map_or(+ Err(errors::ApiErrorResponse::IncorrectConnectorNameGiven),+ |c| Ok(c.connector.to_owned()),+ )?+ }+ };++ Ok(connector_data)+}++#[cfg(feature = "payouts")]+#[instrument(skip_all)]+pub async fn payouts_create_core(+ state: &AppState,+ merchant_account: domain::MerchantAccount,+ key_store: domain::MerchantKeyStore,+ req: payouts::PayoutCreateRequest,+) -> RouterResponse<payouts::PayoutCreateResponse>+where+{+ // Form connector data+ let connector_data = get_connector_data(+ state,+ &merchant_account,+ req.connector+ .clone()+ .and_then(|c| c.first().map(|c| c.to_string())),+ req.routing.clone(),+ )+ .await?;++ // Validate create request+ let (payout_id, payout_method_data) =+ validator::validate_create_request(state, &merchant_account, &req).await?;++ // Create DB entries+ let mut payout_data = payout_create_db_entries(+ state,+ &merchant_account,+ &key_store,+ &req,+ &payout_id,+ &connector_data.connector_name,+ payout_method_data.as_ref(),+ )+ .await?;++ call_connector_payout(+ state,+ &merchant_account,+ &key_store,+ &req,+ connector_data,+ &mut payout_data,+ )+ .await+}++#[cfg(feature = "payouts")]+pub async fn payouts_update_core(+ state: &AppState,+ merchant_account: domain::MerchantAccount,+ key_store: domain::MerchantKeyStore,+ req: payouts::PayoutCreateRequest,+) -> RouterResponse<payouts::PayoutCreateResponse> {+ let mut payout_data = make_payout_data(+ state,+ &merchant_account,+ &key_store,+ &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),+ )+ .await?;++ let payout_attempt = payout_data.payout_attempt.to_owned();+ let status = payout_attempt.status;++ // Verify update feasibility+ if helpers::is_payout_terminal_state(status) || helpers::is_payout_initiated(status) {+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "Payout {} cannot be updated for status {}",+ payout_attempt.payout_id, status+ ),+ }));+ }++ // Update DB with new data+ let payouts = payout_data.payouts.to_owned();+ let updated_payouts = storage::PayoutsUpdate::Update {+ amount: req.amount.unwrap_or(payouts.amount.into()).into(),+ destination_currency: req.currency.unwrap_or(payouts.destination_currency),+ source_currency: req.currency.unwrap_or(payouts.source_currency),+ description: req.description.clone().or(payouts.description),+ recurring: req.recurring.unwrap_or(payouts.recurring),+ auto_fulfill: req.auto_fulfill.unwrap_or(payouts.auto_fulfill),+ return_url: req.return_url.clone().or(payouts.return_url),+ entity_type: req.entity_type.unwrap_or(payouts.entity_type),+ metadata: req.metadata.clone().or(payouts.metadata),+ last_modified_at: Some(common_utils::date_time::now()),+ };++ let db = &*state.store;+ let payout_id = req.payout_id.clone().get_required_value("payout_id")?;+ let merchant_id = &merchant_account.merchant_id;+ payout_data.payouts = db+ .update_payout_by_merchant_id_payout_id(merchant_id, &payout_id, updated_payouts)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payouts")?;++ let payout_attempt = payout_data.payout_attempt.to_owned();+ let updated_business_country =+ payout_attempt+ .business_country+ .map_or(req.business_country.to_owned(), |c| {+ req.business_country+ .to_owned()+ .and_then(|nc| if nc != c { Some(nc) } else { None })+ });+ let updated_business_label =+ payout_attempt+ .business_label+ .map_or(req.business_label.to_owned(), |l| {+ req.business_label+ .to_owned()+ .and_then(|nl| if nl != l { Some(nl) } else { None })+ });+ match (updated_business_country, updated_business_label) {+ (None, None) => {}+ (business_country, business_label) => {+ let update_payout_attempt = storage::PayoutAttemptUpdate::BusinessUpdate {+ business_country,+ business_label,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ &payout_id,+ update_payout_attempt,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt")?;+ }+ }++ // Form connector data+ let connector_data: api::PayoutConnectorData = api::PayoutConnectorData::get_connector_by_name(+ &state.conf.connectors,+ &payout_data.payout_attempt.connector,+ api::GetToken::Connector,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get the connector data")?;++ call_connector_payout(+ state,+ &merchant_account,+ &key_store,+ &req,+ connector_data,+ &mut payout_data,+ )+ .await+}++#[cfg(feature = "payouts")]+#[instrument(skip_all)]+pub async fn payouts_retrieve_core(+ state: &AppState,+ merchant_account: domain::MerchantAccount,+ key_store: domain::MerchantKeyStore,+ req: payouts::PayoutRetrieveRequest,+) -> RouterResponse<payouts::PayoutCreateResponse> {+ let payout_data = make_payout_data(+ state,+ &merchant_account,+ &key_store,+ &payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()),+ )+ .await?;++ response_handler(+ state,+ &merchant_account,+ &payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()),+ &payout_data,+ )+ .await+}++#[cfg(feature = "payouts")]+#[instrument(skip_all)]+pub async fn payouts_cancel_core(+ state: &AppState,+ merchant_account: domain::MerchantAccount,+ key_store: domain::MerchantKeyStore,+ req: payouts::PayoutActionRequest,+) -> RouterResponse<payouts::PayoutCreateResponse> {+ let mut payout_data = make_payout_data(+ state,+ &merchant_account,+ &key_store,+ &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),+ )+ .await?;++ let payout_attempt = payout_data.payout_attempt.to_owned();+ let connector_payout_id = payout_attempt.connector_payout_id.to_owned();+ let status = payout_attempt.status;++ // Verify if cancellation can be triggered+ if helpers::is_payout_terminal_state(status) {+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "Payout {} cannot be cancelled for status {}",+ payout_attempt.payout_id, status+ ),+ }));++ // Make local cancellation+ } else if helpers::is_eligible_for_local_payout_cancellation(status) {+ let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: connector_payout_id.to_owned(),+ status: storage_enums::PayoutStatus::Cancelled,+ error_message: Some("Cancelled by user".to_string()),+ error_code: None,+ is_eligible: None,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = state+ .store+ .update_payout_attempt_by_merchant_id_payout_id(+ &merchant_account.merchant_id,+ &payout_attempt.payout_id,+ updated_payout_attempt,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?;++ // Trigger connector's cancellation+ } else {+ // Form connector data+ let connector_data = get_connector_data(+ state,+ &merchant_account,+ Some(payout_attempt.connector),+ None,+ )+ .await?;++ payout_data = cancel_payout(+ state,+ &merchant_account,+ &key_store,+ &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),+ &connector_data,+ &mut payout_data,+ )+ .await+ .attach_printable("Payout cancellation failed for given Payout request")?;+ }++ response_handler(+ state,+ &merchant_account,+ &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),+ &payout_data,+ )+ .await+}++#[cfg(feature = "payouts")]+#[instrument(skip_all)]+pub async fn payouts_fulfill_core(+ state: &AppState,+ merchant_account: domain::MerchantAccount,+ key_store: domain::MerchantKeyStore,+ req: payouts::PayoutActionRequest,+) -> RouterResponse<payouts::PayoutCreateResponse> {+ let mut payout_data = make_payout_data(+ state,+ &merchant_account,+ &key_store,+ &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),+ )+ .await?;++ let payout_attempt = payout_data.payout_attempt.to_owned();+ let status = payout_attempt.status;++ // Verify if fulfillment can be triggered+ if helpers::is_payout_terminal_state(status)+ || status != api_enums::PayoutStatus::RequiresFulfillment+ {+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "Payout {} cannot be fulfilled for status {}",+ payout_attempt.payout_id, status+ ),+ }));+ }++ // Form connector data+ let connector_data = get_connector_data(+ state,+ &merchant_account,+ Some(payout_attempt.connector.clone()),+ None,+ )+ .await?;++ // Trigger fulfillment+ payout_data.payout_method_data = Some(+ helpers::make_payout_method_data(+ state,+ None,+ payout_attempt.payout_token.as_deref(),+ &payout_attempt.customer_id,+ &payout_attempt.merchant_id,+ &payout_attempt.payout_id,+ Some(&payout_data.payouts.payout_type),+ )+ .await?+ .get_required_value("payout_method_data")?,+ );+ payout_data = fulfill_payout(+ state,+ &merchant_account,+ &key_store,+ &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),+ &connector_data,+ &mut payout_data,+ )+ .await+ .attach_printable("Payout fulfillment failed for given Payout request")?;++ if helpers::is_payout_err_state(status) {+ return Err(report!(errors::ApiErrorResponse::PayoutFailed {+ data: Some(+ serde_json::json!({"payout_status": status.to_string(), "error_message": payout_attempt.error_message, "error_code": payout_attempt.error_code})+ ),+ }));+ }++ response_handler(+ state,+ &merchant_account,+ &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),+ &payout_data,+ )+ .await+}++// ********************************************** HELPERS **********************************************+#[cfg(feature = "payouts")]+pub async fn call_connector_payout(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ req: &payouts::PayoutCreateRequest,+ connector_data: api::PayoutConnectorData,+ payout_data: &mut PayoutData,+) -> RouterResponse<payouts::PayoutCreateResponse> {+ let payout_attempt = &payout_data.payout_attempt.to_owned();+ let payouts: &diesel_models::payouts::Payouts = &payout_data.payouts.to_owned();+ // Fetch / store payout_method_data+ if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() {+ payout_data.payout_method_data = Some(+ helpers::make_payout_method_data(+ state,+ req.payout_method_data.as_ref(),+ payout_attempt.payout_token.as_deref(),+ &payout_attempt.customer_id,+ &payout_attempt.merchant_id,+ &payout_attempt.payout_id,+ Some(&payouts.payout_type),+ )+ .await?+ .get_required_value("payout_method_data")?,+ );+ }+ if let Some(true) = req.confirm {+ // Eligibility flow+ if payouts.payout_type == storage_enums::PayoutType::Card+ && payout_attempt.is_eligible.is_none()+ {+ *payout_data = check_payout_eligibility(+ state,+ merchant_account,+ key_store,+ req,+ &connector_data,+ payout_data,+ )+ .await+ .attach_printable("Eligibility failed for given Payout request")?;+ }++ // Payout creation flow+ utils::when(+ !payout_attempt+ .is_eligible+ .unwrap_or(state.conf.payouts.payout_eligibility),+ || {+ Err(report!(errors::ApiErrorResponse::PayoutFailed {+ data: Some(serde_json::json!({+ "message": "Payout method data is invalid"+ }))+ })+ .attach_printable("Payout data provided is invalid"))+ },+ )?;+ if payout_data.payouts.payout_type == storage_enums::PayoutType::Bank+ && payout_data.payout_attempt.status == storage_enums::PayoutStatus::RequiresCreation+ {+ // Create customer flow+ *payout_data = create_recipient(+ state,+ merchant_account,+ key_store,+ req,+ &connector_data,+ payout_data,+ )+ .await+ .attach_printable("Creation of customer failed")?;++ // Create payout flow+ *payout_data = create_payout(+ state,+ merchant_account,+ key_store,+ req,+ &connector_data,+ payout_data,+ )+ .await+ .attach_printable("Payout creation failed for given Payout request")?;+ }+ };++ // Auto fulfillment flow+ let status = payout_data.payout_attempt.status;+ if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment {+ *payout_data = fulfill_payout(+ state,+ merchant_account,+ key_store,+ &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),+ &connector_data,+ payout_data,+ )+ .await+ .attach_printable("Payout fulfillment failed for given Payout request")?;+ }++ response_handler(+ state,+ merchant_account,+ &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),+ payout_data,+ )+ .await+}++#[cfg(feature = "payouts")]+pub async fn create_recipient(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ req: &payouts::PayoutCreateRequest,+ connector_data: &api::PayoutConnectorData,+ payout_data: &mut PayoutData,+) -> RouterResult<PayoutData> {+ let customer_details = payout_data.customer_details.to_owned();+ let connector_name = connector_data.connector_name.to_string();++ let connector_label = payment_helpers::get_connector_label(+ payout_data+ .payout_attempt+ .business_country+ .unwrap_or_default(),+ &payout_data+ .payout_attempt+ .business_label+ .to_owned()+ .unwrap_or_default(),+ None,+ &connector_name,+ );++ let (should_call_connector, _connector_customer_id) =+ helpers::should_call_payout_connector_create_customer(+ state,+ connector_data,+ &customer_details,+ &connector_label,+ );+ if should_call_connector {+ // 1. Form router data+ let customer_router_data = core_utils::construct_payout_router_data(+ state,+ &connector_name,+ merchant_account,+ key_store,+ &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),+ payout_data,+ )+ .await?;++ // 2. Fetch connector integration details+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ api::PoRecipient,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = connector_data.connector.get_connector_integration();++ // 3. Call connector service+ let router_resp = services::execute_connector_processing_step(+ state,+ connector_integration,+ &customer_router_data,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await+ .to_payout_failed_response()?;++ match router_resp.response {+ Ok(recipient_create_data) => {+ if let Some(customer) = customer_details {+ let db = &*state.store;+ let customer_id = customer.customer_id.to_owned();+ let merchant_id = merchant_account.merchant_id.to_owned();+ let updated_customer = storage::CustomerUpdate::ConnectorCustomer {+ connector_customer: Some(+ serde_json::json!({"id": recipient_create_data.connector_payout_id}),+ ),+ };+ payout_data.customer_details = Some(+ db.update_customer_by_customer_id_merchant_id(+ customer_id,+ merchant_id,+ updated_customer,+ key_store,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating customers in db")?,+ )+ }+ }+ Err(err) => Err(errors::ApiErrorResponse::PayoutFailed {+ data: serde_json::to_value(err).ok(),+ })?,+ }+ }+ Ok(payout_data.clone())+}++#[cfg(feature = "payouts")]+pub async fn check_payout_eligibility(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ req: &payouts::PayoutCreateRequest,+ connector_data: &api::PayoutConnectorData,+ payout_data: &mut PayoutData,+) -> RouterResult<PayoutData> {+ // 1. Form Router data+ let router_data = core_utils::construct_payout_router_data(+ state,+ &connector_data.connector_name.to_string(),+ merchant_account,+ key_store,+ &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),+ payout_data,+ )+ .await?;++ // 2. Fetch connector integration details+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ api::PoEligibility,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = connector_data.connector.get_connector_integration();++ // 3. Call connector service+ let router_data_resp = services::execute_connector_processing_step(+ state,+ connector_integration,+ &router_data,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await+ .to_payout_failed_response()?;++ // 4. Process data returned by the connector+ let db = &*state.store;+ let merchant_id = &merchant_account.merchant_id;+ let payout_id = &payout_data.payouts.payout_id;+ match router_data_resp.response {+ Ok(payout_response_data) => {+ let payout_attempt = &payout_data.payout_attempt;+ let status = payout_response_data+ .status+ .unwrap_or(payout_attempt.status.to_owned());+ let updated_payout_attempt =+ storage::payout_attempt::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: payout_response_data.connector_payout_id,+ status,+ error_code: None,+ error_message: None,+ is_eligible: payout_response_data.payout_eligible,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ updated_payout_attempt,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?;+ if helpers::is_payout_err_state(status) {+ return Err(report!(errors::ApiErrorResponse::PayoutFailed {+ data: Some(+ serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()})+ ),+ }));+ }+ }+ Err(err) => {+ let updated_payout_attempt =+ storage::payout_attempt::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: String::default(),+ status: storage_enums::PayoutStatus::Failed,+ error_code: Some(err.code),+ error_message: Some(err.message),+ is_eligible: None,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ updated_payout_attempt,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?;+ }+ };++ Ok(payout_data.clone())+}++#[cfg(feature = "payouts")]+pub async fn create_payout(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ req: &payouts::PayoutCreateRequest,+ connector_data: &api::PayoutConnectorData,+ payout_data: &mut PayoutData,+) -> RouterResult<PayoutData> {+ // 1. Form Router data+ let mut router_data = core_utils::construct_payout_router_data(+ state,+ &connector_data.connector_name.to_string(),+ merchant_account,+ key_store,+ &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),+ payout_data,+ )+ .await?;++ // 2. Fetch connector integration details+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ api::PoCreate,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = connector_data.connector.get_connector_integration();++ // 3. Execute pretasks+ connector_integration+ .execute_pretasks(&mut router_data, state)+ .await+ .to_payout_failed_response()?;++ // 4. Call connector service+ let router_data_resp = services::execute_connector_processing_step(+ state,+ connector_integration,+ &router_data,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await+ .to_payout_failed_response()?;++ // 5. Process data returned by the connector+ let db = &*state.store;+ let merchant_id = &merchant_account.merchant_id;+ let payout_id = &payout_data.payouts.payout_id;+ match router_data_resp.response {+ Ok(payout_response_data) => {+ let payout_attempt = &payout_data.payout_attempt;+ let status = payout_response_data+ .status+ .unwrap_or(payout_attempt.status.to_owned());+ let updated_payout_attempt =+ storage::payout_attempt::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: payout_response_data.connector_payout_id,+ status,+ error_code: None,+ error_message: None,+ is_eligible: payout_response_data.payout_eligible,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ updated_payout_attempt,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?;+ if helpers::is_payout_err_state(status) {+ return Err(report!(errors::ApiErrorResponse::PayoutFailed {+ data: Some(+ serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()})+ ),+ }));+ }+ }+ Err(err) => {+ let updated_payout_attempt =+ storage::payout_attempt::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: String::default(),+ status: storage_enums::PayoutStatus::Failed,+ error_code: Some(err.code),+ error_message: Some(err.message),+ is_eligible: None,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ updated_payout_attempt,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?;+ }+ };++ Ok(payout_data.clone())+}++#[cfg(feature = "payouts")]+pub async fn cancel_payout(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ req: &payouts::PayoutRequest,+ connector_data: &api::PayoutConnectorData,+ payout_data: &mut PayoutData,+) -> RouterResult<PayoutData> {+ // 1. Form Router data+ let router_data = core_utils::construct_payout_router_data(+ state,+ &connector_data.connector_name.to_string(),+ merchant_account,+ key_store,+ req,+ payout_data,+ )+ .await?;++ // 2. Fetch connector integration details+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ api::PoCancel,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = connector_data.connector.get_connector_integration();++ // 3. Call connector service+ let router_data_resp = services::execute_connector_processing_step(+ state,+ connector_integration,+ &router_data,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await+ .to_payout_failed_response()?;++ // 4. Process data returned by the connector+ let db = &*state.store;+ let merchant_id = &merchant_account.merchant_id;+ let payout_id = &payout_data.payout_attempt.payout_id;+ match router_data_resp.response {+ Ok(payout_response_data) => {+ let status = payout_response_data+ .status+ .unwrap_or(payout_data.payout_attempt.status.to_owned());+ let updated_payout_attempt =+ storage::payout_attempt::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: payout_response_data.connector_payout_id,+ status,+ error_code: None,+ error_message: None,+ is_eligible: payout_response_data.payout_eligible,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ updated_payout_attempt,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?+ }+ Err(err) => {+ let updated_payouts_create =+ storage::payout_attempt::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: String::default(),+ status: storage_enums::PayoutStatus::Failed,+ error_code: Some(err.code),+ error_message: Some(err.message),+ is_eligible: None,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ updated_payouts_create,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?+ }+ };++ Ok(payout_data.clone())+}++#[cfg(feature = "payouts")]+pub async fn fulfill_payout(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ req: &payouts::PayoutRequest,+ connector_data: &api::PayoutConnectorData,+ payout_data: &mut PayoutData,+) -> RouterResult<PayoutData> {+ // 1. Form Router data+ let router_data = core_utils::construct_payout_router_data(+ state,+ &connector_data.connector_name.to_string(),+ merchant_account,+ key_store,+ req,+ payout_data,+ )+ .await?;++ // 2. Fetch connector integration details+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ api::PoFulfill,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = connector_data.connector.get_connector_integration();++ // 3. Call connector service+ let router_data_resp = services::execute_connector_processing_step(+ state,+ connector_integration,+ &router_data,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await+ .to_payout_failed_response()?;++ // 4. Process data returned by the connector+ let db = &*state.store;+ let merchant_id = &merchant_account.merchant_id;+ let payout_attempt = &payout_data.payout_attempt;+ let payout_id = &payout_attempt.payout_id;+ match router_data_resp.response {+ Ok(payout_response_data) => {+ if payout_data.payouts.recurring && payout_data.payouts.payout_method_id.is_none() {+ helpers::save_payout_data_to_locker(+ state,+ payout_attempt,+ &payout_data+ .payout_method_data+ .clone()+ .get_required_value("payout_method_data")?,+ merchant_account,+ key_store,+ )+ .await?;+ }+ let status = payout_response_data+ .status+ .unwrap_or(payout_attempt.status.to_owned());+ let updated_payouts = storage::payout_attempt::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: payout_attempt.connector_payout_id.to_owned(),+ status,+ error_code: None,+ error_message: None,+ is_eligible: payout_response_data.payout_eligible,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ updated_payouts,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?;+ if helpers::is_payout_err_state(status) {+ return Err(report!(errors::ApiErrorResponse::PayoutFailed {+ data: Some(+ serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()})+ ),+ }));+ }+ }+ Err(err) => {+ let updated_payouts = storage::payout_attempt::PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: String::default(),+ status: storage_enums::PayoutStatus::Failed,+ error_code: Some(err.code),+ error_message: Some(err.message),+ is_eligible: None,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ payout_data.payout_attempt = db+ .update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ updated_payouts,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout_attempt in db")?+ }+ };++ Ok(payout_data.clone())+}++#[cfg(feature = "payouts")]+pub async fn response_handler(+ _state: &AppState,+ merchant_account: &domain::MerchantAccount,+ _req: &payouts::PayoutRequest,+ payout_data: &PayoutData,+) -> RouterResponse<payouts::PayoutCreateResponse> {+ let payout_attempt = payout_data.payout_attempt.to_owned();+ let payouts = payout_data.payouts.to_owned();+ let billing_address = payout_data.billing_address.to_owned();+ let customer_details = payout_data.customer_details.to_owned();+ let customer_id = payouts.customer_id;++ let (email, name, phone, phone_country_code) = customer_details+ .map_or((None, None, None, None), |c| {+ (c.email, c.name, c.phone, c.phone_country_code)+ });++ let address = billing_address.as_ref().map(|a| {+ let phone_details = api_models::payments::PhoneDetails {+ number: a.phone_number.to_owned().map(Encryptable::into_inner),+ country_code: a.country_code.to_owned(),+ };+ let address_details = api_models::payments::AddressDetails {+ city: a.city.to_owned(),+ country: a.country.to_owned(),+ line1: a.line1.to_owned().map(Encryptable::into_inner),+ line2: a.line2.to_owned().map(Encryptable::into_inner),+ line3: a.line3.to_owned().map(Encryptable::into_inner),+ zip: a.zip.to_owned().map(Encryptable::into_inner),+ first_name: a.first_name.to_owned().map(Encryptable::into_inner),+ last_name: a.last_name.to_owned().map(Encryptable::into_inner),+ state: a.state.to_owned().map(Encryptable::into_inner),+ };+ api::payments::Address {+ phone: Some(phone_details),+ address: Some(address_details),+ }+ });++ let response = api::PayoutCreateResponse {+ payout_id: payouts.payout_id.to_owned(),+ merchant_id: merchant_account.merchant_id.to_owned(),+ amount: payouts.amount.to_owned(),+ currency: payouts.destination_currency.to_owned(),+ connector: Some(payout_attempt.connector.to_owned()),+ payout_type: payouts.payout_type.to_owned(),+ billing: address,+ customer_id,+ auto_fulfill: payouts.auto_fulfill,+ email,+ name,+ phone,+ phone_country_code,+ client_secret: None,+ return_url: payouts.return_url.to_owned(),+ business_country: payout_attempt.business_country,+ business_label: payout_attempt.business_label,+ description: payouts.description.to_owned(),+ entity_type: payouts.entity_type.to_owned(),+ recurring: payouts.recurring,+ metadata: payouts.metadata,+ status: payout_attempt.status.to_owned(),+ error_message: payout_attempt.error_message.to_owned(),+ error_code: payout_attempt.error_code,+ };+ Ok(services::ApplicationResponse::Json(response))+}++// DB entries+#[cfg(feature = "payouts")]+pub async fn payout_create_db_entries(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ req: &payouts::PayoutCreateRequest,+ payout_id: &String,+ connector_name: &api_enums::PayoutConnectors,+ stored_payout_method_data: Option<&payouts::PayoutMethodData>,+) -> RouterResult<PayoutData> {+ let db = &*state.store;+ let merchant_id = &merchant_account.merchant_id;++ // Get or create customer+ let customer_details = payments::CustomerDetails {+ customer_id: req.customer_id.to_owned(),+ name: req.name.to_owned(),+ email: req.email.to_owned(),+ phone: req.phone.to_owned(),+ phone_country_code: req.phone_country_code.to_owned(),+ };+ let customer = helpers::get_or_create_customer_details(+ state,+ &customer_details,+ merchant_account,+ key_store,+ )+ .await?;+ let customer_id = customer+ .to_owned()+ .ok_or_else(|| {+ report!(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "customer_id",+ })+ })?+ .customer_id;++ // Get or create address+ let billing_address = payment_helpers::get_address_for_payment_request(+ db,+ req.billing.as_ref(),+ None,+ merchant_id,+ Some(&customer_id.to_owned()),+ key_store,+ )+ .await?;+ let address_id = billing_address+ .to_owned()+ .ok_or_else(|| {+ report!(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "billing.address",+ })+ })?+ .address_id;++ // Make payouts entry+ let currency = req.currency.to_owned().get_required_value("currency")?;+ let payout_type = req+ .payout_type+ .to_owned()+ .get_required_value("payout_type")?;++ let payout_method_id = if stored_payout_method_data.is_some() {+ req.payout_token.to_owned()+ } else {+ None+ };++ let payouts_req = storage::PayoutsNew::default()+ .set_payout_id(payout_id.to_owned())+ .set_merchant_id(merchant_id.to_owned())+ .set_customer_id(customer_id.to_owned())+ .set_address_id(address_id.to_owned())+ .set_payout_type(payout_type)+ .set_amount(req.amount.unwrap_or(api::Amount::Zero).into())+ .set_destination_currency(currency)+ .set_source_currency(currency)+ .set_description(req.description.to_owned())+ .set_recurring(req.recurring.unwrap_or(false))+ .set_auto_fulfill(req.auto_fulfill.unwrap_or(false))+ .set_return_url(req.return_url.to_owned())+ .set_entity_type(+ req.entity_type+ .unwrap_or(api_enums::PayoutEntityType::default()),+ )+ .set_metadata(req.metadata.to_owned())+ .set_created_at(Some(common_utils::date_time::now()))+ .set_last_modified_at(Some(common_utils::date_time::now()))+ .set_payout_method_id(payout_method_id)+ .to_owned();+ let payouts = db+ .insert_payout(payouts_req)+ .await+ .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout {+ payout_id: payout_id.to_owned(),+ })+ .attach_printable("Error inserting payouts in db")?;++ // Make payout_attempt entry+ let status = if req.payout_method_data.is_some()+ || req.payout_token.is_some()+ || stored_payout_method_data.is_some()+ {+ storage_enums::PayoutStatus::RequiresCreation+ } else {+ storage_enums::PayoutStatus::RequiresPayoutMethodData+ };+ let _id = core_utils::get_or_generate_uuid("payout_attempt_id", None)?;+ let payout_attempt_id = format!("{}_{}", merchant_id.to_owned(), payout_id.to_owned());++ let payout_attempt_req = storage::PayoutAttemptNew::default()+ .set_payout_attempt_id(payout_attempt_id.to_string())+ .set_payout_id(payout_id.to_owned())+ .set_customer_id(customer_id.to_owned())+ .set_merchant_id(merchant_id.to_owned())+ .set_address_id(address_id.to_owned())+ .set_connector(connector_name.to_string())+ .set_status(status)+ .set_business_country(req.business_country.to_owned())+ .set_business_label(req.business_label.to_owned())+ .set_payout_token(req.payout_token.to_owned())+ .set_created_at(Some(common_utils::date_time::now()))+ .set_last_modified_at(Some(common_utils::date_time::now()))+ .to_owned();+ let payout_attempt = db+ .insert_payout_attempt(payout_attempt_req)+ .await+ .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout {+ payout_id: payout_id.to_owned(),+ })+ .attach_printable("Error inserting payout_attempt in db")?;++ // Make PayoutData+ Ok(PayoutData {+ billing_address,+ customer_details: customer,+ payouts,+ payout_attempt,+ payout_method_data: req+ .payout_method_data+ .as_ref()+ .cloned()+ .or(stored_payout_method_data.cloned()),+ merchant_connector_account: None,+ })+}++#[cfg(feature = "payouts")]+pub async fn make_payout_data(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ req: &payouts::PayoutRequest,+) -> RouterResult<PayoutData> {+ let db = &*state.store;+ let merchant_id = &merchant_account.merchant_id;+ let payout_id = match req {+ payouts::PayoutRequest::PayoutActionRequest(r) => r.payout_id.clone(),+ payouts::PayoutRequest::PayoutCreateRequest(r) => r.payout_id.clone().unwrap_or_default(),+ payouts::PayoutRequest::PayoutRetrieveRequest(r) => r.payout_id.clone(),+ };++ let payouts = db+ .find_payout_by_merchant_id_payout_id(merchant_id, &payout_id)+ .await+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;++ let payout_attempt = db+ .find_payout_attempt_by_merchant_id_payout_id(merchant_id, &payout_id)+ .await+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;++ let billing_address = payment_helpers::get_address_for_payment_request(+ db,+ None,+ Some(&payouts.address_id.to_owned()),+ merchant_id,+ Some(&payouts.customer_id.to_owned()),+ key_store,+ )+ .await?;++ let customer_details = db+ .find_customer_optional_by_customer_id_merchant_id(+ &payouts.customer_id.to_owned(),+ merchant_id,+ key_store,+ )+ .await+ .map_or(None, |c| c);++ Ok(PayoutData {+ billing_address,+ customer_details,+ payouts,+ payout_attempt,+ payout_method_data: None,+ merchant_connector_account: None,+ })+}diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsnew file mode 100644index 0000000000..da2934c4c5--- /dev/null+++ b/crates/router/src/core/payouts/helpers.rs@@ -0,0 +1,426 @@+use std::str::FromStr;++use ::cards::CardNumber;+use common_utils::{errors::CustomResult, ext_traits::ValueExt};+use diesel_models::encryption::Encryption;+use error_stack::{IntoReport, ResultExt};+use masking::{ExposeInterface, PeekInterface, Secret};++use crate::{+ core::{+ errors::{self, RouterResult},+ payment_methods::{cards, vault},+ payments::{customers::get_connector_customer_details_if_present, CustomerDetails},+ utils as core_utils,+ },+ db::StorageInterface,+ routes::AppState,+ types::{+ api::{self, enums as api_enums},+ domain::{+ self,+ types::{self as domain_types, AsyncLift},+ },+ storage,+ transformers::ForeignFrom,+ },+ utils::{self, OptionExt},+};++pub async fn make_payout_method_data<'a>(+ state: &'a AppState,+ payout_method_data: Option<&api::PayoutMethodData>,+ payout_token: Option<&str>,+ customer_id: &str,+ merchant_id: &str,+ payout_id: &str,+ payout_type: Option<&api_enums::PayoutType>,+) -> RouterResult<Option<api::PayoutMethodData>> {+ let db = &*state.store;+ let hyperswitch_token = if let Some(payout_token) = payout_token {+ let key = format!(+ "pm_token_{}_{}_hyperswitch",+ payout_token,+ api_enums::PaymentMethod::foreign_from(+ payout_type.get_required_value("payout_type")?.to_owned()+ )+ );++ let redis_conn = state.store.get_redis_conn();+ let hyperswitch_token_option = redis_conn+ .get_key::<Option<String>>(&key)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch the token from redis")?;++ hyperswitch_token_option.or(Some(payout_token.to_string()))+ } else {+ None+ };++ match (payout_method_data.to_owned(), hyperswitch_token) {+ // Get operation+ (None, Some(payout_token)) => {+ let (pm, supplementary_data) = vault::Vault::get_payout_method_data_from_temporary_locker(+ state,+ &payout_token,+ )+ .await+ .attach_printable(+ "Payout method for given token not found or there was a problem fetching it",+ )?;+ utils::when(+ supplementary_data+ .customer_id+ .ne(&Some(customer_id.to_owned())),+ || {+ Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payout method and customer passed in payout are not same".into() })+ },+ )?;+ Ok(pm)+ }++ // Create / Update operation+ (Some(payout_method), payout_token) => {+ let lookup_key = vault::Vault::store_payout_method_data_in_locker(+ state,+ payout_token.to_owned(),+ payout_method,+ Some(customer_id.to_owned()),+ )+ .await?;++ // Update payout_token in payout_attempt table+ if payout_token.is_none() {+ let payout_update = storage::PayoutAttemptUpdate::PayoutTokenUpdate {+ payout_token: lookup_key,+ last_modified_at: Some(common_utils::date_time::now()),+ };+ db.update_payout_attempt_by_merchant_id_payout_id(+ merchant_id,+ payout_id,+ payout_update,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating token in payout attempt")?;+ }+ Ok(Some(payout_method.clone()))+ }++ // Ignore if nothing is passed+ _ => Ok(None),+ }+}++pub async fn save_payout_data_to_locker(+ state: &AppState,+ payout_attempt: &storage::payout_attempt::PayoutAttempt,+ payout_method_data: &api::PayoutMethodData,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+) -> RouterResult<()> {+ let mut enc_card_data = None;+ let (card_details, payment_method_type) = match payout_method_data {+ api_models::payouts::PayoutMethodData::Card(card) => (+ api::CardDetail {+ card_number: card.card_number.to_owned(),+ card_exp_month: card.expiry_month.to_owned(),+ card_exp_year: card.expiry_year.to_owned(),+ card_holder_name: Some(card.card_holder_name.to_owned()),+ nick_name: None,+ },+ api_enums::PaymentMethodType::Debit,+ ),+ api_models::payouts::PayoutMethodData::Bank(bank) => {+ let key = key_store.key.get_inner().peek();+ let enc_str = async {+ serde_json::to_value(payout_method_data.to_owned())+ .into_report()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encode payout method data")+ .ok()+ .map(|v| {+ let secret: Secret<String> = Secret::new(v.to_string());+ secret+ })+ .async_lift(|inner| domain_types::encrypt_optional(inner, key))+ .await+ }+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encrypt payout method data")?+ .map(Encryption::from)+ .map(|e| e.into_inner())+ .map_or(Err(errors::ApiErrorResponse::InternalServerError), |e| {+ Ok(hex::encode(e.peek()))+ })?;+ enc_card_data = Some(enc_str);+ (+ api::CardDetail {+ card_number: CardNumber::from_str("4111111111111111")+ .into_report()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to form a sample card number")?,+ card_exp_month: "12".to_string().into(),+ card_exp_year: "99".to_string().into(),+ card_holder_name: None,+ nick_name: None,+ },+ api_enums::PaymentMethodType::foreign_from(bank.to_owned()),+ )+ }+ };+ // Store payout method in locker+ let stored_resp = cards::call_to_card_hs(+ state,+ &card_details,+ enc_card_data.as_deref(),+ &payout_attempt.customer_id,+ merchant_account,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ // Store card_reference in payouts table+ let db = &*state.store;+ let updated_payout = storage::PayoutsUpdate::PayoutMethodIdUpdate {+ payout_method_id: Some(stored_resp.card_reference.to_owned()),+ last_modified_at: Some(common_utils::date_time::now()),+ };+ db.update_payout_by_merchant_id_payout_id(+ &merchant_account.merchant_id,+ &payout_attempt.payout_id,+ updated_payout,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payouts in saved payout method")?;++ // Insert in payment_method table+ let payment_method = api::PaymentMethodCreate {+ payment_method: api_enums::PaymentMethod::foreign_from(payout_method_data.to_owned()),+ payment_method_type: Some(payment_method_type),+ payment_method_issuer: None,+ payment_method_issuer_code: None,+ card: Some(card_details),+ metadata: None,+ customer_id: Some(payout_attempt.customer_id.to_owned()),+ card_network: None,+ };+ cards::create_payment_method(+ db,+ &payment_method,+ &payout_attempt.customer_id,+ &stored_resp.card_reference,+ &merchant_account.merchant_id,+ None,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to save payment method")?;++ Ok(())+}++pub async fn get_or_create_customer_details(+ state: &AppState,+ customer_details: &CustomerDetails,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+) -> RouterResult<Option<domain::Customer>> {+ let db: &dyn StorageInterface = &*state.store;+ // Create customer_id if not passed in request+ let customer_id =+ core_utils::get_or_generate_id("customer_id", &customer_details.customer_id, "cust")?;+ let merchant_id = &merchant_account.merchant_id;+ let key = key_store.key.get_inner().peek();++ match db+ .find_customer_optional_by_customer_id_merchant_id(&customer_id, merchant_id, key_store)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?+ {+ Some(customer) => Ok(Some(customer)),+ None => {+ let customer = domain::Customer {+ customer_id,+ merchant_id: merchant_id.to_string(),+ name: domain_types::encrypt_optional(customer_details.name.to_owned(), key)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?,+ email: domain_types::encrypt_optional(+ customer_details.email.to_owned().map(|e| e.expose()),+ key,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?,+ phone: domain_types::encrypt_optional(customer_details.phone.to_owned(), key)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?,+ description: None,+ phone_country_code: customer_details.phone_country_code.to_owned(),+ metadata: None,+ connector_customer: None,+ id: None,+ created_at: common_utils::date_time::now(),+ modified_at: common_utils::date_time::now(),+ };++ Ok(Some(+ db.insert_customer(customer, key_store)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?,+ ))+ }+ }+}++pub fn decide_payout_connector(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ request_straight_through: Option<api::PayoutStraightThroughAlgorithm>,+ routing_data: &mut storage::PayoutRoutingData,+) -> RouterResult<api::PayoutConnectorCallType> {+ if let Some(ref connector_name) = routing_data.routed_through {+ let connector_data = api::PayoutConnectorData::get_connector_by_name(+ &state.conf.connectors,+ connector_name,+ api::GetToken::Connector,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid connector name received in 'routed_through'")?;++ return Ok(api::PayoutConnectorCallType::Single(connector_data));+ }++ if let Some(routing_algorithm) = request_straight_through {+ let connector_name = match &routing_algorithm {+ api::PayoutStraightThroughAlgorithm::Single(conn) => conn.to_string(),+ };++ let connector_data = api::PayoutConnectorData::get_connector_by_name(+ &state.conf.connectors,+ &connector_name,+ api::GetToken::Connector,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid connector name received in routing algorithm")?;++ routing_data.routed_through = Some(connector_name);+ routing_data.algorithm = Some(routing_algorithm);+ return Ok(api::PayoutConnectorCallType::Single(connector_data));+ }++ if let Some(ref routing_algorithm) = routing_data.algorithm {+ let connector_name = match routing_algorithm {+ api::PayoutStraightThroughAlgorithm::Single(conn) => conn.to_string(),+ };++ let connector_data = api::PayoutConnectorData::get_connector_by_name(+ &state.conf.connectors,+ &connector_name,+ api::GetToken::Connector,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid connector name received in routing algorithm")?;++ routing_data.routed_through = Some(connector_name);+ return Ok(api::PayoutConnectorCallType::Single(connector_data));+ }++ let routing_algorithm = merchant_account+ .payout_routing_algorithm+ .clone()+ .get_required_value("PayoutRoutingAlgorithm")+ .change_context(errors::ApiErrorResponse::PreconditionFailed {+ message: "no routing algorithm has been configured".to_string(),+ })?+ .parse_value::<api::PayoutRoutingAlgorithm>("PayoutRoutingAlgorithm")+ .change_context(errors::ApiErrorResponse::InternalServerError) // Deserialization failed+ .attach_printable("Unable to deserialize merchant routing algorithm")?;++ let connector_name = match routing_algorithm {+ api::PayoutRoutingAlgorithm::Single(conn) => conn.to_string(),+ };++ let connector_data = api::PayoutConnectorData::get_connector_by_name(+ &state.conf.connectors,+ &connector_name,+ api::GetToken::Connector,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Routing algorithm gave invalid connector")?;++ routing_data.routed_through = Some(connector_name);++ Ok(api::PayoutConnectorCallType::Single(connector_data))+}++pub async fn get_default_payout_connector(+ _state: &AppState,+ request_connector: Option<serde_json::Value>,+) -> CustomResult<api::PayoutConnectorChoice, errors::ApiErrorResponse> {+ Ok(request_connector.map_or(+ api::PayoutConnectorChoice::Decide,+ api::PayoutConnectorChoice::StraightThrough,+ ))+}++pub fn should_call_payout_connector_create_customer<'a>(+ state: &AppState,+ connector: &api::PayoutConnectorData,+ customer: &'a Option<domain::Customer>,+ connector_label: &str,+) -> (bool, Option<&'a str>) {+ // Check if create customer is required for the connector+ let connector_needs_customer = state+ .conf+ .connector_customer+ .payout_connector_list+ .contains(&connector.connector_name);++ if connector_needs_customer {+ let connector_customer_details = customer.as_ref().and_then(|customer| {+ get_connector_customer_details_if_present(customer, connector_label)+ });+ let should_call_connector = connector_customer_details.is_none();+ (should_call_connector, connector_customer_details)+ } else {+ (false, None)+ }+}++pub fn is_payout_initiated(status: api_enums::PayoutStatus) -> bool {+ matches!(+ status,+ api_enums::PayoutStatus::Pending | api_enums::PayoutStatus::RequiresFulfillment+ )+}++pub fn is_payout_terminal_state(status: api_enums::PayoutStatus) -> bool {+ !matches!(+ status,+ api_enums::PayoutStatus::Pending+ | api_enums::PayoutStatus::RequiresCreation+ | api_enums::PayoutStatus::RequiresFulfillment+ | api_enums::PayoutStatus::RequiresPayoutMethodData+ )+}++pub fn is_payout_err_state(status: api_enums::PayoutStatus) -> bool {+ matches!(+ status,+ api_enums::PayoutStatus::Cancelled+ | api_enums::PayoutStatus::Failed+ | api_enums::PayoutStatus::Ineligible+ )+}++pub fn is_eligible_for_local_payout_cancellation(status: api_enums::PayoutStatus) -> bool {+ matches!(+ status,+ api_enums::PayoutStatus::RequiresCreation+ | api_enums::PayoutStatus::RequiresPayoutMethodData,+ )+}diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rsnew file mode 100644index 0000000000..74b212ade2--- /dev/null+++ b/crates/router/src/core/payouts/validator.rs@@ -0,0 +1,113 @@+use error_stack::{report, ResultExt};+use router_env::{instrument, tracing};++use super::helpers;+use crate::{+ core::{+ errors::{self, RouterResult},+ utils as core_utils,+ },+ db::StorageInterface,+ logger,+ routes::AppState,+ types::{api::payouts, domain, storage},+ utils::{self},+};++#[cfg(feature = "payouts")]+#[instrument(skip(db))]+pub async fn validate_uniqueness_of_payout_id_against_merchant_id(+ db: &dyn StorageInterface,+ payout_id: &str,+ merchant_id: &str,+) -> RouterResult<Option<storage::Payouts>> {+ let payout = db+ .find_payout_by_merchant_id_payout_id(merchant_id, payout_id)+ .await;++ logger::debug!(?payout);+ match payout {+ Err(err) => {+ if err.current_context().is_db_not_found() {+ // Empty vec should be returned by query in case of no results, this check exists just+ // to be on the safer side. Fixed this, now vector is not returned but should check the flow in detail later.+ Ok(None)+ } else {+ Err(err+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while finding payout_attempt, database error"))+ }+ }+ Ok(payout) => {+ if payout.payout_id == payout_id {+ Ok(Some(payout))+ } else {+ Ok(None)+ }+ }+ }+}++/// Validates the request on below checks+/// - merchant_id passed is same as the one in merchant_account table+/// - payout_id is unique against merchant_id+/// - payout_token provided is legitimate+#[cfg(feature = "payouts")]+pub async fn validate_create_request(+ state: &AppState,+ merchant_account: &domain::MerchantAccount,+ req: &payouts::PayoutCreateRequest,+) -> RouterResult<(String, Option<payouts::PayoutMethodData>)> {+ let merchant_id = &merchant_account.merchant_id;++ // Merchant ID+ let predicate = req.merchant_id.as_ref().map(|mid| mid != merchant_id);+ utils::when(predicate.unwrap_or(false), || {+ Err(report!(errors::ApiErrorResponse::InvalidDataFormat {+ field_name: "merchant_id".to_string(),+ expected_format: "merchant_id from merchant account".to_string(),+ })+ .attach_printable("invalid merchant_id in request"))+ })?;++ // Payout ID+ let db: &dyn StorageInterface = &*state.store;+ let payout_id = core_utils::get_or_generate_uuid("payout_id", req.payout_id.as_ref())?;+ match validate_uniqueness_of_payout_id_against_merchant_id(db, &payout_id, merchant_id)+ .await+ .change_context(errors::ApiErrorResponse::DuplicatePayout {+ payout_id: payout_id.to_owned(),+ })+ .attach_printable_lazy(|| {+ format!(+ "Unique violation while checking payout_id: {} against merchant_id: {}",+ payout_id.to_owned(),+ merchant_id+ )+ })? {+ Some(_) => Err(report!(errors::ApiErrorResponse::DuplicatePayout {+ payout_id: payout_id.to_owned()+ })),+ None => Ok(()),+ }?;++ // Payout token+ let payout_method_data = match req.payout_token.to_owned() {+ Some(payout_token) => {+ let customer_id = req.customer_id.to_owned().map_or("".to_string(), |c| c);+ helpers::make_payout_method_data(+ state,+ req.payout_method_data.as_ref(),+ Some(&payout_token),+ &customer_id,+ &merchant_account.merchant_id,+ payout_id.as_ref(),+ req.payout_type.as_ref(),+ )+ .await?+ }+ None => None,+ };++ Ok((payout_id, payout_method_data))+}diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex 3d81ed913d..f3f281cdc9 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -2,10 +2,17 @@ use std::marker::PhantomData;use api_models::enums::{DisputeStage, DisputeStatus};use common_utils::errors::CustomResult;+#[cfg(feature = "payouts")]+use common_utils::{crypto::Encryptable, pii::Email};use error_stack::{IntoReport, ResultExt};use router_env::{instrument, tracing};+use uuid::Uuid;use super::payments::{helpers, PaymentAddress};+#[cfg(feature = "payouts")]+use super::payouts::PayoutData;+#[cfg(feature = "payouts")]+use crate::core::payments;use crate::{configs::settings,consts,@@ -16,14 +23,169 @@ use crate::{storage::{self, enums},ErrorResponse,},- utils::{generate_id, OptionExt, ValueExt},+ utils::{generate_id, generate_uuid, OptionExt, ValueExt},};-const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW: &str =+pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW: &str ="irrelevant_connector_request_reference_id_in_dispute_flow";const IRRELEVANT_PAYMENT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_payment_id_in_dispute_flow";const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_dispute_flow";+#[cfg(feature = "payouts")]+#[instrument(skip_all)]+pub async fn get_mca_for_payout<'a>(+ state: &'a AppState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ payout_data: &PayoutData,+) -> RouterResult<helpers::MerchantConnectorAccountType> {+ let payout_attempt = &payout_data.payout_attempt;+ match payout_data.merchant_connector_account.to_owned() {+ Some(mca) => Ok(mca),+ None => {+ let (business_country, business_label) = helpers::get_business_details(+ payout_attempt.business_country,+ payout_attempt.business_label.as_ref(),+ merchant_account,+ )?;++ let connector_label =+ helpers::get_connector_label(business_country, &business_label, None, connector_id);++ let merchant_connector_account = helpers::get_merchant_connector_account(+ state,+ merchant_account.merchant_id.as_str(),+ &connector_label,+ None,+ key_store,+ )+ .await?;+ Ok(merchant_connector_account)+ }+ }+}++#[cfg(feature = "payouts")]+#[instrument(skip_all)]+pub async fn construct_payout_router_data<'a, F>(+ state: &'a AppState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ _request: &api_models::payouts::PayoutRequest,+ payout_data: &mut PayoutData,+) -> RouterResult<types::PayoutsRouterData<F>> {+ let (business_country, _) = helpers::get_business_details(+ payout_data.payout_attempt.business_country,+ payout_data.payout_attempt.business_label.as_ref(),+ merchant_account,+ )?;+ let merchant_connector_account = get_mca_for_payout(+ state,+ connector_id,+ merchant_account,+ key_store,+ payout_data,+ )+ .await?;+ payout_data.merchant_connector_account = Some(merchant_connector_account.clone());+ let connector_auth_type: types::ConnectorAuthType = merchant_connector_account+ .get_connector_account_details()+ .parse_value("ConnectorAuthType")+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let billing = payout_data.billing_address.to_owned();++ let address = PaymentAddress {+ shipping: None,+ billing: billing.map(|a| {+ let phone_details = api_models::payments::PhoneDetails {+ number: a.phone_number.clone().map(Encryptable::into_inner),+ country_code: a.country_code.to_owned(),+ };+ let address_details = api_models::payments::AddressDetails {+ city: a.city.to_owned(),+ country: a.country.to_owned(),+ line1: a.line1.clone().map(Encryptable::into_inner),+ line2: a.line2.clone().map(Encryptable::into_inner),+ line3: a.line3.clone().map(Encryptable::into_inner),+ zip: a.zip.clone().map(Encryptable::into_inner),+ first_name: a.first_name.clone().map(Encryptable::into_inner),+ last_name: a.last_name.clone().map(Encryptable::into_inner),+ state: a.state.map(Encryptable::into_inner),+ };++ api_models::payments::Address {+ phone: Some(phone_details),+ address: Some(address_details),+ }+ }),+ };++ let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();+ let payouts = &payout_data.payouts;+ let payout_attempt = &payout_data.payout_attempt;+ let customer_details = &payout_data.customer_details;+ let connector_customer_id = customer_details+ .as_ref()+ .and_then(|c| c.connector_customer.as_ref())+ .and_then(|cc| cc.get("id"))+ .and_then(|id| serde_json::from_value::<String>(id.to_owned()).ok());+ let router_data = types::RouterData {+ flow: PhantomData,+ merchant_id: merchant_account.merchant_id.to_owned(),+ customer_id: None,+ connector_customer: connector_customer_id,+ connector: connector_id.to_string(),+ payment_id: "".to_string(),+ attempt_id: "".to_string(),+ status: enums::AttemptStatus::Failure,+ payment_method: enums::PaymentMethod::default(),+ connector_auth_type,+ description: None,+ return_url: payouts.return_url.to_owned(),+ payment_method_id: None,+ address,+ auth_type: enums::AuthenticationType::default(),+ connector_meta_data: merchant_connector_account.get_metadata(),+ amount_captured: None,+ request: types::PayoutsData {+ payout_id: payouts.payout_id.to_owned(),+ amount: payouts.amount,+ connector_payout_id: Some(payout_attempt.connector_payout_id.to_owned()),+ destination_currency: payouts.destination_currency,+ source_currency: payouts.source_currency,+ entity_type: payouts.entity_type.to_owned(),+ payout_type: payouts.payout_type,+ country_code: business_country,+ customer_details: customer_details+ .to_owned()+ .map(|c| payments::CustomerDetails {+ customer_id: Some(c.customer_id),+ name: c.name.map(Encryptable::into_inner),+ email: c.email.map(Email::from),+ phone: c.phone.map(Encryptable::into_inner),+ phone_country_code: c.phone_country_code,+ }),+ },+ response: Ok(types::PayoutsResponseData::default()),+ access_token: None,+ session_token: None,+ reference_id: None,+ payment_method_token: None,+ recurring_mandate_payment_data: None,+ preprocessing_id: None,+ connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW+ .to_string(),+ payout_method_data: payout_data.payout_method_data.to_owned(),+ quote_id: None,+ test_mode,+ };++ Ok(router_data)+}+#[instrument(skip_all)]#[allow(clippy::too_many_arguments)]pub async fn construct_refund_router_data<'a, F>(@@ -120,6 +282,10 @@ pub async fn construct_refund_router_data<'a, F>(&merchant_account.merchant_id,payment_attempt,),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode,};@@ -137,6 +303,16 @@ pub fn get_or_generate_id(.map_or(Ok(generate_id(consts::ID_LENGTH, prefix)), validate_id)}+pub fn get_or_generate_uuid(+ key: &str,+ provided_id: Option<&String>,+) -> Result<String, errors::ApiErrorResponse> {+ let validate_id = |id: String| validate_uuid(id, key);+ provided_id+ .cloned()+ .map_or(Ok(generate_uuid()), validate_id)+}+fn invalid_id_format_error(key: &str) -> errors::ApiErrorResponse {errors::ApiErrorResponse::InvalidDataFormat {field_name: key.to_string(),@@ -155,6 +331,13 @@ pub fn validate_id(id: String, key: &str) -> Result<String, errors::ApiErrorResp}}+pub fn validate_uuid(uuid: String, key: &str) -> Result<String, errors::ApiErrorResponse> {+ match (Uuid::parse_str(&uuid), uuid.len() > consts::MAX_ID_LENGTH) {+ (Ok(_), false) => Ok(uuid),+ (_, _) => Err(invalid_id_format_error(key)),+ }+}+#[cfg(test)]mod tests {use super::*;@@ -315,6 +498,10 @@ pub async fn construct_accept_dispute_router_data<'a>(&merchant_account.merchant_id,payment_attempt,),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode,};Ok(router_data)@@ -384,6 +571,10 @@ pub async fn construct_submit_evidence_router_data<'a>(&merchant_account.merchant_id,payment_attempt,),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode,};Ok(router_data)@@ -454,6 +645,10 @@ pub async fn construct_upload_file_router_data<'a>(&merchant_account.merchant_id,payment_attempt,),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode,};Ok(router_data)@@ -526,6 +721,10 @@ pub async fn construct_defend_dispute_router_data<'a>(&merchant_account.merchant_id,payment_attempt,),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode,};Ok(router_data)@@ -593,6 +792,10 @@ pub async fn construct_retrieve_file_router_data<'a>(preprocessing_id: None,connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW.to_string(),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode,};Ok(router_data)diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex 0bc43e6d56..304e2a0fc7 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -17,6 +17,8 @@ pub mod merchant_key_store;pub mod payment_attempt;pub mod payment_intent;pub mod payment_method;+pub mod payout_attempt;+pub mod payouts;pub mod process_tracker;pub mod queue;pub mod refund;@@ -60,6 +62,8 @@ pub trait StorageInterface:+ payment_attempt::PaymentAttemptInterface+ payment_intent::PaymentIntentInterface+ payment_method::PaymentMethodInterface+ + payout_attempt::PayoutAttemptInterface+ + payouts::PayoutsInterface+ process_tracker::ProcessTrackerInterface+ queue::QueueInterface+ refund::RefundInterfacediff --git a/crates/router/src/db/locker_mock_up.rs b/crates/router/src/db/locker_mock_up.rsindex a0c88fd0d4..96c74d8b8d 100644--- a/crates/router/src/db/locker_mock_up.rs+++ b/crates/router/src/db/locker_mock_up.rs@@ -100,6 +100,7 @@ impl LockerMockUpInterface for MockDb {duplicate: None,card_cvc: new.card_cvc,payment_method_id: new.payment_method_id,+ enc_card_data: new.enc_card_data,};locked_lockers.push(created_locker.clone());@@ -153,6 +154,7 @@ mod tests {payment_method_id: Some("payment_method_id".into()),customer_id: Some(locker_ids.customer_id),nickname: Some("card_holder_nickname".into()),+ enc_card_data: Some("enc_card_data".into()),}}diff --git a/crates/router/src/db/payout_attempt.rs b/crates/router/src/db/payout_attempt.rsnew file mode 100644index 0000000000..d95037ace9--- /dev/null+++ b/crates/router/src/db/payout_attempt.rs@@ -0,0 +1,100 @@+use error_stack::IntoReport;++use super::{MockDb, Store};+use crate::{+ connection,+ core::errors::{self, CustomResult},+ types::storage,+};++#[async_trait::async_trait]+pub trait PayoutAttemptInterface {+ async fn find_payout_attempt_by_merchant_id_payout_id(+ &self,+ _merchant_id: &str,+ _payout_id: &str,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError>;++ async fn update_payout_attempt_by_merchant_id_payout_id(+ &self,+ _merchant_id: &str,+ _payout_id: &str,+ _payout: storage::PayoutAttemptUpdate,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError>;++ async fn insert_payout_attempt(+ &self,+ _payout: storage::PayoutAttemptNew,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError>;+}++#[async_trait::async_trait]+impl PayoutAttemptInterface for Store {+ async fn find_payout_attempt_by_merchant_id_payout_id(+ &self,+ merchant_id: &str,+ payout_id: &str,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage::PayoutAttempt::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id)+ .await+ .map_err(Into::into)+ .into_report()+ }++ async fn update_payout_attempt_by_merchant_id_payout_id(+ &self,+ merchant_id: &str,+ payout_id: &str,+ payout: storage::PayoutAttemptUpdate,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ storage::PayoutAttempt::update_by_merchant_id_payout_id(+ &conn,+ merchant_id,+ payout_id,+ payout,+ )+ .await+ .map_err(Into::into)+ .into_report()+ }++ async fn insert_payout_attempt(+ &self,+ payout: storage::PayoutAttemptNew,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ payout.insert(&conn).await.map_err(Into::into).into_report()+ }+}++#[async_trait::async_trait]+impl PayoutAttemptInterface for MockDb {+ async fn find_payout_attempt_by_merchant_id_payout_id(+ &self,+ _merchant_id: &str,+ _payout_id: &str,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {+ // TODO: Implement function for `MockDb`+ Err(errors::StorageError::MockDbError)?+ }++ async fn update_payout_attempt_by_merchant_id_payout_id(+ &self,+ _merchant_id: &str,+ _payout_id: &str,+ _payout: storage::PayoutAttemptUpdate,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {+ // TODO: Implement function for `MockDb`+ Err(errors::StorageError::MockDbError)?+ }++ async fn insert_payout_attempt(+ &self,+ _payout: storage::PayoutAttemptNew,+ ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {+ // TODO: Implement function for `MockDb`+ Err(errors::StorageError::MockDbError)?+ }+}diff --git a/crates/router/src/db/payouts.rs b/crates/router/src/db/payouts.rsnew file mode 100644index 0000000000..cd9c50217b--- /dev/null+++ b/crates/router/src/db/payouts.rs@@ -0,0 +1,95 @@+use error_stack::IntoReport;++use super::{MockDb, Store};+use crate::{+ connection,+ core::errors::{self, CustomResult},+ types::storage,+};++#[async_trait::async_trait]+pub trait PayoutsInterface {+ async fn find_payout_by_merchant_id_payout_id(+ &self,+ _merchant_id: &str,+ _payout_id: &str,+ ) -> CustomResult<storage::Payouts, errors::StorageError>;++ async fn update_payout_by_merchant_id_payout_id(+ &self,+ _merchant_id: &str,+ _payout_id: &str,+ _payout: storage::PayoutsUpdate,+ ) -> CustomResult<storage::Payouts, errors::StorageError>;++ async fn insert_payout(+ &self,+ _payout: storage::PayoutsNew,+ ) -> CustomResult<storage::Payouts, errors::StorageError>;+}++#[async_trait::async_trait]+impl PayoutsInterface for Store {+ async fn find_payout_by_merchant_id_payout_id(+ &self,+ merchant_id: &str,+ payout_id: &str,+ ) -> CustomResult<storage::Payouts, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage::Payouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id)+ .await+ .map_err(Into::into)+ .into_report()+ }++ async fn update_payout_by_merchant_id_payout_id(+ &self,+ merchant_id: &str,+ payout_id: &str,+ payout: storage::PayoutsUpdate,+ ) -> CustomResult<storage::Payouts, errors::StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ storage::Payouts::update_by_merchant_id_payout_id(&conn, merchant_id, payout_id, payout)+ .await+ .map_err(Into::into)+ .into_report()+ }++ async fn insert_payout(+ &self,+ payout: storage::PayoutsNew,+ ) -> CustomResult<storage::Payouts, errors::StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ payout.insert(&conn).await.map_err(Into::into).into_report()+ }+}++#[async_trait::async_trait]+impl PayoutsInterface for MockDb {+ async fn find_payout_by_merchant_id_payout_id(+ &self,+ _merchant_id: &str,+ _payout_id: &str,+ ) -> CustomResult<storage::Payouts, errors::StorageError> {+ // TODO: Implement function for `MockDb`+ Err(errors::StorageError::MockDbError)?+ }++ async fn update_payout_by_merchant_id_payout_id(+ &self,+ _merchant_id: &str,+ _payout_id: &str,+ _payout: storage::PayoutsUpdate,+ ) -> CustomResult<storage::Payouts, errors::StorageError> {+ // TODO: Implement function for `MockDb`+ Err(errors::StorageError::MockDbError)?+ }++ async fn insert_payout(+ &self,+ _payout: storage::PayoutsNew,+ ) -> CustomResult<storage::Payouts, errors::StorageError> {+ // TODO: Implement function for `MockDb`+ Err(errors::StorageError::MockDbError)?+ }+}diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex ad3ee4c42d..b0087b0522 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -113,7 +113,6 @@ pub fn mk_app(.service(routes::Customers::server(state.clone())).service(routes::Configs::server(state.clone())).service(routes::Refunds::server(state.clone()))- .service(routes::Payouts::server(state.clone())).service(routes::MerchantConnectorAccount::server(state.clone())).service(routes::Mandates::server(state.clone()));}@@ -135,6 +134,11 @@ pub fn mk_app(.service(routes::Disputes::server(state.clone()));}+ #[cfg(feature = "payouts")]+ {+ server_app = server_app.service(routes::Payouts::server(state.clone()));+ }+#[cfg(feature = "stripe")]{server_app = server_app.service(routes::StripeApis::server(state.clone()));diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rsindex f692ed6c52..ceb2897538 100644--- a/crates/router/src/openapi.rs+++ b/crates/router/src/openapi.rs@@ -59,6 +59,7 @@ Never share your secret api keys. Keep them guarded and secure.(name = "Payment Methods", description = "Create and manage payment methods of customers"),(name = "Disputes", description = "Manage disputes"),// (name = "API Key", description = "Create and manage API Keys"),+ (name = "Payouts", description = "Create and manage payouts"),),paths(crate::routes::refunds::refunds_create,@@ -105,6 +106,11 @@ Never share your secret api keys. Keep them guarded and secure.// crate::routes::api_keys::api_key_list,crate::routes::disputes::retrieve_disputes_list,crate::routes::disputes::retrieve_dispute,+ crate::routes::payouts::payouts_create,+ crate::routes::payouts::payouts_cancel,+ crate::routes::payouts::payouts_fulfill,+ crate::routes::payouts::payouts_retrieve,+ crate::routes::payouts::payouts_update,),components(schemas(crate::types::api::refunds::RefundRequest,@@ -136,6 +142,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::enums::PaymentMethod,api_models::enums::PaymentMethodType,api_models::enums::ConnectorType,+ api_models::enums::PayoutConnectors,api_models::enums::Currency,api_models::enums::IntentStatus,api_models::enums::CaptureMethod,@@ -277,6 +284,22 @@ Never share your secret api keys. Keep them guarded and secure.api_models::mandates::MandateCardDetails,api_models::ephemeral_key::EphemeralKeyCreateResponse,api_models::payments::CustomerDetails,+ api_models::payouts::PayoutCreateRequest,+ api_models::payments::Address,+ api_models::payouts::Card,+ api_models::payouts::AchBankTransfer,+ api_models::payouts::BacsBankTransfer,+ api_models::payouts::SepaBankTransfer,+ api_models::payouts::PayoutCreateResponse,+ api_models::payouts::PayoutRetrieveBody,+ api_models::payouts::PayoutRetrieveRequest,+ api_models::payouts::PayoutActionRequest,+ api_models::payouts::PayoutRequest,+ api_models::payouts::PayoutMethodData,+ api_models::payouts::Bank,+ api_models::enums::PayoutEntityType,+ api_models::enums::PayoutStatus,+ api_models::enums::PayoutType,crate::types::api::admin::MerchantAccountResponse,crate::types::api::admin::MerchantConnectorId,crate::types::api::admin::MerchantDetails,diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rsindex 8596be380d..aa9da13aa5 100644--- a/crates/router/src/routes.rs+++ b/crates/router/src/routes.rs@@ -15,16 +15,19 @@ pub mod mandates;pub mod metrics;pub mod payment_methods;pub mod payments;+#[cfg(feature = "payouts")]pub mod payouts;pub mod refunds;pub mod webhooks;#[cfg(feature = "dummy_connector")]pub use self::app::DummyConnector;+#[cfg(feature = "payouts")]+pub use self::app::Payouts;pub use self::app::{ApiKeys, AppState, Cache, Cards, Configs, Customers, Disputes, EphemeralKey, Files, Health,- Mandates, MerchantAccount, MerchantConnectorAccount, PaymentMethods, Payments, Payouts,- Refunds, Webhooks,+ Mandates, MerchantAccount, MerchantConnectorAccount, PaymentMethods, Payments, Refunds,+ Webhooks,};#[cfg(feature = "stripe")]pub use super::compatibility::stripe::StripeApis;diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 63295353fc..75d0ed2fba 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -5,11 +5,13 @@ use tokio::sync::oneshot;#[cfg(feature = "dummy_connector")]use super::dummy_connector::*;+#[cfg(feature = "payouts")]+use super::payouts::*;#[cfg(feature = "olap")]use super::{admin::*, api_keys::*, disputes::*, files::*};use super::{cache::*, health::*};#[cfg(any(feature = "olap", feature = "oltp"))]-use super::{configs::*, customers::*, mandates::*, payments::*, payouts::*, refunds::*};+use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*};#[cfg(feature = "oltp")]use super::{ephemeral_key::*, payment_methods::*, webhooks::*};#[cfg(feature = "kms")]@@ -268,28 +270,22 @@ impl Refunds {}}+#[cfg(feature = "payouts")]pub struct Payouts;-#[cfg(any(feature = "olap", feature = "oltp"))]+#[cfg(feature = "payouts")]impl Payouts {pub fn server(state: AppState) -> Scope {- let mut route = web::scope("/payouts").app_data(web::Data::new(state));-- #[cfg(feature = "olap")]- {- route =- route.service(web::resource("/accounts").route(web::get().to(payouts_accounts)));- }- #[cfg(feature = "oltp")]- {- route = route- .service(web::resource("/create").route(web::post().to(payouts_create)))- .service(web::resource("/retrieve").route(web::get().to(payouts_retrieve)))- .service(web::resource("/update").route(web::post().to(payouts_update)))- .service(web::resource("/reverse").route(web::post().to(payouts_reverse)))- .service(web::resource("/cancel").route(web::post().to(payouts_cancel)));- }+ let route = web::scope("/payouts").app_data(web::Data::new(state));route+ .service(web::resource("/create").route(web::post().to(payouts_create)))+ .service(web::resource("/{payout_id}/cancel").route(web::post().to(payouts_cancel)))+ .service(web::resource("/{payout_id}/fulfill").route(web::post().to(payouts_fulfill)))+ .service(+ web::resource("/{payout_id}")+ .route(web::get().to(payouts_retrieve))+ .route(web::put().to(payouts_update)),+ )}}diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rsindex 844c47837a..987866acb4 100644--- a/crates/router/src/routes/payouts.rs+++ b/crates/router/src/routes/payouts.rs@@ -1,42 +1,200 @@use actix_web::{body::{BoxBody, MessageBody},- HttpResponse, Responder,+ web, HttpRequest, HttpResponse, Responder,};use router_env::{instrument, tracing, Flow};+use super::app::AppState;+use crate::services::{api, authentication as auth};+#[cfg(feature = "payouts")]+use crate::{core::payouts::*, types::api::payouts as payout_types};++/// Payouts - Create+#[cfg(feature = "payouts")]+#[utoipa::path(+ post,+ path = "/payouts/create",+ request_body=PayoutCreateRequest,+ responses(+ (status = 200, description = "Payout created", body = PayoutCreateResponse),+ (status = 400, description = "Missing Mandatory fields")+ ),+ tag = "Payouts",+ operation_id = "Create a Payout",+ security(("api_key" = []))+)]#[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))]-// #[post("/create")]-pub async fn payouts_create() -> impl Responder {- let _flow = Flow::PayoutsCreate;- http_response("create")+pub async fn payouts_create(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<payout_types::PayoutCreateRequest>,+) -> HttpResponse {+ let flow = Flow::PayoutsCreate;+ api::server_wrap(+ flow,+ state.get_ref(),+ &req,+ json_payload.into_inner(),+ |state, auth, req| payouts_create_core(state, auth.merchant_account, auth.key_store, req),+ &auth::ApiKeyAuth,+ )+ .await}+/// Payouts - Retrieve+#[cfg(feature = "payouts")]+#[utoipa::path(+ get,+ path = "/payouts/{payout_id}",+ params(+ ("payout_id" = String, Path, description = "The identifier for payout]")+ ),+ responses(+ (status = 200, description = "Payout retrieved", body = PayoutCreateResponse),+ (status = 404, description = "Payout does not exist in our records")+ ),+ tag = "Payouts",+ operation_id = "Retrieve a Payout",+ security(("api_key" = []))+)]#[instrument(skip_all, fields(flow = ?Flow::PayoutsRetrieve))]-// #[get("/retrieve")]-pub async fn payouts_retrieve() -> impl Responder {- let _flow = Flow::PayoutsRetrieve;- http_response("retrieve")+pub async fn payouts_retrieve(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<String>,+ query_params: web::Query<payout_types::PayoutRetrieveBody>,+) -> HttpResponse {+ let payout_retrieve_request = payout_types::PayoutRetrieveRequest {+ payout_id: path.into_inner(),+ force_sync: query_params.force_sync,+ };+ let flow = Flow::PayoutsRetrieve;+ api::server_wrap(+ flow,+ state.get_ref(),+ &req,+ payout_retrieve_request,+ |state, auth, req| payouts_retrieve_core(state, auth.merchant_account, auth.key_store, req),+ &auth::ApiKeyAuth,+ )+ .await}+/// Payouts - Update+#[cfg(feature = "payouts")]+#[utoipa::path(+ post,+ path = "/payouts/{payout_id}",+ params(+ ("payout_id" = String, Path, description = "The identifier for payout]")+ ),+ request_body=PayoutCreateRequest,+ responses(+ (status = 200, description = "Payout updated", body = PayoutCreateResponse),+ (status = 400, description = "Missing Mandatory fields")+ ),+ tag = "Payouts",+ operation_id = "Update a Payout",+ security(("api_key" = []))+)]#[instrument(skip_all, fields(flow = ?Flow::PayoutsUpdate))]-// #[post("/update")]-pub async fn payouts_update() -> impl Responder {- let _flow = Flow::PayoutsUpdate;- http_response("update")+pub async fn payouts_update(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<String>,+ json_payload: web::Json<payout_types::PayoutCreateRequest>,+) -> HttpResponse {+ let flow = Flow::PayoutsUpdate;+ let payout_id = path.into_inner();+ let mut payout_update_payload = json_payload.into_inner();+ payout_update_payload.payout_id = Some(payout_id);+ api::server_wrap(+ flow,+ state.get_ref(),+ &req,+ payout_update_payload,+ |state, auth, req| payouts_update_core(state, auth.merchant_account, auth.key_store, req),+ &auth::ApiKeyAuth,+ )+ .await}-#[instrument(skip_all, fields(flow = ?Flow::PayoutsReverse))]-// #[post("/reverse")]-pub async fn payouts_reverse() -> impl Responder {- let _flow = Flow::PayoutsReverse;- http_response("reverse")+/// Payouts - Cancel+#[cfg(feature = "payouts")]+#[utoipa::path(+ post,+ path = "/payouts/{payout_id}/cancel",+ params(+ ("payout_id" = String, Path, description = "The identifier for payout")+ ),+ request_body=PayoutActionRequest,+ responses(+ (status = 200, description = "Payout cancelled", body = PayoutCreateResponse),+ (status = 400, description = "Missing Mandatory fields")+ ),+ tag = "Payouts",+ operation_id = "Cancel a Payout",+ security(("api_key" = []))+)]+#[instrument(skip_all, fields(flow = ?Flow::PayoutsCancel))]+pub async fn payouts_cancel(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<payout_types::PayoutActionRequest>,+ path: web::Path<String>,+) -> HttpResponse {+ let flow = Flow::PayoutsCancel;+ let mut payload = json_payload.into_inner();+ payload.payout_id = path.into_inner();++ api::server_wrap(+ flow,+ state.get_ref(),+ &req,+ payload,+ |state, auth, req| payouts_cancel_core(state, auth.merchant_account, auth.key_store, req),+ &auth::ApiKeyAuth,+ )+ .await}-#[instrument(skip_all, fields(flow = ?Flow::PayoutsCancel))]-// #[post("/cancel")]-pub async fn payouts_cancel() -> impl Responder {- let _flow = Flow::PayoutsCancel;- http_response("cancel")+/// Payouts - Fulfill+#[cfg(feature = "payouts")]+#[utoipa::path(+ post,+ path = "/payouts/{payout_id}/fulfill",+ params(+ ("payout_id" = String, Path, description = "The identifier for payout")+ ),+ request_body=PayoutActionRequest,+ responses(+ (status = 200, description = "Payout fulfilled", body = PayoutCreateResponse),+ (status = 400, description = "Missing Mandatory fields")+ ),+ tag = "Payouts",+ operation_id = "Fulfill a Payout",+ security(("api_key" = []))+)]+#[instrument(skip_all, fields(flow = ?Flow::PayoutsFulfill))]+pub async fn payouts_fulfill(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<payout_types::PayoutActionRequest>,+ path: web::Path<String>,+) -> HttpResponse {+ let flow = Flow::PayoutsFulfill;+ let mut payload = json_payload.into_inner();+ payload.payout_id = path.into_inner();++ api::server_wrap(+ flow,+ state.get_ref(),+ &req,+ payload,+ |state, auth, req| payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req),+ &auth::ApiKeyAuth,+ )+ .await}#[instrument(skip_all, fields(flow = ?Flow::PayoutsAccounts))]diff --git a/crates/router/src/types.rs b/crates/router/src/types.rsindex 23142a7011..f78a419cd9 100644--- a/crates/router/src/types.rs+++ b/crates/router/src/types.rs@@ -13,13 +13,18 @@ pub mod transformers;use std::marker::PhantomData;-pub use api_models::enums::Connector;+pub use api_models::{+ enums::{Connector, PayoutConnectors},+ payouts as payout_types,+};use common_utils::{pii, pii::Email};use error_stack::{IntoReport, ResultExt};use masking::Secret;use self::{api::payments, storage::enums as storage_enums};-pub use crate::core::payments::PaymentAddress;+pub use crate::core::payments::{CustomerDetails, PaymentAddress};+#[cfg(feature = "payouts")]+use crate::core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW;use crate::{core::{errors, payments::RecurringMandatePaymentData},services,@@ -129,6 +134,25 @@ pub type RefundExecuteType =pub type RefundSyncType =dyn services::ConnectorIntegration<api::RSync, RefundsData, RefundsResponseData>;+#[cfg(feature = "payouts")]+pub type PayoutCancelType =+ dyn services::ConnectorIntegration<api::PoCancel, PayoutsData, PayoutsResponseData>;+#[cfg(feature = "payouts")]+pub type PayoutCreateType =+ dyn services::ConnectorIntegration<api::PoCreate, PayoutsData, PayoutsResponseData>;+#[cfg(feature = "payouts")]+pub type PayoutEligibilityType =+ dyn services::ConnectorIntegration<api::PoEligibility, PayoutsData, PayoutsResponseData>;+#[cfg(feature = "payouts")]+pub type PayoutFulfillType =+ dyn services::ConnectorIntegration<api::PoFulfill, PayoutsData, PayoutsResponseData>;+#[cfg(feature = "payouts")]+pub type PayoutRecipientType =+ dyn services::ConnectorIntegration<api::PoRecipient, PayoutsData, PayoutsResponseData>;+#[cfg(feature = "payouts")]+pub type PayoutQuoteType =+ dyn services::ConnectorIntegration<api::PoQuote, PayoutsData, PayoutsResponseData>;+pub type RefreshTokenType =dyn services::ConnectorIntegration<api::AccessTokenAuth, AccessTokenRequestData, AccessToken>;@@ -175,6 +199,13 @@ pub type RetrieveFileRouterData =pub type DefendDisputeRouterData =RouterData<api::Defend, DefendDisputeRequestData, DefendDisputeResponse>;+#[cfg(feature = "payouts")]+pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;++#[cfg(feature = "payouts")]+pub type PayoutsResponseRouterData<F, R> =+ ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;+#[derive(Debug, Clone)]pub struct RouterData<Flow, Request, Response> {pub flow: PhantomData<Flow>,@@ -211,9 +242,46 @@ pub struct RouterData<Flow, Request, Response> {/// Contains a reference ID that should be sent in the connector requestpub connector_request_reference_id: String,++ #[cfg(feature = "payouts")]+ /// Contains payout method data+ pub payout_method_data: Option<api::PayoutMethodData>,++ #[cfg(feature = "payouts")]+ /// Contains payout method data+ pub quote_id: Option<String>,+pub test_mode: Option<bool>,}+#[cfg(feature = "payouts")]+#[derive(Debug, Clone)]+pub struct PayoutsData {+ pub payout_id: String,+ pub amount: i64,+ pub connector_payout_id: Option<String>,+ pub destination_currency: storage_enums::Currency,+ pub source_currency: storage_enums::Currency,+ pub payout_type: storage_enums::PayoutType,+ pub entity_type: storage_enums::PayoutEntityType,+ pub country_code: storage_enums::CountryAlpha2,+ pub customer_details: Option<CustomerDetails>,+}++#[cfg(feature = "payouts")]+#[derive(Clone, Debug, Default)]+pub struct PayoutsResponseData {+ pub status: Option<storage_enums::PayoutStatus>,+ pub connector_payout_id: String,+ pub payout_eligible: Option<bool>,+}++#[derive(Clone, Debug, Default)]+pub struct PayoutsFulfillResponseData {+ pub status: Option<storage_enums::PayoutStatus>,+ pub reference_id: Option<String>,+}+#[derive(Debug, Clone)]pub struct PaymentsAuthorizeData {pub payment_method_data: payments::PaymentMethodData,@@ -671,7 +739,7 @@ pub struct Response {pub status_code: u16,}-#[derive(Clone, Debug)]+#[derive(Clone, Debug, serde::Serialize)]pub struct ErrorResponse {pub code: String,pub message: String,@@ -826,6 +894,10 @@ impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)>connector_customer: data.connector_customer.clone(),recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(),connector_request_reference_id: data.connector_request_reference_id.clone(),+ #[cfg(feature = "payouts")]+ payout_method_data: data.payout_method_data.clone(),+ #[cfg(feature = "payouts")]+ quote_id: data.quote_id.clone(),test_mode: data.test_mode,}}@@ -850,3 +922,53 @@ impl RequestBody {request_body.0}}++#[cfg(feature = "payouts")]+impl<F1, F2>+ From<(+ &&mut RouterData<F1, PayoutsData, PayoutsResponseData>,+ PayoutsData,+ )> for RouterData<F2, PayoutsData, PayoutsResponseData>+{+ fn from(+ item: (+ &&mut RouterData<F1, PayoutsData, PayoutsResponseData>,+ PayoutsData,+ ),+ ) -> Self {+ let data = item.0;+ let request = item.1;+ Self {+ flow: PhantomData,+ request,+ merchant_id: data.merchant_id.clone(),+ connector: data.connector.clone(),+ attempt_id: data.attempt_id.clone(),+ status: data.status,+ payment_method: data.payment_method,+ connector_auth_type: data.connector_auth_type.clone(),+ description: data.description.clone(),+ return_url: data.return_url.clone(),+ address: data.address.clone(),+ auth_type: data.auth_type,+ connector_meta_data: data.connector_meta_data.clone(),+ amount_captured: data.amount_captured,+ access_token: data.access_token.clone(),+ response: data.response.clone(),+ payment_method_id: data.payment_method_id.clone(),+ payment_id: data.payment_id.clone(),+ session_token: data.session_token.clone(),+ reference_id: data.reference_id.clone(),+ customer_id: data.customer_id.clone(),+ payment_method_token: None,+ recurring_mandate_payment_data: None,+ preprocessing_id: None,+ connector_customer: data.connector_customer.clone(),+ connector_request_reference_id:+ IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW.to_string(),+ payout_method_data: data.payout_method_data.clone(),+ quote_id: data.quote_id.clone(),+ test_mode: data.test_mode,+ }+ }+}diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rsindex 9d496b8d14..049da56aea 100644--- a/crates/router/src/types/api.rs+++ b/crates/router/src/types/api.rs@@ -9,6 +9,7 @@ pub mod files;pub mod mandates;pub mod payment_methods;pub mod payments;+pub mod payouts;pub mod refunds;pub mod webhooks;@@ -18,7 +19,7 @@ use error_stack::{report, IntoReport, ResultExt};pub use self::{admin::*, api_keys::*, configs::*, customers::*, disputes::*, files::*, payment_methods::*,- payments::*, refunds::*, webhooks::*,+ payments::*, payouts::*, refunds::*, webhooks::*,};use super::ErrorResponse;use crate::{@@ -111,6 +112,7 @@ pub trait Connector:+ Dispute+ FileUpload+ ConnectorTransactionId+ + Payouts{}@@ -128,7 +130,8 @@ impl<+ ConnectorAccessToken+ Dispute+ FileUpload- + ConnectorTransactionId,+ + ConnectorTransactionId+ + Payouts,> Connector for T{}@@ -151,6 +154,22 @@ pub struct ConnectorData {pub get_token: GetToken,}+#[cfg(feature = "payouts")]+#[derive(Clone)]+pub struct PayoutConnectorData {+ pub connector: BoxedConnector,+ pub connector_name: api_enums::PayoutConnectors,+ pub get_token: GetToken,+}++#[cfg(feature = "payouts")]+#[derive(Clone)]+pub struct PayoutSessionConnectorData {+ pub payment_method_type: api_enums::PaymentMethodType,+ pub connector: PayoutConnectorData,+ pub business_sub_label: Option<String>,+}+#[derive(Clone)]pub struct SessionConnectorData {pub payment_method_type: api_enums::PaymentMethodType,@@ -164,18 +183,70 @@ pub enum ConnectorChoice {Decide,}+#[cfg(feature = "payouts")]+pub enum PayoutConnectorChoice {+ SessionMultiple(Vec<PayoutSessionConnectorData>),+ StraightThrough(serde_json::Value),+ Decide,+}+#[derive(Clone)]pub enum ConnectorCallType {Multiple(Vec<SessionConnectorData>),Single(ConnectorData),}+#[cfg(feature = "payouts")]+#[derive(Clone)]+pub enum PayoutConnectorCallType {+ Multiple(Vec<PayoutSessionConnectorData>),+ Single(PayoutConnectorData),+}+impl ConnectorCallType {pub fn is_single(&self) -> bool {matches!(self, Self::Single(_))}}+#[cfg(feature = "payouts")]+impl PayoutConnectorData {+ pub fn get_connector_by_name(+ connectors: &Connectors,+ name: &str,+ connector_type: GetToken,+ ) -> CustomResult<Self, errors::ApiErrorResponse> {+ let connector = Self::convert_connector(connectors, name)?;+ let connector_name = api_enums::PayoutConnectors::from_str(name)+ .into_report()+ .change_context(errors::ConnectorError::InvalidConnectorName)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!("unable to parse payout connector name {connector:?}")+ })?;+ Ok(Self {+ connector,+ connector_name,+ get_token: connector_type,+ })+ }++ fn convert_connector(+ _connectors: &Connectors,+ connector_name: &str,+ ) -> CustomResult<BoxedConnector, errors::ApiErrorResponse> {+ match enums::PayoutConnectors::from_str(connector_name) {+ Ok(name) => match name {+ enums::PayoutConnectors::Adyen => Ok(Box::new(&connector::Adyen)),+ enums::PayoutConnectors::Wise => Ok(Box::new(&connector::Wise)),+ },+ Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName)+ .attach_printable(format!("invalid payout connector name: {connector_name}")))+ .change_context(errors::ApiErrorResponse::InternalServerError),+ }+ }+}+impl ConnectorData {pub fn get_connector_by_name(connectors: &Connectors,@@ -248,6 +319,7 @@ impl ConnectorData {enums::Connector::Shift4 => Ok(Box::new(&connector::Shift4)),enums::Connector::Stax => Ok(Box::new(&connector::Stax)),enums::Connector::Stripe => Ok(Box::new(&connector::Stripe)),+ enums::Connector::Wise => Ok(Box::new(&connector::Wise)),enums::Connector::Worldline => Ok(Box::new(&connector::Worldline)),enums::Connector::Worldpay => Ok(Box::new(&connector::Worldpay)),enums::Connector::Multisafepay => Ok(Box::new(&connector::Multisafepay)),diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rsindex 4cc0b27736..c21e0790ff 100644--- a/crates/router/src/types/api/admin.rs+++ b/crates/router/src/types/api/admin.rs@@ -1,8 +1,9 @@pub use api_models::admin::{- MerchantAccountCreate, MerchantAccountDeleteResponse, MerchantAccountResponse,- MerchantAccountUpdate, MerchantConnectorCreate, MerchantConnectorDeleteResponse,- MerchantConnectorDetails, MerchantConnectorDetailsWrap, MerchantConnectorId,- MerchantConnectorResponse, MerchantDetails, MerchantId, PaymentMethodsEnabled,+ payout_routing_algorithm, MerchantAccountCreate, MerchantAccountDeleteResponse,+ MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate,+ MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap,+ MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId,+ PaymentMethodsEnabled, PayoutRoutingAlgorithm, PayoutStraightThroughAlgorithm,RoutingAlgorithm, StraightThroughAlgorithm, ToggleKVRequest, ToggleKVResponse, WebhookDetails,};use common_utils::ext_traits::ValueExt;@@ -34,6 +35,7 @@ impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse {primary_business_details,frm_routing_algorithm: item.frm_routing_algorithm,intent_fulfillment_time: item.intent_fulfillment_time,+ payout_routing_algorithm: item.payout_routing_algorithm,organization_id: item.organization_id,is_recon_enabled: item.is_recon_enabled,})diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rsindex e69de29bb2..dd118b0915 100644--- a/crates/router/src/types/api/payouts.rs+++ b/crates/router/src/types/api/payouts.rs@@ -0,0 +1,84 @@+pub use api_models::payouts::{+ AchBankTransfer, BacsBankTransfer, Bank as BankPayout, Card as CardPayout, PayoutActionRequest,+ PayoutCreateRequest, PayoutCreateResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody,+ PayoutRetrieveRequest, SepaBankTransfer,+};++#[cfg(feature = "payouts")]+use super::ConnectorCommon;+#[cfg(feature = "payouts")]+use crate::{services::api, types};++#[cfg(feature = "payouts")]+#[derive(Debug, Clone)]+pub struct PoCancel;++#[cfg(feature = "payouts")]+#[derive(Debug, Clone)]+pub struct PoCreate;++#[cfg(feature = "payouts")]+#[derive(Debug, Clone)]+pub struct PoEligibility;++#[cfg(feature = "payouts")]+#[derive(Debug, Clone)]+pub struct PoFulfill;++#[cfg(feature = "payouts")]+#[derive(Debug, Clone)]+pub struct PoQuote;++#[cfg(feature = "payouts")]+#[derive(Debug, Clone)]+pub struct PoRecipient;++#[cfg(feature = "payouts")]+pub trait PayoutCancel:+ api::ConnectorIntegration<PoCancel, types::PayoutsData, types::PayoutsResponseData>+{+}++#[cfg(feature = "payouts")]+pub trait PayoutCreate:+ api::ConnectorIntegration<PoCreate, types::PayoutsData, types::PayoutsResponseData>+{+}++#[cfg(feature = "payouts")]+pub trait PayoutEligibility:+ api::ConnectorIntegration<PoEligibility, types::PayoutsData, types::PayoutsResponseData>+{+}++#[cfg(feature = "payouts")]+pub trait PayoutFulfill:+ api::ConnectorIntegration<PoFulfill, types::PayoutsData, types::PayoutsResponseData>+{+}++#[cfg(feature = "payouts")]+pub trait PayoutQuote:+ api::ConnectorIntegration<PoQuote, types::PayoutsData, types::PayoutsResponseData>+{+}++#[cfg(feature = "payouts")]+pub trait PayoutRecipient:+ api::ConnectorIntegration<PoRecipient, types::PayoutsData, types::PayoutsResponseData>+{+}++#[cfg(feature = "payouts")]+pub trait Payouts:+ ConnectorCommon+ + PayoutCancel+ + PayoutCreate+ + PayoutEligibility+ + PayoutFulfill+ + PayoutQuote+ + PayoutRecipient+{+}+#[cfg(not(feature = "payouts"))]+pub trait Payouts {}diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rsindex a51a0a7c4a..f90f8da1f7 100644--- a/crates/router/src/types/domain/merchant_account.rs+++ b/crates/router/src/types/domain/merchant_account.rs@@ -36,6 +36,7 @@ pub struct MerchantAccount {pub created_at: time::PrimitiveDateTime,pub modified_at: time::PrimitiveDateTime,pub intent_fulfillment_time: Option<i64>,+ pub payout_routing_algorithm: Option<serde_json::Value>,pub organization_id: Option<String>,pub is_recon_enabled: bool,}@@ -60,6 +61,7 @@ pub enum MerchantAccountUpdate {primary_business_details: Option<serde_json::Value>,intent_fulfillment_time: Option<i64>,frm_routing_algorithm: Option<serde_json::Value>,+ payout_routing_algorithm: Option<serde_json::Value>,},StorageSchemeUpdate {storage_scheme: enums::MerchantStorageScheme,@@ -89,6 +91,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {primary_business_details,intent_fulfillment_time,frm_routing_algorithm,+ payout_routing_algorithm,} => Self {merchant_name: merchant_name.map(Encryption::from),merchant_details: merchant_details.map(Encryption::from),@@ -107,6 +110,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {primary_business_details,modified_at: Some(date_time::now()),intent_fulfillment_time,+ payout_routing_algorithm,..Default::default()},MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {@@ -151,6 +155,7 @@ impl super::behaviour::Conversion for MerchantAccount {modified_at: self.modified_at,intent_fulfillment_time: self.intent_fulfillment_time,frm_routing_algorithm: self.frm_routing_algorithm,+ payout_routing_algorithm: self.payout_routing_algorithm,organization_id: self.organization_id,is_recon_enabled: self.is_recon_enabled,})@@ -192,6 +197,7 @@ impl super::behaviour::Conversion for MerchantAccount {created_at: item.created_at,modified_at: item.modified_at,intent_fulfillment_time: item.intent_fulfillment_time,+ payout_routing_algorithm: item.payout_routing_algorithm,organization_id: item.organization_id,is_recon_enabled: item.is_recon_enabled,})@@ -224,6 +230,7 @@ impl super::behaviour::Conversion for MerchantAccount {modified_at: now,intent_fulfillment_time: self.intent_fulfillment_time,frm_routing_algorithm: self.frm_routing_algorithm,+ payout_routing_algorithm: self.payout_routing_algorithm,organization_id: self.organization_id,is_recon_enabled: self.is_recon_enabled,})diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rsindex 781bd495cb..396315b4c8 100644--- a/crates/router/src/types/storage.rs+++ b/crates/router/src/types/storage.rs@@ -16,6 +16,8 @@ pub mod merchant_connector_account;pub mod payment_attempt;pub mod payment_intent;pub mod payment_method;+pub mod payout_attempt;+pub mod payouts;pub mod process_tracker;pub mod reverse_lookup;@@ -29,5 +31,6 @@ pub use self::{address::*, api_keys::*, cards_info::*, configs::*, connector_response::*, customers::*,dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*,merchant_account::*, merchant_connector_account::*, payment_attempt::*, payment_intent::*,- payment_method::*, process_tracker::*, refund::*, reverse_lookup::*,+ payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, refund::*,+ reverse_lookup::*,};diff --git a/crates/router/src/types/storage/payout_attempt.rs b/crates/router/src/types/storage/payout_attempt.rsnew file mode 100644index 0000000000..966ec24bab--- /dev/null+++ b/crates/router/src/types/storage/payout_attempt.rs@@ -0,0 +1,9 @@+pub use diesel_models::payout_attempt::{+ PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,+};++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct PayoutRoutingData {+ pub routed_through: Option<String>,+ pub algorithm: Option<api_models::admin::PayoutStraightThroughAlgorithm>,+}diff --git a/crates/router/src/types/storage/payouts.rs b/crates/router/src/types/storage/payouts.rsnew file mode 100644index 0000000000..3d4ed9b843--- /dev/null+++ b/crates/router/src/types/storage/payouts.rs@@ -0,0 +1 @@+pub use diesel_models::payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal};diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex 6cd2182854..63948fe808 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -530,3 +530,31 @@ impl ForeignFrom<storage::PaymentAttempt> for api_models::payments::PaymentAttem}}}++impl ForeignFrom<api_models::payouts::Bank> for api_enums::PaymentMethodType {+ fn foreign_from(value: api_models::payouts::Bank) -> Self {+ match value {+ api_models::payouts::Bank::Ach(_) => Self::Ach,+ api_models::payouts::Bank::Bacs(_) => Self::Bacs,+ api_models::payouts::Bank::Sepa(_) => Self::Sepa,+ }+ }+}++impl ForeignFrom<api_models::payouts::PayoutMethodData> for api_enums::PaymentMethod {+ fn foreign_from(value: api_models::payouts::PayoutMethodData) -> Self {+ match value {+ api_models::payouts::PayoutMethodData::Bank(_) => Self::BankTransfer,+ api_models::payouts::PayoutMethodData::Card(_) => Self::Card,+ }+ }+}++impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod {+ fn foreign_from(value: api_models::enums::PayoutType) -> Self {+ match value {+ api_models::enums::PayoutType::Bank => Self::BankTransfer,+ api_models::enums::PayoutType::Card => Self::Card,+ }+ }+}diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex 06d1995329..371a8ca564 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -17,6 +17,7 @@ use image::Luma;use nanoid::nanoid;use qrcode;use serde::de::DeserializeOwned;+use uuid::Uuid;pub use self::ext_traits::{OptionExt, ValidateCall};use crate::{@@ -76,6 +77,11 @@ pub fn generate_id(length: usize, prefix: &str) -> String {format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS))}+#[inline]+pub fn generate_uuid() -> String {+ Uuid::new_v4().to_string()+}+pub trait ConnectorResponseExt: Sized {fn get_response(self) -> RouterResult<types::Response>;fn get_error_response(self) -> RouterResult<types::Response>;diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rsindex d34dfe063d..d82c3eff6f 100644--- a/crates/router/tests/connectors/aci.rs+++ b/crates/router/tests/connectors/aci.rs@@ -82,6 +82,10 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {recurring_mandate_payment_data: None,preprocessing_id: None,connector_request_reference_id: uuid::Uuid::new_v4().to_string(),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode: None,}}@@ -129,6 +133,10 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {recurring_mandate_payment_data: None,preprocessing_id: None,connector_request_reference_id: uuid::Uuid::new_v4().to_string(),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode: None,}}diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rsindex a5ab565772..886069e3c4 100644--- a/crates/router/tests/connectors/adyen.rs+++ b/crates/router/tests/connectors/adyen.rs@@ -22,6 +22,15 @@ impl utils::Connector for AdyenTest {}}+ fn get_payout_data(&self) -> Option<types::api::PayoutConnectorData> {+ use router::connector::Adyen;+ Some(types::api::PayoutConnectorData {+ connector: Box::new(&Adyen),+ connector_name: types::PayoutConnectors::Adyen,+ get_token: types::api::GetToken::Connector,+ })+ }+fn get_auth_token(&self) -> types::ConnectorAuthType {types::ConnectorAuthType::from(connector_auth::ConnectorAuthentication::new()@@ -42,12 +51,59 @@ impl AdyenTest {billing: Some(Address {address: Some(AddressDetails {country: Some(api_models::enums::CountryAlpha2::US),+ state: Some(Secret::new("California".to_string())),+ city: Some("San Francisco".to_string()),+ zip: Some(Secret::new("94122".to_string())),+ line1: Some(Secret::new("1467".to_string())),+ line2: Some(Secret::new("Harrison Street".to_string())),+ ..Default::default()+ }),+ phone: None,+ }),+ ..Default::default()+ }),+ ..Default::default()+ })+ }++ fn get_payout_info(payout_type: enums::PayoutType) -> Option<PaymentInfo> {+ Some(PaymentInfo {+ country: Some(api_models::enums::CountryAlpha2::NL),+ currency: Some(enums::Currency::EUR),+ address: Some(PaymentAddress {+ billing: Some(Address {+ address: Some(AddressDetails {+ country: Some(api_models::enums::CountryAlpha2::US),+ state: Some(Secret::new("California".to_string())),+ city: Some("San Francisco".to_string()),+ zip: Some(Secret::new("94122".to_string())),+ line1: Some(Secret::new("1467".to_string())),+ line2: Some(Secret::new("Harrison Street".to_string())),..Default::default()}),phone: None,}),..Default::default()}),+ payout_method_data: match payout_type {+ enums::PayoutType::Card => {+ Some(api::PayoutMethodData::Card(api::payouts::CardPayout {+ card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),+ expiry_month: Secret::new("3".to_string()),+ expiry_year: Secret::new("2030".to_string()),+ card_holder_name: Secret::new("John Doe".to_string()),+ }))+ }+ enums::PayoutType::Bank => Some(api::PayoutMethodData::Bank(+ api::payouts::BankPayout::Sepa(api::SepaBankTransfer {+ iban: "NL46TEST0136169112".to_string().into(),+ bic: Some("ABNANL2A".to_string().into()),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ }),+ )),+ },..Default::default()})}@@ -457,6 +513,83 @@ async fn should_fail_capture_for_invalid_payment() {);}+/******************** Payouts test cases ********************/+// Create SEPA payout+#[ignore]+#[cfg(feature = "payouts")]+#[actix_web::test]+async fn should_create_sepa_payout() {+ let payout_type = enums::PayoutType::Bank;+ let payout_info = AdyenTest::get_payout_info(payout_type);+ let response = CONNECTOR+ .create_payout(None, payout_type, payout_info)+ .await+ .expect("Payout bank creation response");+ assert_eq!(+ response.status.unwrap(),+ enums::PayoutStatus::RequiresFulfillment+ );+}++// Create and fulfill SEPA payout+#[ignore]+#[cfg(feature = "payouts")]+#[actix_web::test]+async fn should_create_and_fulfill_sepa_payout() {+ let payout_type = enums::PayoutType::Bank;+ let payout_info = AdyenTest::get_payout_info(payout_type);+ let response = CONNECTOR+ .create_and_fulfill_payout(None, payout_type, payout_info)+ .await+ .expect("Payout bank creation and fulfill response");+ assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success);+}++// Verifies if card is eligible for payout+#[ignore]+#[cfg(feature = "payouts")]+#[actix_web::test]+async fn should_verify_payout_eligibility() {+ let payout_type = enums::PayoutType::Card;+ let payout_info = AdyenTest::get_payout_info(payout_type);+ let response = CONNECTOR+ .verify_payout_eligibility(payout_type, payout_info)+ .await+ .expect("Payout eligibility response");+ assert_eq!(+ response.status.unwrap(),+ enums::PayoutStatus::RequiresFulfillment+ );+}++// Fulfills card payout+#[ignore]+#[cfg(feature = "payouts")]+#[actix_web::test]+async fn should_fulfill_card_payout() {+ let payout_type = enums::PayoutType::Card;+ let payout_info: Option<PaymentInfo> = AdyenTest::get_payout_info(payout_type);+ let response = CONNECTOR+ .fulfill_payout(None, payout_type, payout_info)+ .await+ .expect("Payout fulfill response");+ assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success);+}++// Cancels a created bank payout+#[ignore]+#[cfg(feature = "payouts")]+#[actix_web::test]+async fn should_create_and_cancel_created_payout() {+ let payout_type = enums::PayoutType::Bank;+ let payout_info = AdyenTest::get_payout_info(payout_type);+ let response = CONNECTOR+ .create_and_cancel_payout(None, payout_type, payout_info)+ .await+ .expect("Payout cancel response");+ assert_eq!(response.status.unwrap(), enums::PayoutStatus::Cancelled);+}+// Connector dependent test cases goes here// [#478]: add unit tests for non 3DS, wallets & webhooks in connector testsdiff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rsindex 5213e7466c..41b4b13377 100644--- a/crates/router/tests/connectors/main.rs+++ b/crates/router/tests/connectors/main.rs@@ -64,6 +64,7 @@ mod trustpay;mod trustpay_3ds_ui;mod tsys;mod utils;+mod wise;mod worldline;mod worldline_ui;mod worldpay;diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rsindex 9db03cdfff..91e9e0b881 100644--- a/crates/router/tests/connectors/payme.rs+++ b/crates/router/tests/connectors/payme.rs@@ -61,6 +61,9 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> {access_token: None,connector_meta_data: None,return_url: None,+ country: None,+ currency: None,+ payout_method_data: None,})}diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.tomlindex e5954e1c6c..84724ae9bc 100644--- a/crates/router/tests/connectors/sample_auth.toml+++ b/crates/router/tests/connectors/sample_auth.toml@@ -8,6 +8,7 @@ key1 = "MyEntityId"[adyen]api_key = "Bearer MyApiKey"key1 = "MerchantId"+api_secret = "Secondary key"[authorizedotnet]api_key = "MyMerchantName"@@ -120,6 +121,10 @@ key1 = "Business Identifier"[opayo]api_key="API Key"+[wise]+api_key = "API Key"+key1 = "Profile ID"+[automation_configs]hs_base_url="http://localhost:8080"hs_test_browser="firefox"diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rsindex afcb5e6120..2f7eae9fd9 100644--- a/crates/router/tests/connectors/utils.rs+++ b/crates/router/tests/connectors/utils.rs@@ -5,7 +5,7 @@ use error_stack::Report;use masking::Secret;use router::{configs::settings::Settings,- core::{errors, errors::ConnectorError, payments},+ core::{errors, errors::ConnectorError, payments, utils as core_utils},db::StorageImpl,routes, services,types::{self, api, storage::enums, AccessToken, PaymentAddress, RouterData},@@ -24,6 +24,9 @@ pub trait Connector {fn get_request_interval(&self) -> u64 {5}+ fn get_payout_data(&self) -> Option<types::api::PayoutConnectorData> {+ None+ }}#[derive(Debug, Default, Clone)]@@ -33,6 +36,9 @@ pub struct PaymentInfo {pub access_token: Option<AccessToken>,pub connector_meta_data: Option<serde_json::Value>,pub return_url: Option<String>,+ pub payout_method_data: Option<api::PayoutMethodData>,+ pub currency: Option<enums::Currency>,+ pub country: Option<enums::CountryAlpha2>,}#[async_trait]@@ -362,6 +368,43 @@ pub trait ConnectorActions: Connector {Err(errors::ConnectorError::ProcessingStepFailed(None).into())}+ fn get_payout_request<Flow, Res>(+ &self,+ connector_payout_id: Option<String>,+ payout_type: enums::PayoutType,+ payment_info: Option<PaymentInfo>,+ ) -> RouterData<Flow, types::PayoutsData, Res> {+ self.generate_data(+ types::PayoutsData {+ payout_id: core_utils::get_or_generate_uuid("payout_id", None)+ .map_or("payout_3154763247".to_string(), |p| p),+ amount: 1,+ connector_payout_id,+ destination_currency: payment_info.to_owned().map_or(enums::Currency::EUR, |pi| {+ pi.currency.map_or(enums::Currency::EUR, |c| c)+ }),+ source_currency: payment_info.to_owned().map_or(enums::Currency::EUR, |pi| {+ pi.currency.map_or(enums::Currency::EUR, |c| c)+ }),+ entity_type: enums::PayoutEntityType::Individual,+ payout_type,+ country_code: payment_info+ .to_owned()+ .map_or(enums::CountryAlpha2::NL, |pi| {+ pi.country.map_or(enums::CountryAlpha2::NL, |c| c)+ }),+ customer_details: Some(payments::CustomerDetails {+ customer_id: core_utils::get_or_generate_id("customer_id", &None, "cust_").ok(),+ name: Some(Secret::new("John Doe".to_string())),+ email: TryFrom::try_from(Secret::new("john.doe@example".to_string())).ok(),+ phone: Some(Secret::new("620874518".to_string())),+ phone_country_code: Some("+31".to_string()),+ }),+ },+ payment_info,+ )+ }+fn generate_data<Flow, Req: From<Req>, Res>(&self,req: Req,@@ -397,7 +440,7 @@ pub trait ConnectorActions: Connector {.clone().and_then(|a| a.connector_meta_data.map(masking::Secret::new)),amount_captured: None,- access_token: info.and_then(|a| a.access_token),+ access_token: info.clone().and_then(|a| a.access_token),session_token: None,reference_id: None,payment_method_token: None,@@ -405,6 +448,10 @@ pub trait ConnectorActions: Connector {recurring_mandate_payment_data: None,preprocessing_id: None,connector_request_reference_id: uuid::Uuid::new_v4().to_string(),+ #[cfg(feature = "payouts")]+ payout_method_data: info.and_then(|p| p.payout_method_data),+ #[cfg(feature = "payouts")]+ quote_id: None,test_mode: None,}}@@ -427,6 +474,242 @@ pub trait ConnectorActions: Connector {Err(_) => None,}}++ async fn verify_payout_eligibility(+ &self,+ payout_type: enums::PayoutType,+ payment_info: Option<PaymentInfo>,+ ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ types::api::PoEligibility,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = self+ .get_payout_data()+ .ok_or(ConnectorError::FailedToObtainPreferredConnector)?+ .connector+ .get_connector_integration();+ let mut request = self.get_payout_request(None, payout_type, payment_info);+ let tx: oneshot::Sender<()> = oneshot::channel().0;+ let state = routes::AppState::with_storage(+ Settings::new().unwrap(),+ StorageImpl::PostgresqlTest,+ tx,+ )+ .await;+ connector_integration+ .execute_pretasks(&mut request, &state)+ .await?;+ let res = services::api::execute_connector_processing_step(+ &state,+ connector_integration,+ &request,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await?;+ Ok(res.response.unwrap())+ }++ async fn fulfill_payout(+ &self,+ connector_payout_id: Option<String>,+ payout_type: enums::PayoutType,+ payment_info: Option<PaymentInfo>,+ ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ types::api::PoFulfill,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = self+ .get_payout_data()+ .ok_or(ConnectorError::FailedToObtainPreferredConnector)?+ .connector+ .get_connector_integration();+ let mut request = self.get_payout_request(connector_payout_id, payout_type, payment_info);+ let tx: oneshot::Sender<()> = oneshot::channel().0;+ let state = routes::AppState::with_storage(+ Settings::new().unwrap(),+ StorageImpl::PostgresqlTest,+ tx,+ )+ .await;+ connector_integration+ .execute_pretasks(&mut request, &state)+ .await?;+ let res = services::api::execute_connector_processing_step(+ &state,+ connector_integration,+ &request,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await?;+ Ok(res.response.unwrap())+ }++ async fn create_payout(+ &self,+ connector_customer: Option<String>,+ payout_type: enums::PayoutType,+ payment_info: Option<PaymentInfo>,+ ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ types::api::PoCreate,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = self+ .get_payout_data()+ .ok_or(ConnectorError::FailedToObtainPreferredConnector)?+ .connector+ .get_connector_integration();+ let mut request = self.get_payout_request(None, payout_type, payment_info);+ request.connector_customer = connector_customer;+ let tx: oneshot::Sender<()> = oneshot::channel().0;+ let state = routes::AppState::with_storage(+ Settings::new().unwrap(),+ StorageImpl::PostgresqlTest,+ tx,+ )+ .await;+ connector_integration+ .execute_pretasks(&mut request, &state)+ .await?;+ let res = services::api::execute_connector_processing_step(+ &state,+ connector_integration,+ &request,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await?;+ Ok(res.response.unwrap())+ }++ async fn cancel_payout(+ &self,+ connector_payout_id: String,+ payout_type: enums::PayoutType,+ payment_info: Option<PaymentInfo>,+ ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ types::api::PoCancel,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = self+ .get_payout_data()+ .ok_or(ConnectorError::FailedToObtainPreferredConnector)?+ .connector+ .get_connector_integration();+ let mut request =+ self.get_payout_request(Some(connector_payout_id), payout_type, payment_info);+ let tx: oneshot::Sender<()> = oneshot::channel().0;+ let state = routes::AppState::with_storage(+ Settings::new().unwrap(),+ StorageImpl::PostgresqlTest,+ tx,+ )+ .await;+ connector_integration+ .execute_pretasks(&mut request, &state)+ .await?;+ let res = services::api::execute_connector_processing_step(+ &state,+ connector_integration,+ &request,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await?;+ Ok(res.response.unwrap())+ }++ async fn create_and_fulfill_payout(+ &self,+ connector_customer: Option<String>,+ payout_type: enums::PayoutType,+ payment_info: Option<PaymentInfo>,+ ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {+ let create_res = self+ .create_payout(connector_customer, payout_type, payment_info.to_owned())+ .await?;+ assert_eq!(+ create_res.status.unwrap(),+ enums::PayoutStatus::RequiresFulfillment+ );+ let fulfill_res = self+ .fulfill_payout(+ Some(create_res.connector_payout_id),+ payout_type,+ payment_info.to_owned(),+ )+ .await?;+ Ok(fulfill_res)+ }++ async fn create_and_cancel_payout(+ &self,+ connector_customer: Option<String>,+ payout_type: enums::PayoutType,+ payment_info: Option<PaymentInfo>,+ ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {+ let create_res = self+ .create_payout(connector_customer, payout_type, payment_info.to_owned())+ .await?;+ assert_eq!(+ create_res.status.unwrap(),+ enums::PayoutStatus::RequiresFulfillment+ );+ let cancel_res = self+ .cancel_payout(+ create_res.connector_payout_id,+ payout_type,+ payment_info.to_owned(),+ )+ .await?;+ Ok(cancel_res)+ }++ async fn create_payout_recipient(+ &self,+ payout_type: enums::PayoutType,+ payment_info: Option<PaymentInfo>,+ ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {+ let connector_integration: services::BoxedConnectorIntegration<+ '_,+ types::api::PoRecipient,+ types::PayoutsData,+ types::PayoutsResponseData,+ > = self+ .get_payout_data()+ .ok_or(ConnectorError::FailedToObtainPreferredConnector)?+ .connector+ .get_connector_integration();+ let mut request = self.get_payout_request(None, payout_type, payment_info);+ let tx = oneshot::channel().0;+ let state = routes::AppState::with_storage(+ Settings::new().unwrap(),+ StorageImpl::PostgresqlTest,+ tx,+ )+ .await;+ connector_integration+ .execute_pretasks(&mut request, &state)+ .await?;+ let res = services::api::execute_connector_processing_step(+ &state,+ connector_integration,+ &request,+ payments::CallConnectorAction::Trigger,+ None,+ )+ .await?;+ Ok(res.response.unwrap())+ }}async fn call_connector<diff --git a/crates/router/tests/connectors/wise.rs b/crates/router/tests/connectors/wise.rsnew file mode 100644index 0000000000..1857a79065--- /dev/null+++ b/crates/router/tests/connectors/wise.rs@@ -0,0 +1,150 @@+use api_models::payments::{Address, AddressDetails};+use masking::Secret;+use router::types::{self, api, storage::enums, PaymentAddress};++use crate::{+ connector_auth,+ utils::{self, ConnectorActions, PaymentInfo},+};++struct WiseTest;+impl ConnectorActions for WiseTest {}+impl utils::Connector for WiseTest {+ fn get_data(&self) -> types::api::ConnectorData {+ use router::connector::Adyen;+ types::api::ConnectorData {+ connector: Box::new(&Adyen),+ connector_name: types::Connector::Adyen,+ get_token: types::api::GetToken::Connector,+ }+ }++ fn get_payout_data(&self) -> Option<types::api::PayoutConnectorData> {+ use router::connector::Wise;+ Some(types::api::PayoutConnectorData {+ connector: Box::new(&Wise),+ connector_name: types::PayoutConnectors::Wise,+ get_token: types::api::GetToken::Connector,+ })+ }++ fn get_auth_token(&self) -> types::ConnectorAuthType {+ types::ConnectorAuthType::from(+ connector_auth::ConnectorAuthentication::new()+ .wise+ .expect("Missing connector authentication configuration"),+ )+ }++ fn get_name(&self) -> String {+ "wise".to_string()+ }+}++impl WiseTest {+ fn get_payout_info() -> Option<PaymentInfo> {+ Some(PaymentInfo {+ country: Some(api_models::enums::CountryAlpha2::NL),+ currency: Some(enums::Currency::GBP),+ address: Some(PaymentAddress {+ billing: Some(Address {+ address: Some(AddressDetails {+ country: Some(api_models::enums::CountryAlpha2::GB),+ city: Some("London".to_string()),+ zip: Some(Secret::new("10025".to_string())),+ line1: Some(Secret::new("50 Branson Ave".to_string())),+ ..Default::default()+ }),+ phone: None,+ }),+ ..Default::default()+ }),+ payout_method_data: Some(api::PayoutMethodData::Bank(api::payouts::BankPayout::Bacs(+ api::BacsBankTransfer {+ bank_sort_code: "231470".to_string().into(),+ bank_account_number: "28821822".to_string().into(),+ bank_name: "Deutsche Bank".to_string(),+ bank_country_code: enums::CountryAlpha2::NL,+ bank_city: "Amsterdam".to_string(),+ },+ ))),+ ..Default::default()+ })+ }+}++static CONNECTOR: WiseTest = WiseTest {};++/******************** Payouts test cases ********************/+// Creates a recipient at connector's end+#[cfg(feature = "payouts")]+#[actix_web::test]+async fn should_create_payout_recipient() {+ let payout_type = enums::PayoutType::Bank;+ let payment_info = WiseTest::get_payout_info();+ let response = CONNECTOR+ .create_payout_recipient(payout_type, payment_info)+ .await+ .expect("Payout recipient creation response");+ assert_eq!(+ response.status.unwrap(),+ enums::PayoutStatus::RequiresCreation+ );+}++// Create BACS payout+#[cfg(feature = "payouts")]+#[actix_web::test]+async fn should_create_bacs_payout() {+ let payout_type = enums::PayoutType::Bank;+ let payout_info = WiseTest::get_payout_info();+ // Create recipient+ let recipient_res = CONNECTOR+ .create_payout_recipient(payout_type.to_owned(), payout_info.to_owned())+ .await+ .expect("Payout recipient response");+ assert_eq!(+ recipient_res.status.unwrap(),+ enums::PayoutStatus::RequiresCreation+ );++ // Create payout+ let create_res: types::PayoutsResponseData = CONNECTOR+ .create_payout(+ Some(recipient_res.connector_payout_id),+ payout_type,+ payout_info,+ )+ .await+ .expect("Payout bank creation response");+ assert_eq!(+ create_res.status.unwrap(),+ enums::PayoutStatus::RequiresFulfillment+ );+}++// Create and fulfill BACS payout+#[cfg(feature = "payouts")]+#[actix_web::test]+async fn should_create_and_fulfill_bacs_payout() {+ let payout_type = enums::PayoutType::Bank;+ let payout_info = WiseTest::get_payout_info();+ // Create recipient+ let recipient_res = CONNECTOR+ .create_payout_recipient(payout_type.to_owned(), payout_info.to_owned())+ .await+ .expect("Payout recipient response");+ assert_eq!(+ recipient_res.status.unwrap(),+ enums::PayoutStatus::RequiresCreation+ );+ let response = CONNECTOR+ .create_and_fulfill_payout(+ Some(recipient_res.connector_payout_id),+ payout_type,+ payout_info,+ )+ .await+ .expect("Payout bank creation and fulfill response");+ assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success);+}diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.tomlindex ef2af7ce11..c72220f52d 100644--- a/crates/router_env/Cargo.toml+++ b/crates/router_env/Cargo.toml@@ -37,8 +37,9 @@ cargo_metadata = "0.15.4"vergen = { version = "8.2.1", features = ["cargo", "git", "git2", "rustc"], optional = true }[features]-default = ["actix_web"]+default = ["actix_web", "payouts"]actix_web = ["tracing-actix-web"]log_custom_entries_to_extra = []log_extra_implicit_fields = []log_active_span_json = []+payouts = []diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex b9fd06876e..1ef07c135b 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -128,16 +128,21 @@ pub enum Flow {PaymentsStart,/// Payments list flow.PaymentsList,+ #[cfg(feature = "payouts")]/// Payouts create flowPayoutsCreate,+ #[cfg(feature = "payouts")]/// Payouts retrieve flow.PayoutsRetrieve,+ #[cfg(feature = "payouts")]/// Payouts update flow.PayoutsUpdate,- /// Payouts reverse flow.- PayoutsReverse,+ #[cfg(feature = "payouts")]/// Payouts cancel flow.PayoutsCancel,+ #[cfg(feature = "payouts")]+ /// Payouts fulfill flow.+ PayoutsFulfill,/// Payouts accounts flow.PayoutsAccounts,/// Payments Redirect flow.diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.tomlindex 920cdc1405..b05e137e60 100644--- a/crates/test_utils/Cargo.toml+++ b/crates/test_utils/Cargo.toml@@ -8,9 +8,9 @@ readme = "README.md"license.workspace = true[features]-default = ["dummy_connector"]+default = ["dummy_connector", "payouts"]dummy_connector = ["api_models/dummy_connector"]-+payouts = [][dependencies]clap = { version = "4.3.2", default-features = false, features = ["std", "derive", "help", "usage", "cargo"] }diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rsindex d478e32955..be470d8f91 100644--- a/crates/test_utils/src/connector_auth.rs+++ b/crates/test_utils/src/connector_auth.rs@@ -7,8 +7,14 @@ use serde::{Deserialize, Serialize};#[derive(Debug, Serialize, Deserialize, Clone)]pub struct ConnectorAuthentication {pub aci: Option<BodyKey>,+ #[cfg(not(feature = "payouts"))]pub adyen: Option<BodyKey>,+ #[cfg(feature = "payouts")]+ pub adyen: Option<SignatureKey>,+ #[cfg(not(feature = "payouts"))]pub adyen_uk: Option<BodyKey>,+ #[cfg(feature = "payouts")]+ pub adyen_uk: Option<SignatureKey>,pub airwallex: Option<BodyKey>,pub authorizedotnet: Option<BodyKey>,pub bambora: Option<BodyKey>,@@ -48,6 +54,7 @@ pub struct ConnectorAuthentication {pub stripe_uk: Option<HeaderKey>,pub trustpay: Option<SignatureKey>,pub tsys: Option<SignatureKey>,+ pub wise: Option<BodyKey>,pub worldpay: Option<BodyKey>,pub worldline: Option<SignatureKey>,pub zen: Option<HeaderKey>,diff --git a/loadtest/config/development.toml b/loadtest/config/development.tomlindex 0b2697498e..7a7354d09a 100644--- a/loadtest/config/development.toml+++ b/loadtest/config/development.toml@@ -59,6 +59,7 @@ hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"[connectors]aci.base_url = "https://eu-test.oppwa.com/"adyen.base_url = "https://checkout-test.adyen.com/"+adyen.secondary_base_url = "https://pal-test.adyen.com/"airwallex.base_url = "https://api-demo.airwallex.com/"applepay.base_url = "https://apple-pay-gateway.apple.com/"authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"@@ -102,6 +103,7 @@ worldline.base_url = "https://eu.sandbox.api-ingenico.com/"worldpay.base_url = "https://try.access.worldpay.com/"trustpay.base_url = "https://test-tpgw.trustpay.eu/"tsys.base_url = "https://stagegw.transnox.com/"+wise.base_url = "https://api.sandbox.transferwise.tech/"trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"zen.base_url = "https://api.zen-test.com/"@@ -146,6 +148,7 @@ cards = ["stripe","trustpay","tsys",+ "wise","worldline","worldpay","zen",@@ -168,3 +171,6 @@ refund_duration = 1000refund_tolerance = 100refund_retrieve_duration = 500refund_retrieve_tolerance = 100++[payouts]+payout_eligibility = truediff --git a/migrations/2023-05-02-102332_payout_create/down.sql b/migrations/2023-05-02-102332_payout_create/down.sqlnew file mode 100644index 0000000000..c464916526--- /dev/null+++ b/migrations/2023-05-02-102332_payout_create/down.sql@@ -0,0 +1,23 @@+DROP TABLE PAYOUT_ATTEMPT;++DROP TABLE PAYOUTS;++DROP TYPE "PayoutStatus";++DROP TYPE "PayoutType";++-- Alterations++ALTER TABLE+ merchant_account DROP COLUMN payout_routing_algorithm;++ALTER TABLE locker_mock_up DROP COLUMN enc_card_data;++DELETE FROM pg_enum+WHERE+ enumlabel = 'payout_processor'+ AND enumtypid = (+ SELECT oid+ FROM pg_type+ WHERE typname = 'ConnectorType'+ )\ No newline at end of filediff --git a/migrations/2023-05-02-102332_payout_create/up.sql b/migrations/2023-05-02-102332_payout_create/up.sqlnew file mode 100644index 0000000000..3464b62a70--- /dev/null+++ b/migrations/2023-05-02-102332_payout_create/up.sql@@ -0,0 +1,71 @@+CREATE type "PayoutStatus" AS ENUM (+ 'success',+ 'failed',+ 'cancelled',+ 'pending',+ 'ineligible',+ 'requires_creation',+ 'requires_payout_method_data',+ 'requires_fulfillment'+);++CREATE type "PayoutType" AS ENUM ('card', 'bank');++CREATE TABLE+ PAYOUT_ATTEMPT (+ payout_attempt_id VARCHAR (64) NOT NULL PRIMARY KEY,+ payout_id VARCHAR (64) NOT NULL,+ customer_id VARCHAR (64) NOT NULL,+ merchant_id VARCHAR (64) NOT NULL,+ address_id VARCHAR (64) NOT NULL,+ connector VARCHAR (64) NOT NULL,+ connector_payout_id VARCHAR (128) NOT NULL,+ payout_token VARCHAR (64),+ status "PayoutStatus" NOT NULL,+ is_eligible BOOLEAN,+ error_message TEXT,+ error_code VARCHAR (64),+ business_country "CountryAlpha2",+ business_label VARCHAR(64),+ created_at timestamp NOT NULL DEFAULT NOW():: timestamp,+ last_modified_at timestamp NOT NULL DEFAULT NOW():: timestamp+ );++CREATE TABLE+ PAYOUTS (+ payout_id VARCHAR (64) NOT NULL PRIMARY KEY,+ merchant_id VARCHAR (64) NOT NULL,+ customer_id VARCHAR (64) NOT NULL,+ address_id VARCHAR (64) NOT NULL,+ payout_type "PayoutType" NOT NULL,+ payout_method_id VARCHAR (64),+ amount BIGINT NOT NULL,+ destination_currency "Currency" NOT NULL,+ source_currency "Currency" NOT NULL,+ description VARCHAR (255),+ recurring BOOLEAN NOT NULL,+ auto_fulfill BOOLEAN NOT NULL,+ return_url VARCHAR (255),+ entity_type VARCHAR (64) NOT NULL,+ metadata JSONB DEFAULT '{}':: JSONB,+ created_at timestamp NOT NULL DEFAULT NOW():: timestamp,+ last_modified_at timestamp NOT NULL DEFAULT NOW():: timestamp+ );++CREATE UNIQUE INDEX payout_attempt_index ON PAYOUT_ATTEMPT (+ merchant_id,+ payout_attempt_id,+ payout_id+);++CREATE UNIQUE INDEX payouts_index ON PAYOUTS (merchant_id, payout_id);++-- Alterations++ALTER TABLE merchant_account+ADD+ COLUMN payout_routing_algorithm JSONB;++ALTER TABLE locker_mock_up ADD COLUMN enc_card_data TEXT;++ALTER TYPE "ConnectorType" ADD VALUE 'payout_processor';\ No newline at end of filediff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.jsonindex 9466dabe69..018605093e 100644--- a/openapi/openapi_spec.json+++ b/openapi/openapi_spec.json@@ -1410,6 +1410,238 @@]}},+ "/payouts/create": {+ "post": {+ "tags": [+ "Payouts"+ ],+ "summary": "Payouts - Create",+ "description": "Payouts - Create",+ "operationId": "Create a Payout",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutCreateRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Payout created",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutCreateResponse"+ }+ }+ }+ },+ "400": {+ "description": "Missing Mandatory fields"+ }+ },+ "security": [+ {+ "api_key": []+ }+ ]+ }+ },+ "/payouts/{payout_id}": {+ "get": {+ "tags": [+ "Payouts"+ ],+ "summary": "Payouts - Retrieve",+ "description": "Payouts - Retrieve",+ "operationId": "Retrieve a Payout",+ "parameters": [+ {+ "name": "payout_id",+ "in": "path",+ "description": "The identifier for payout]",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Payout retrieved",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutCreateResponse"+ }+ }+ }+ },+ "404": {+ "description": "Payout does not exist in our records"+ }+ },+ "security": [+ {+ "api_key": []+ }+ ]+ },+ "post": {+ "tags": [+ "Payouts"+ ],+ "summary": "Payouts - Update",+ "description": "Payouts - Update",+ "operationId": "Update a Payout",+ "parameters": [+ {+ "name": "payout_id",+ "in": "path",+ "description": "The identifier for payout]",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutCreateRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Payout updated",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutCreateResponse"+ }+ }+ }+ },+ "400": {+ "description": "Missing Mandatory fields"+ }+ },+ "security": [+ {+ "api_key": []+ }+ ]+ }+ },+ "/payouts/{payout_id}/cancel": {+ "post": {+ "tags": [+ "Payouts"+ ],+ "summary": "Payouts - Cancel",+ "description": "Payouts - Cancel",+ "operationId": "Cancel a Payout",+ "parameters": [+ {+ "name": "payout_id",+ "in": "path",+ "description": "The identifier for payout",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutActionRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Payout cancelled",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutCreateResponse"+ }+ }+ }+ },+ "400": {+ "description": "Missing Mandatory fields"+ }+ },+ "security": [+ {+ "api_key": []+ }+ ]+ }+ },+ "/payouts/{payout_id}/fulfill": {+ "post": {+ "tags": [+ "Payouts"+ ],+ "summary": "Payouts - Fulfill",+ "description": "Payouts - Fulfill",+ "operationId": "Fulfill a Payout",+ "parameters": [+ {+ "name": "payout_id",+ "in": "path",+ "description": "The identifier for payout",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutActionRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Payout fulfilled",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutCreateResponse"+ }+ }+ }+ },+ "400": {+ "description": "Missing Mandatory fields"+ }+ },+ "security": [+ {+ "api_key": []+ }+ ]+ }+ },"/refunds": {"post": {"tags": [@@ -1713,6 +1945,41 @@"propertyName": "type"}},+ "AchBankTransfer": {+ "type": "object",+ "required": [+ "bank_name",+ "bank_country_code",+ "bank_city",+ "bank_account_number",+ "bank_routing_number"+ ],+ "properties": {+ "bank_name": {+ "type": "string",+ "description": "Bank name",+ "example": "Deutsche Bank"+ },+ "bank_country_code": {+ "$ref": "#/components/schemas/CountryAlpha2"+ },+ "bank_city": {+ "type": "string",+ "description": "Bank city",+ "example": "California"+ },+ "bank_account_number": {+ "type": "string",+ "description": "Bank account number is an unique identifier assigned by a bank to a customer.",+ "example": "000123456"+ },+ "bank_routing_number": {+ "type": "string",+ "description": "[9 digits] Routing number - used in USA for identifying a specific bank.",+ "example": "110000000"+ }+ }+ },"AchBillingDetails": {"type": "object","required": [@@ -2080,6 +2347,41 @@"no_three_ds"]},+ "BacsBankTransfer": {+ "type": "object",+ "required": [+ "bank_name",+ "bank_country_code",+ "bank_city",+ "bank_account_number",+ "bank_sort_code"+ ],+ "properties": {+ "bank_name": {+ "type": "string",+ "description": "Bank name",+ "example": "Deutsche Bank"+ },+ "bank_country_code": {+ "$ref": "#/components/schemas/CountryAlpha2"+ },+ "bank_city": {+ "type": "string",+ "description": "Bank city",+ "example": "California"+ },+ "bank_account_number": {+ "type": "string",+ "description": "Bank account number is an unique identifier assigned by a bank to a customer.",+ "example": "000123456"+ },+ "bank_sort_code": {+ "type": "string",+ "description": "[6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches.",+ "example": "98-76-54"+ }+ }+ },"BacsBankTransferInstructions": {"type": "object","required": [@@ -2102,6 +2404,19 @@}}},+ "Bank": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/AchBankTransfer"+ },+ {+ "$ref": "#/components/schemas/BacsBankTransfer"+ },+ {+ "$ref": "#/components/schemas/SepaBankTransfer"+ }+ ]+ },"BankDebitBilling": {"type": "object","required": [@@ -2903,10 +3218,9 @@"type": "object","required": ["card_number",- "card_exp_month",- "card_exp_year",- "card_holder_name",- "card_cvc"+ "expiry_month",+ "expiry_year",+ "card_holder_name"],"properties": {"card_number": {@@ -2914,78 +3228,36 @@"description": "The card number","example": "4242424242424242"},- "card_exp_month": {+ "expiry_month": {"type": "string",- "description": "The card's expiry month",- "example": "24"+ "description": "The card's expiry month"},- "card_exp_year": {+ "expiry_year": {"type": "string",- "description": "The card's expiry year",- "example": "24"+ "description": "The card's expiry year"},"card_holder_name": {"type": "string","description": "The card holder's name",- "example": "John Test"- },- "card_cvc": {+ "example": "John Doe"+ }+ }+ },+ "CardDetail": {+ "type": "object",+ "required": [+ "card_number",+ "card_exp_month",+ "card_exp_year",+ "card_holder_name"+ ],+ "properties": {+ "card_number": {"type": "string",- "description": "The CVC number for the card",- "example": "242"+ "description": "Card Number",+ "example": "4111111145551142"},- "card_issuer": {- "type": "string",- "description": "The name of the issuer of card",- "example": "chase",- "nullable": true- },- "card_network": {- "allOf": [- {- "$ref": "#/components/schemas/CardNetwork"- }- ],- "nullable": true- },- "card_type": {- "type": "string",- "example": "CREDIT",- "nullable": true- },- "card_issuing_country": {- "type": "string",- "example": "INDIA",- "nullable": true- },- "bank_code": {- "type": "string",- "example": "JP_AMEX",- "nullable": true- },- "nick_name": {- "type": "string",- "description": "The card holder's nick name",- "example": "John Test",- "nullable": true- }- }- },- "CardDetail": {- "type": "object",- "required": [- "card_number",- "card_exp_month",- "card_exp_year",- "card_holder_name"- ],- "properties": {- "card_number": {- "type": "string",- "description": "Card Number",- "example": "4111111145551142"- },- "card_exp_month": {+ "card_exp_month": {"type": "string","description": "Card Expiry Month","example": "10"@@ -3068,11 +3340,19 @@"Connector": {"type": "string","enum": [+ "phonypay",+ "fauxpay",+ "pretendpay",+ "stripe_test",+ "adyen_test",+ "checkout_test",+ "paypal_test","aci","adyen","airwallex","authorizedotnet","bitpay",+ "bambora","bluesnap","braintree","cashtocode",@@ -3080,20 +3360,12 @@"coinbase","cryptopay","cybersource",- "iatapay",- "phonypay",- "fauxpay",- "pretendpay",- "stripe_test",- "adyen_test",- "checkout_test",- "paypal_test",- "bambora","dlocal","fiserv","forte","globalpay","globepay",+ "iatapay","klarna","mollie","multisafepay",@@ -3112,6 +3384,7 @@"stripe","trustpay","tsys",+ "wise","worldline","worldpay","zen"@@ -3795,6 +4068,14 @@"description": "A timestamp (ISO 8601 code) that determines when the customer was created","example": "2023-01-18T11:04:09.922Z","nullable": true+ },+ "bank_transfer": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Bank"+ }+ ],+ "nullable": true}}},@@ -4911,6 +5192,14 @@"description": "The routing algorithm to be used for routing payments to desired connectors","nullable": true},+ "payout_routing_algorithm": {+ "allOf": [+ {+ "$ref": "#/components/schemas/RoutingAlgorithm"+ }+ ],+ "nullable": true+ },"sub_merchants_enabled": {"type": "boolean","description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.",@@ -5081,6 +5370,14 @@],"nullable": true},+ "payout_routing_algorithm": {+ "allOf": [+ {+ "$ref": "#/components/schemas/RoutingAlgorithm"+ }+ ],+ "nullable": true+ },"sub_merchants_enabled": {"type": "boolean","description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.",@@ -5190,6 +5487,14 @@"description": "The routing algorithm to be used for routing payments to desired connectors","nullable": true},+ "payout_routing_algorithm": {+ "allOf": [+ {+ "$ref": "#/components/schemas/RoutingAlgorithm"+ }+ ],+ "nullable": true+ },"sub_merchants_enabled": {"type": "boolean","description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.",@@ -8160,6 +8465,469 @@}}},+ "PayoutActionRequest": {+ "type": "object",+ "required": [+ "payout_id"+ ],+ "properties": {+ "payout_id": {+ "type": "string",+ "description": "Unique identifier for the payout. This ensures idempotency for multiple payouts\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.",+ "example": "payout_mbabizu24mvu3mela5njyhpit4",+ "maxLength": 30,+ "minLength": 30+ }+ }+ },+ "PayoutConnectors": {+ "type": "string",+ "enum": [+ "adyen",+ "wise"+ ]+ },+ "PayoutCreateRequest": {+ "type": "object",+ "required": [+ "merchant_id",+ "currency",+ "confirm",+ "payout_type",+ "customer_id",+ "auto_fulfill",+ "client_secret",+ "return_url",+ "business_country",+ "description",+ "entity_type"+ ],+ "properties": {+ "payout_id": {+ "type": "string",+ "description": "Unique identifier for the payout. This ensures idempotency for multiple payouts\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.",+ "example": "payout_mbabizu24mvu3mela5njyhpit4",+ "nullable": true,+ "maxLength": 30,+ "minLength": 30+ },+ "merchant_id": {+ "type": "string",+ "description": "This is an identifier for the merchant account. This is inferred from the API key\nprovided during the request",+ "example": "merchant_1668273825",+ "maxLength": 255+ },+ "amount": {+ "type": "integer",+ "format": "int64",+ "description": "The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,",+ "example": 1000+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ },+ "routing": {+ "allOf": [+ {+ "$ref": "#/components/schemas/RoutingAlgorithm"+ }+ ],+ "nullable": true+ },+ "connector": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Connector"+ },+ "description": "This allows the merchant to manually select a connector with which the payout can go through",+ "example": [+ "wise",+ "adyen"+ ],+ "nullable": true+ },+ "confirm": {+ "type": "boolean",+ "description": "The boolean value to create payout with connector",+ "default": false,+ "example": true+ },+ "payout_type": {+ "$ref": "#/components/schemas/PayoutType"+ },+ "payout_method_data": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PayoutMethodData"+ }+ ],+ "nullable": true+ },+ "billing": {+ "type": "object",+ "description": "The billing address for the payout",+ "nullable": true+ },+ "customer_id": {+ "type": "string",+ "description": "The identifier for the customer object. If not provided the customer ID will be autogenerated.",+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",+ "maxLength": 255+ },+ "auto_fulfill": {+ "type": "boolean",+ "description": "Set to true to confirm the payout without review, no further action required",+ "default": false,+ "example": true+ },+ "email": {+ "type": "string",+ "description": "description: The customer's email address",+ "example": "[email protected]",+ "nullable": true,+ "maxLength": 255+ },+ "name": {+ "type": "string",+ "description": "description: The customer's name",+ "example": "John Test",+ "nullable": true,+ "maxLength": 255+ },+ "phone": {+ "type": "string",+ "description": "The customer's phone number",+ "example": "3141592653",+ "nullable": true,+ "maxLength": 255+ },+ "phone_country_code": {+ "type": "string",+ "description": "The country code for the customer phone number",+ "example": "+1",+ "nullable": true,+ "maxLength": 255+ },+ "client_secret": {+ "type": "string",+ "description": "It's a token used for client side verification.",+ "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo"+ },+ "return_url": {+ "type": "string",+ "description": "The URL to redirect after the completion of the operation",+ "example": "https://hyperswitch.io"+ },+ "business_country": {+ "$ref": "#/components/schemas/CountryAlpha2"+ },+ "business_label": {+ "type": "string",+ "description": "Business label of the merchant for this payout",+ "example": "food",+ "nullable": true+ },+ "description": {+ "type": "string",+ "description": "A description of the payout",+ "example": "It's my first payout request"+ },+ "entity_type": {+ "$ref": "#/components/schemas/PayoutEntityType"+ },+ "recurring": {+ "type": "boolean",+ "description": "Specifies whether or not the payout request is recurring",+ "default": false,+ "nullable": true+ },+ "metadata": {+ "type": "object",+ "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.",+ "nullable": true+ },+ "payout_token": {+ "type": "string",+ "description": "Provide a reference to a stored payment method",+ "example": "187282ab-40ef-47a9-9206-5099ba31e432",+ "nullable": true+ }+ }+ },+ "PayoutCreateResponse": {+ "type": "object",+ "required": [+ "payout_id",+ "merchant_id",+ "amount",+ "currency",+ "payout_type",+ "customer_id",+ "auto_fulfill",+ "client_secret",+ "return_url",+ "business_country",+ "description",+ "entity_type",+ "status",+ "error_message",+ "error_code"+ ],+ "properties": {+ "payout_id": {+ "type": "string",+ "description": "Unique identifier for the payout. This ensures idempotency for multiple payouts\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.",+ "example": "payout_mbabizu24mvu3mela5njyhpit4",+ "maxLength": 30,+ "minLength": 30+ },+ "merchant_id": {+ "type": "string",+ "description": "This is an identifier for the merchant account. This is inferred from the API key\nprovided during the request",+ "example": "merchant_1668273825",+ "maxLength": 255+ },+ "amount": {+ "type": "integer",+ "format": "int64",+ "description": "The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,",+ "example": 1000+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ },+ "connector": {+ "type": "string",+ "description": "The connector used for the payout",+ "example": "wise",+ "nullable": true+ },+ "payout_type": {+ "$ref": "#/components/schemas/PayoutType"+ },+ "billing": {+ "type": "object",+ "description": "The billing address for the payout",+ "nullable": true+ },+ "customer_id": {+ "type": "string",+ "description": "The identifier for the customer object. If not provided the customer ID will be autogenerated.",+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",+ "maxLength": 255+ },+ "auto_fulfill": {+ "type": "boolean",+ "description": "Set to true to confirm the payout without review, no further action required",+ "default": false,+ "example": true+ },+ "email": {+ "type": "string",+ "description": "description: The customer's email address",+ "example": "[email protected]",+ "nullable": true,+ "maxLength": 255+ },+ "name": {+ "type": "string",+ "description": "description: The customer's name",+ "example": "John Test",+ "nullable": true,+ "maxLength": 255+ },+ "phone": {+ "type": "string",+ "description": "The customer's phone number",+ "example": "3141592653",+ "nullable": true,+ "maxLength": 255+ },+ "phone_country_code": {+ "type": "string",+ "description": "The country code for the customer phone number",+ "example": "+1",+ "nullable": true,+ "maxLength": 255+ },+ "client_secret": {+ "type": "string",+ "description": "It's a token used for client side verification.",+ "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo"+ },+ "return_url": {+ "type": "string",+ "description": "The URL to redirect after the completion of the operation",+ "example": "https://hyperswitch.io"+ },+ "business_country": {+ "$ref": "#/components/schemas/CountryAlpha2"+ },+ "business_label": {+ "type": "string",+ "description": "Business label of the merchant for this payout",+ "example": "food",+ "nullable": true+ },+ "description": {+ "type": "string",+ "description": "A description of the payout",+ "example": "It's my first payout request"+ },+ "entity_type": {+ "$ref": "#/components/schemas/PayoutEntityType"+ },+ "recurring": {+ "type": "boolean",+ "description": "Specifies whether or not the payout request is recurring",+ "default": false,+ "nullable": true+ },+ "metadata": {+ "type": "object",+ "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.",+ "nullable": true+ },+ "status": {+ "$ref": "#/components/schemas/PayoutStatus"+ },+ "error_message": {+ "type": "string",+ "description": "If there was an error while calling the connector the error message is received here",+ "example": "Failed while verifying the card"+ },+ "error_code": {+ "type": "string",+ "description": "If there was an error while calling the connectors the code is received here",+ "example": "E0001"+ }+ }+ },+ "PayoutEntityType": {+ "type": "string",+ "enum": [+ "Individual",+ "Company",+ "NonProfit",+ "PublicSector",+ "lowercase",+ "Personal"+ ]+ },+ "PayoutMethodData": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "card"+ ],+ "properties": {+ "card": {+ "$ref": "#/components/schemas/Card"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "bank"+ ],+ "properties": {+ "bank": {+ "$ref": "#/components/schemas/Bank"+ }+ }+ }+ ]+ },+ "PayoutRequest": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "PayoutActionRequest"+ ],+ "properties": {+ "PayoutActionRequest": {+ "$ref": "#/components/schemas/PayoutActionRequest"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "PayoutCreateRequest"+ ],+ "properties": {+ "PayoutCreateRequest": {+ "$ref": "#/components/schemas/PayoutCreateRequest"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "PayoutRetrieveRequest"+ ],+ "properties": {+ "PayoutRetrieveRequest": {+ "$ref": "#/components/schemas/PayoutRetrieveRequest"+ }+ }+ }+ ]+ },+ "PayoutRetrieveBody": {+ "type": "object",+ "properties": {+ "force_sync": {+ "type": "boolean",+ "nullable": true+ }+ }+ },+ "PayoutRetrieveRequest": {+ "type": "object",+ "required": [+ "payout_id"+ ],+ "properties": {+ "payout_id": {+ "type": "string",+ "description": "Unique identifier for the payout. This ensures idempotency for multiple payouts\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.",+ "example": "payout_mbabizu24mvu3mela5njyhpit4",+ "maxLength": 30,+ "minLength": 30+ },+ "force_sync": {+ "type": "boolean",+ "description": "`force_sync` with the connector to get payout details\n(defaults to false)",+ "default": false,+ "example": true,+ "nullable": true+ }+ }+ },+ "PayoutStatus": {+ "type": "string",+ "enum": [+ "success",+ "failed",+ "cancelled",+ "pending",+ "ineligible",+ "requires_creation",+ "requires_payout_method_data",+ "requires_fulfillment"+ ]+ },+ "PayoutType": {+ "type": "string",+ "enum": [+ "card",+ "bank"+ ]+ },"PaypalRedirection": {"type": "object"},@@ -8681,6 +9449,41 @@}}},+ "SepaBankTransfer": {+ "type": "object",+ "required": [+ "bank_name",+ "bank_country_code",+ "bank_city",+ "iban",+ "bic"+ ],+ "properties": {+ "bank_name": {+ "type": "string",+ "description": "Bank name",+ "example": "Deutsche Bank"+ },+ "bank_country_code": {+ "$ref": "#/components/schemas/CountryAlpha2"+ },+ "bank_city": {+ "type": "string",+ "description": "Bank city",+ "example": "California"+ },+ "iban": {+ "type": "string",+ "description": "International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer.",+ "example": "DE89370400440532013000"+ },+ "bic": {+ "type": "string",+ "description": "[8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches",+ "example": "HSBCGB2LXXX"+ }+ }+ },"SepaBankTransferInstructions": {"type": "object","required": [@@ -9301,6 +10104,10 @@{"name": "Disputes","description": "Manage disputes"+ },+ {+ "name": "Payouts",+ "description": "Create and manage payouts"}]}\ No newline at end of filediff --git a/scripts/add_connector.sh b/scripts/add_connector.shindex 622dfb8d01..7d7e919457 100755--- a/scripts/add_connector.sh+++ b/scripts/add_connector.sh@@ -4,7 +4,7 @@ function find_prev_connector() {git checkout $selfcp $self $self.tmp# add new connector to existing list and sort it- connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu powertranz rapyd shift4 stax stripe trustpay tsys worldline worldpay "$1")+ connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu powertranz rapyd shift4 stax stripe trustpay tsys wise worldline worldpay "$1")IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFSres=`echo ${sorted[@]}`sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp@@ -53,8 +53,8 @@ sed -i'' -e "s|\"$prvc\" \(.*\)|\"$prvc\" \1\n\t\t\t\"${pg}\" => Ok(Box::new(\&csed -i'' -e "s/pub $prvc: \(.*\)/pub $prvc: \1\n\tpub ${pg}: ConnectorParams,/" $src/configs/settings.rssed -i'' -e "s|$prvc.base_url \(.*\)|$prvc.base_url \1\n${pg}.base_url = \"$base_url\"|" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.tomlsed -r -i'' -e "s/\"$prvc\",/\"$prvc\",\n \"${pg}\",/" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml-sed -i'' -e "s/Dummy,/Dummy,\n\t${pgc},/" crates/api_models/src/enums.rssed -i'' -e "s/pub enum RoutableConnectors {/pub enum RoutableConnectors {\n\t${pgc},/" crates/api_models/src/enums.rs+sed -i'' -e "s/Dummy,/Dummy,\n\t${pgc},/" crates/api_models/src/enums.rssed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnector::${pgc},/" $src/core/payments/flows.rs# remove temporary files created in above step