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(core): Create Payout Webhook Flow (#4696)
Sakil Mostaka3183a0c5ba7
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rsindex b5428b6fca..2c10e3a81e 100644--- a/crates/api_models/src/webhooks.rs+++ b/crates/api_models/src/webhooks.rs@@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize};use time::PrimitiveDateTime;use utoipa::ToSchema;+#[cfg(feature = "payouts")]+use crate::payouts;use crate::{disputes, enums as api_enums, mandates, payments, refunds};#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)]@@ -41,10 +43,26 @@ pub enum IncomingWebhookEvent {ExternalAuthenticationARes,FrmApproved,FrmRejected,+ #[cfg(feature = "payouts")]+ PayoutSuccess,+ #[cfg(feature = "payouts")]+ PayoutFailure,+ #[cfg(feature = "payouts")]+ PayoutProcessing,+ #[cfg(feature = "payouts")]+ PayoutCancelled,+ #[cfg(feature = "payouts")]+ PayoutCreated,+ #[cfg(feature = "payouts")]+ PayoutExpired,+ #[cfg(feature = "payouts")]+ PayoutReversed,}pub enum WebhookFlow {Payment,+ #[cfg(feature = "payouts")]+ Payout,Refund,Dispute,Subscription,@@ -62,6 +80,11 @@ pub enum WebhookResponseTracker {payment_id: String,status: common_enums::IntentStatus,},+ #[cfg(feature = "payouts")]+ Payout {+ payout_id: String,+ status: common_enums::PayoutStatus,+ },Refund {payment_id: String,refund_id: String,@@ -86,6 +109,8 @@ impl WebhookResponseTracker {| Self::Refund { payment_id, .. }| Self::Dispute { payment_id, .. } => Some(payment_id.to_string()),Self::NoEffect | Self::Mandate { .. } => None,+ #[cfg(feature = "payouts")]+ Self::Payout { .. } => None,}}}@@ -125,6 +150,14 @@ impl From<IncomingWebhookEvent> for WebhookFlow {IncomingWebhookEvent::FrmApproved | IncomingWebhookEvent::FrmRejected => {Self::FraudCheck}+ #[cfg(feature = "payouts")]+ IncomingWebhookEvent::PayoutSuccess+ | IncomingWebhookEvent::PayoutFailure+ | IncomingWebhookEvent::PayoutProcessing+ | IncomingWebhookEvent::PayoutCancelled+ | IncomingWebhookEvent::PayoutCreated+ | IncomingWebhookEvent::PayoutExpired+ | IncomingWebhookEvent::PayoutReversed => Self::Payout,}}}@@ -149,12 +182,21 @@ pub enum AuthenticationIdType {ConnectorAuthenticationId(String),}+#[cfg(feature = "payouts")]+#[derive(Clone)]+pub enum PayoutIdType {+ PayoutAttemptId(String),+ ConnectorPayoutId(String),+}+#[derive(Clone)]pub enum ObjectReferenceId {PaymentId(payments::PaymentIdType),RefundId(RefundIdType),MandateId(MandateIdType),ExternalAuthenticationID(AuthenticationIdType),+ #[cfg(feature = "payouts")]+ PayoutId(PayoutIdType),}pub struct IncomingWebhookDetails {@@ -193,6 +235,9 @@ pub enum OutgoingWebhookContent {DisputeDetails(Box<disputes::DisputeResponse>),#[schema(value_type = MandateResponse, title = "MandateResponse")]MandateDetails(Box<mandates::MandateResponse>),+ #[cfg(feature = "payouts")]+ #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]+ PayoutDetails(payouts::PayoutCreateResponse),}#[derive(Debug, Clone, Serialize)]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 3df291d568..e0ed251b7a 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -1069,6 +1069,8 @@ pub enum EventClass {Refunds,Disputes,Mandates,+ #[cfg(feature = "payouts")]+ Payouts,}#[derive(@@ -1107,6 +1109,13 @@ pub enum EventType {DisputeLost,MandateActive,MandateRevoked,+ PayoutSuccess,+ PayoutFailed,+ PayoutInitiated,+ PayoutProcessing,+ PayoutCancelled,+ PayoutExpired,+ PayoutReversed,}#[derive(@@ -2116,6 +2125,9 @@ pub enum PayoutStatus {Success,Failed,Cancelled,+ Initiated,+ Expired,+ Reversed,Pending,Ineligible,#[default]diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rsindex d78a6b1148..5caa410ed5 100644--- a/crates/diesel_models/src/enums.rs+++ b/crates/diesel_models/src/enums.rs@@ -68,6 +68,7 @@ pub enum EventObjectType {RefundDetails,DisputeDetails,MandateDetails,+ PayoutDetails,}#[derive(diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rsindex 8544d2d273..68c99d5ac0 100644--- a/crates/diesel_models/src/payout_attempt.rs+++ b/crates/diesel_models/src/payout_attempt.rs@@ -15,7 +15,7 @@ pub struct PayoutAttempt {pub merchant_id: String,pub address_id: String,pub connector: Option<String>,- pub connector_payout_id: String,+ pub connector_payout_id: Option<String>,pub payout_token: Option<String>,pub status: storage_enums::PayoutStatus,pub is_eligible: Option<bool>,@@ -51,7 +51,7 @@ pub struct PayoutAttemptNew {pub merchant_id: String,pub address_id: String,pub connector: Option<String>,- pub connector_payout_id: String,+ pub connector_payout_id: Option<String>,pub payout_token: Option<String>,pub status: storage_enums::PayoutStatus,pub is_eligible: Option<bool>,@@ -71,7 +71,7 @@ pub struct PayoutAttemptNew {#[derive(Debug, Clone, Serialize, Deserialize)]pub enum PayoutAttemptUpdate {StatusUpdate {- connector_payout_id: String,+ connector_payout_id: Option<String>,status: storage_enums::PayoutStatus,error_message: Option<String>,error_code: Option<String>,@@ -138,7 +138,7 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {error_code,is_eligible,} => Self {- connector_payout_id: Some(connector_payout_id),+ connector_payout_id,status: Some(status),error_message,error_code,@@ -182,7 +182,7 @@ impl PayoutAttemptUpdate {} = self.into();PayoutAttempt {payout_token: payout_token.or(source.payout_token),- connector_payout_id: connector_payout_id.unwrap_or(source.connector_payout_id),+ connector_payout_id: connector_payout_id.or(source.connector_payout_id),status: status.unwrap_or(source.status),error_message: error_message.or(source.error_message),error_code: error_code.or(source.error_code),diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rsindex 4f95877bd7..df4a7d77e6 100644--- a/crates/diesel_models/src/query/payout_attempt.rs+++ b/crates/diesel_models/src/query/payout_attempt.rs@@ -81,6 +81,20 @@ impl PayoutAttempt {.await}+ pub async fn find_by_merchant_id_connector_payout_id(+ conn: &PgPooledConn,+ merchant_id: &str,+ connector_payout_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::connector_payout_id.eq(connector_payout_id.to_owned())),+ )+ .await+ }+pub async fn update_by_merchant_id_payout_id(conn: &PgPooledConn,merchant_id: &str,diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 6074fdc10b..2c57feb4cd 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -967,7 +967,7 @@ diesel::table! {#[max_length = 64]connector -> Nullable<Varchar>,#[max_length = 128]- connector_payout_id -> Varchar,+ connector_payout_id -> Nullable<Varchar>,#[max_length = 64]payout_token -> Nullable<Varchar>,status -> PayoutStatus,diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rsindex a19e694ff2..a0786f4de7 100644--- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs@@ -32,6 +32,13 @@ pub trait PayoutAttemptInterface {_storage_scheme: MerchantStorageScheme,) -> error_stack::Result<PayoutAttempt, errors::StorageError>;+ async fn find_payout_attempt_by_merchant_id_connector_payout_id(+ &self,+ _merchant_id: &str,+ _connector_payout_id: &str,+ _storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<PayoutAttempt, errors::StorageError>;+async fn get_filters_for_payouts(&self,payout: &[Payouts],@@ -56,7 +63,7 @@ pub struct PayoutAttempt {pub merchant_id: String,pub address_id: String,pub connector: Option<String>,- pub connector_payout_id: String,+ pub connector_payout_id: Option<String>,pub payout_token: Option<String>,pub status: storage_enums::PayoutStatus,pub is_eligible: Option<bool>,@@ -81,7 +88,7 @@ pub struct PayoutAttemptNew {pub merchant_id: String,pub address_id: String,pub connector: Option<String>,- pub connector_payout_id: String,+ pub connector_payout_id: Option<String>,pub payout_token: Option<String>,pub status: storage_enums::PayoutStatus,pub is_eligible: Option<bool>,@@ -107,7 +114,7 @@ impl Default for PayoutAttemptNew {merchant_id: String::default(),address_id: String::default(),connector: None,- connector_payout_id: String::default(),+ connector_payout_id: Some(String::default()),payout_token: None,status: storage_enums::PayoutStatus::default(),is_eligible: None,@@ -124,10 +131,10 @@ impl Default for PayoutAttemptNew {}}-#[derive(Debug)]+#[derive(Debug, Clone)]pub enum PayoutAttemptUpdate {StatusUpdate {- connector_payout_id: String,+ connector_payout_id: Option<String>,status: storage_enums::PayoutStatus,error_message: Option<String>,error_code: Option<String>,@@ -174,7 +181,7 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {error_code,is_eligible,} => Self {- connector_payout_id: Some(connector_payout_id),+ connector_payout_id,status: Some(status),error_message,error_code,diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rsindex b61a60ecd3..6ce5b48ee0 100644--- a/crates/hyperswitch_domain_models/src/router_response_types.rs+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs@@ -182,7 +182,7 @@ pub struct RetrieveFileResponse {#[derive(Clone, Debug, Default)]pub struct PayoutsResponseData {pub status: Option<common_enums::PayoutStatus>,- pub connector_payout_id: String,+ pub connector_payout_id: Option<String>,pub payout_eligible: Option<bool>,pub should_add_next_step_to_process_tracker: bool,}diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rsindex 77e2c85abb..b52c8136b9 100644--- a/crates/router/src/compatibility/stripe/webhooks.rs+++ b/crates/router/src/compatibility/stripe/webhooks.rs@@ -1,7 +1,14 @@+#[cfg(feature = "payouts")]+use api_models::payouts as payout_models;use api_models::{enums::{DisputeStatus, MandateStatus},webhooks::{self as api},};+#[cfg(feature = "payouts")]+use common_utils::{+ crypto::Encryptable,+ pii::{self, Email},+};use common_utils::{crypto::SignMessage, date_time, ext_traits::Encode};use error_stack::ResultExt;use router_env::logger;@@ -81,6 +88,8 @@ pub enum StripeWebhookObject {Refund(StripeRefundResponse),Dispute(StripeDisputeResponse),Mandate(StripeMandateResponse),+ #[cfg(feature = "payouts")]+ Payout(StripePayoutResponse),}#[derive(Serialize, Debug)]@@ -101,6 +110,82 @@ pub struct StripeMandateResponse {pub payment_method: String,}+#[cfg(feature = "payouts")]+#[derive(Clone, Serialize, Debug)]+pub struct StripePayoutResponse {+ pub id: String,+ pub amount: i64,+ pub currency: String,+ pub payout_type: common_enums::PayoutType,+ pub status: StripePayoutStatus,+ pub name: Option<masking::Secret<String>>,+ pub email: Option<Email>,+ pub phone: Option<masking::Secret<String>>,+ pub phone_country_code: Option<String>,+ pub created: Option<i64>,+ pub metadata: Option<pii::SecretSerdeValue>,+ pub entity_type: common_enums::PayoutEntityType,+ pub recurring: bool,+ pub error_message: Option<String>,+ pub error_code: Option<String>,+}++#[cfg(feature = "payouts")]+#[derive(Clone, Serialize, Debug)]+#[serde(rename_all = "snake_case")]+pub enum StripePayoutStatus {+ PayoutSuccess,+ PayoutFailure,+ PayoutProcessing,+ PayoutCancelled,+ PayoutInitiated,+ PayoutExpired,+ PayoutReversed,+}++#[cfg(feature = "payouts")]+impl From<common_enums::PayoutStatus> for StripePayoutStatus {+ fn from(status: common_enums::PayoutStatus) -> Self {+ match status {+ common_enums::PayoutStatus::Success => Self::PayoutSuccess,+ common_enums::PayoutStatus::Failed => Self::PayoutFailure,+ common_enums::PayoutStatus::Cancelled => Self::PayoutCancelled,+ common_enums::PayoutStatus::Initiated => Self::PayoutInitiated,+ common_enums::PayoutStatus::Expired => Self::PayoutExpired,+ common_enums::PayoutStatus::Reversed => Self::PayoutReversed,+ common_enums::PayoutStatus::Pending+ | common_enums::PayoutStatus::Ineligible+ | common_enums::PayoutStatus::RequiresCreation+ | common_enums::PayoutStatus::RequiresFulfillment+ | common_enums::PayoutStatus::RequiresPayoutMethodData+ | common_enums::PayoutStatus::RequiresVendorAccountCreation => Self::PayoutProcessing,+ }+ }+}++#[cfg(feature = "payouts")]+impl From<payout_models::PayoutCreateResponse> for StripePayoutResponse {+ fn from(res: payout_models::PayoutCreateResponse) -> Self {+ Self {+ id: res.payout_id,+ amount: res.amount,+ currency: res.currency.to_string(),+ payout_type: res.payout_type,+ status: StripePayoutStatus::from(res.status),+ name: res.name.map(Encryptable::into_inner),+ email: res.email.map(|inner| inner.into()),+ phone: res.phone.map(Encryptable::into_inner),+ phone_country_code: res.phone_country_code,+ created: res.created.map(|t| t.assume_utc().unix_timestamp()),+ metadata: res.metadata,+ entity_type: res.entity_type,+ recurring: res.recurring,+ error_message: res.error_message,+ error_code: res.error_code,+ }+ }+}+#[derive(Serialize, Debug)]#[serde(rename_all = "snake_case")]pub enum StripeMandateStatus {@@ -197,6 +282,13 @@ fn get_stripe_event_type(event_type: api_models::enums::EventType) -> &'static s}// stripe treats partially captured payments as succeeded.api_models::enums::EventType::PaymentCaptured => "payment_intent.succeeded",+ api_models::enums::EventType::PayoutSuccess => "payout.paid",+ api_models::enums::EventType::PayoutFailed => "payout.failed",+ api_models::enums::EventType::PayoutInitiated => "payout.created",+ api_models::enums::EventType::PayoutCancelled => "payout.canceled",+ api_models::enums::EventType::PayoutProcessing => "payout.created",+ api_models::enums::EventType::PayoutExpired => "payout.failed",+ api_models::enums::EventType::PayoutReversed => "payout.reconciliation_completed",}}@@ -237,6 +329,8 @@ impl From<api::OutgoingWebhookContent> for StripeWebhookObject {api::OutgoingWebhookContent::MandateDetails(mandate) => {Self::Mandate((*mandate).into())}+ #[cfg(feature = "payouts")]+ api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout(payout.into()),}}}diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rsindex e38edeaa85..c43c1dd2de 100644--- a/crates/router/src/connector/adyen.rs+++ b/crates/router/src/connector/adyen.rs@@ -1806,6 +1806,12 @@ impl api::IncomingWebhook for Adyen {),));}+ #[cfg(feature = "payouts")]+ if adyen::is_payout_event(¬if.event_code) {+ return Ok(api_models::webhooks::ObjectReferenceId::PayoutId(+ api_models::webhooks::PayoutIdType::PayoutAttemptId(notif.merchant_reference),+ ));+ }Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound))}diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rsindex 2489afd94d..c8b8ced7bd 100644--- a/crates/router/src/connector/adyen/transformers.rs+++ b/crates/router/src/connector/adyen/transformers.rs@@ -294,7 +294,7 @@ impl ForeignTryFrom<(bool, AdyenWebhookStatus)> for storage_enums::AttemptStatusAdyenWebhookStatus::CaptureFailed => Ok(Self::CaptureFailed),//If Unexpected Event is received, need to understand how it reached this point//Webhooks with Payment Events only should try to conume this resource object.- AdyenWebhookStatus::UnexpectedEvent => {+ AdyenWebhookStatus::UnexpectedEvent | AdyenWebhookStatus::Reversed => {Err(report!(errors::ConnectorError::WebhookBodyDecodingFailed))}}@@ -373,6 +373,7 @@ pub enum AdyenWebhookStatus {CancelFailed,Captured,CaptureFailed,+ Reversed,UnexpectedEvent,}@@ -4107,6 +4108,14 @@ pub enum WebhookEventCode {SecondChargeback,PrearbitrationWon,PrearbitrationLost,+ #[cfg(feature = "payouts")]+ PayoutThirdparty,+ #[cfg(feature = "payouts")]+ PayoutDecline,+ #[cfg(feature = "payouts")]+ PayoutExpire,+ #[cfg(feature = "payouts")]+ PayoutReversed,#[serde(other)]Unknown,}@@ -4146,6 +4155,17 @@ pub fn is_chargeback_event(event_code: &WebhookEventCode) -> bool {)}+#[cfg(feature = "payouts")]+pub fn is_payout_event(event_code: &WebhookEventCode) -> bool {+ matches!(+ event_code,+ WebhookEventCode::PayoutThirdparty+ | WebhookEventCode::PayoutDecline+ | WebhookEventCode::PayoutExpire+ | WebhookEventCode::PayoutReversed+ )+}+fn is_success_scenario(is_success: String) -> bool {is_success.as_str() == "true"}@@ -4205,6 +4225,14 @@ impl ForeignFrom<(WebhookEventCode, String, Option<DisputeStatus>)>}}WebhookEventCode::CaptureFailed => Self::PaymentIntentCaptureFailure,+ #[cfg(feature = "payouts")]+ WebhookEventCode::PayoutThirdparty => Self::PayoutCreated,+ #[cfg(feature = "payouts")]+ WebhookEventCode::PayoutDecline => Self::PayoutFailure,+ #[cfg(feature = "payouts")]+ WebhookEventCode::PayoutExpire => Self::PayoutExpired,+ #[cfg(feature = "payouts")]+ WebhookEventCode::PayoutReversed => Self::PayoutReversed,WebhookEventCode::Unknown => Self::EventNotSupported,}}@@ -4278,6 +4306,20 @@ impl From<AdyenNotificationRequestItemWH> for AdyenWebhookResponse {AdyenWebhookStatus::CaptureFailed}}+ #[cfg(feature = "payouts")]+ WebhookEventCode::PayoutThirdparty => {+ if is_success_scenario(notif.success) {+ AdyenWebhookStatus::Authorised+ } else {+ AdyenWebhookStatus::AuthorisationFailed+ }+ }+ #[cfg(feature = "payouts")]+ WebhookEventCode::PayoutDecline => AdyenWebhookStatus::Cancelled,+ #[cfg(feature = "payouts")]+ WebhookEventCode::PayoutExpire => AdyenWebhookStatus::AuthorisationFailed,+ #[cfg(feature = "payouts")]+ WebhookEventCode::PayoutReversed => AdyenWebhookStatus::Reversed,WebhookEventCode::CaptureFailed => AdyenWebhookStatus::CaptureFailed,WebhookEventCode::CancelOrRefund| WebhookEventCode::Refund@@ -4557,7 +4599,7 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutE},merchant_account: auth_type.merchant_account,payment_method: payout_method_data,- reference: item.router_data.request.payout_id.clone(),+ reference: item.router_data.connector_request_reference_id.clone(),shopper_reference: item.router_data.merchant_id.clone(),})}@@ -4644,7 +4686,7 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutC},merchant_account,payment_data: PayoutPaymentMethodData::PayoutBankData(bank_data),- reference: item.router_data.request.payout_id.to_owned(),+ reference: item.router_data.connector_request_reference_id.to_owned(),shopper_reference: item.router_data.merchant_id.to_owned(),shopper_email: customer_email,shopper_name: ShopperName {@@ -4741,7 +4783,7 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutFbilling_address: get_address_info(item.router_data.get_billing().ok()).transpose()?,merchant_account,- reference: item.router_data.request.payout_id.clone(),+ reference: item.router_data.connector_request_reference_id.clone(),shopper_name: ShopperName {first_name: Some(address.get_first_name()?.to_owned()), // it is a required field for payoutslast_name: Some(address.get_last_name()?.to_owned()), // it is a required field for payouts@@ -4788,7 +4830,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenPayoutResponse>>Ok(Self {response: Ok(types::PayoutsResponseData {status,- connector_payout_id: response.psp_reference,+ connector_payout_id: Some(response.psp_reference),payout_eligible,should_add_next_step_to_process_tracker: false,}),@@ -4801,7 +4843,8 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenPayoutResponse>>impl From<AdyenStatus> for storage_enums::PayoutStatus {fn from(adyen_status: AdyenStatus) -> Self {match adyen_status {- AdyenStatus::Authorised | AdyenStatus::PayoutConfirmReceived => Self::Success,+ AdyenStatus::Authorised => Self::Success,+ AdyenStatus::PayoutConfirmReceived => Self::Initiated,AdyenStatus::Cancelled | AdyenStatus::PayoutDeclineReceived => Self::Cancelled,AdyenStatus::Error => Self::Failed,AdyenStatus::Pending => Self::Pending,diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rsindex 4527ea3950..b800563364 100644--- a/crates/router/src/connector/cybersource/transformers.rs+++ b/crates/router/src/connector/cybersource/transformers.rs@@ -3151,7 +3151,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, CybersourceFulfillResponse>>Ok(Self {response: Ok(types::PayoutsResponseData {status: Some(enums::PayoutStatus::foreign_from(item.response.status)),- connector_payout_id: item.response.id,+ connector_payout_id: Some(item.response.id),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),diff --git a/crates/router/src/connector/ebanx/transformers.rs b/crates/router/src/connector/ebanx/transformers.rsindex 472e2da1b6..8f667065a4 100644--- a/crates/router/src/connector/ebanx/transformers.rs+++ b/crates/router/src/connector/ebanx/transformers.rs@@ -218,7 +218,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxPayoutResponse>>status: Some(storage_enums::PayoutStatus::from(item.response.payout.status,)),- connector_payout_id: item.response.payout.uid,+ connector_payout_id: Some(item.response.payout.uid),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),@@ -301,7 +301,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxFulfillResponse>>Ok(Self {response: Ok(types::PayoutsResponseData {status: Some(storage_enums::PayoutStatus::from(item.response.status)),- connector_payout_id: item.data.request.get_transfer_id()?,+ connector_payout_id: Some(item.data.request.get_transfer_id()?),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),@@ -391,12 +391,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxCancelResponse>>Ok(Self {response: Ok(types::PayoutsResponseData {status: Some(storage_enums::PayoutStatus::from(item.response.status)),- connector_payout_id: item- .data- .request- .connector_payout_id- .clone()- .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,+ connector_payout_id: item.data.request.connector_payout_id.clone(),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),diff --git a/crates/router/src/connector/payone/transformers.rs b/crates/router/src/connector/payone/transformers.rsindex 3c9e562787..77a3d9bc5b 100644--- a/crates/router/src/connector/payone/transformers.rs+++ b/crates/router/src/connector/payone/transformers.rs@@ -272,7 +272,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>Ok(Self {response: Ok(types::PayoutsResponseData {status: Some(storage_enums::PayoutStatus::foreign_from(response.status)),- connector_payout_id: response.id,+ connector_payout_id: Some(response.id),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rsindex d240c1b05e..f89e6d6e07 100644--- a/crates/router/src/connector/paypal/transformers.rs+++ b/crates/router/src/connector/paypal/transformers.rs@@ -1699,7 +1699,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, PaypalFulfillResponse>>status: Some(storage_enums::PayoutStatus::foreign_from(item.response.batch_header.batch_status,)),- connector_payout_id: item.response.batch_header.payout_batch_id,+ connector_payout_id: Some(item.response.batch_header.payout_batch_id),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),diff --git a/crates/router/src/connector/stripe/transformers/connect.rs b/crates/router/src/connector/stripe/transformers/connect.rsindex 43bc0f2f51..5145421675 100644--- a/crates/router/src/connector/stripe/transformers/connect.rs+++ b/crates/router/src/connector/stripe/transformers/connect.rs@@ -234,7 +234,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutCreateResOk(Self {response: Ok(types::PayoutsResponseData {status: Some(enums::PayoutStatus::RequiresFulfillment),- connector_payout_id: response.id,+ connector_payout_id: Some(response.id),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),@@ -268,7 +268,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutFulfillReOk(Self {response: Ok(types::PayoutsResponseData {status: Some(enums::PayoutStatus::from(response.status)),- connector_payout_id: response.id,+ connector_payout_id: Some(response.id),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),@@ -300,7 +300,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectReversalResponsOk(Self {response: Ok(types::PayoutsResponseData {status: Some(enums::PayoutStatus::Cancelled),- connector_payout_id: response.id,+ connector_payout_id: Some(response.id),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),@@ -374,7 +374,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientCreateOk(Self {response: Ok(types::PayoutsResponseData {status: Some(enums::PayoutStatus::RequiresVendorAccountCreation),- connector_payout_id: response.id,+ connector_payout_id: Some(response.id),payout_eligible: None,should_add_next_step_to_process_tracker: true,}),@@ -457,7 +457,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientAccounOk(Self {response: Ok(types::PayoutsResponseData {status: Some(enums::PayoutStatus::RequiresCreation),- connector_payout_id: response.id,+ connector_payout_id: Some(response.id),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rsindex 763adca1ee..dd826a9ab8 100644--- a/crates/router/src/connector/wise.rs+++ b/crates/router/src/connector/wise.rs@@ -531,7 +531,7 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pamatch quote_router_resp.response.to_owned() {Ok(resp) => {- router_data.quote_id = Some(resp.connector_payout_id);+ router_data.quote_id = resp.connector_payout_id;Ok(())}Err(_err) => {diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rsindex c3347fd938..c480a0bc84 100644--- a/crates/router/src/connector/wise/transformers.rs+++ b/crates/router/src/connector/wise/transformers.rs@@ -406,7 +406,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse>Ok(Self {response: Ok(types::PayoutsResponseData {status: Some(storage_enums::PayoutStatus::RequiresCreation),- connector_payout_id: response.id.to_string(),+ connector_payout_id: Some(response.id.to_string()),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),@@ -452,7 +452,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>>Ok(Self {response: Ok(types::PayoutsResponseData {status: Some(storage_enums::PayoutStatus::RequiresCreation),- connector_payout_id: response.id,+ connector_payout_id: Some(response.id),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),@@ -515,7 +515,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutResponse>>Ok(Self {response: Ok(types::PayoutsResponseData {status: Some(status),- connector_payout_id: response.id.to_string(),+ connector_payout_id: Some(response.id.to_string()),payout_eligible: None,should_add_next_step_to_process_tracker: false,}),@@ -557,7 +557,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseFulfillResponse>>Ok(Self {response: Ok(types::PayoutsResponseData {status: Some(storage_enums::PayoutStatus::from(response.status)),- connector_payout_id: "".to_string(),+ connector_payout_id: None,payout_eligible: None,should_add_next_step_to_process_tracker: false,}),diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rsindex 0e36ed165b..fee3d8aafb 100644--- a/crates/router/src/core/metrics.rs+++ b/crates/router/src/core/metrics.rs@@ -33,6 +33,12 @@ counter_metric!(GLOBAL_METER);+counter_metric!(INCOMING_PAYOUT_WEBHOOK_METRIC, GLOBAL_METER); // No. of incoming payout webhooks+counter_metric!(+ INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC,+ GLOBAL_METER+); // No. of incoming payout webhooks for which signature verification failed+counter_metric!(WEBHOOK_INCOMING_COUNT, GLOBAL_METER);counter_metric!(WEBHOOK_INCOMING_FILTERED_COUNT, GLOBAL_METER);counter_metric!(WEBHOOK_SOURCE_VERIFIED_COUNT, GLOBAL_METER);diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 8eca589ca2..733002fe7c 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -985,7 +985,7 @@ impl ForeignFrom<(storage::Payouts, storage::PayoutAttempt, domain::Customer)>error_message: payout_attempt.error_message.clone(),payment_method: Some(payout.payout_type),payout_method_type: None,- connector_transaction_id: Some(payout_attempt.connector_payout_id),+ connector_transaction_id: payout_attempt.connector_payout_id,cancellation_reason: None,unified_code: None,unified_message: None,diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 93c634b07f..eb1f54ab6c 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -1048,7 +1048,7 @@ pub async fn create_recipient(customers::update_connector_customer_in_customers(&connector_label,Some(&customer),- &Some(recipient_create_data.connector_payout_id.clone()),+ &recipient_create_data.connector_payout_id.clone(),).await{@@ -1248,7 +1248,7 @@ pub async fn check_payout_eligibility(Err(err) => {let status = storage_enums::PayoutStatus::Failed;let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {- connector_payout_id: String::default(),+ connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),status,error_code: Some(err.code),error_message: Some(err.message),@@ -1298,7 +1298,7 @@ pub async fn complete_create_payout(let db = &*state.store;let payout_attempt = &payout_data.payout_attempt;let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {- connector_payout_id: "".to_string(),+ connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),status: storage::enums::PayoutStatus::RequiresFulfillment,error_code: None,error_message: None,@@ -1440,7 +1440,7 @@ pub async fn create_payout(Err(err) => {let status = storage_enums::PayoutStatus::Failed;let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {- connector_payout_id: String::default(),+ connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),status,error_code: Some(err.code),error_message: Some(err.message),@@ -1563,7 +1563,7 @@ pub async fn create_recipient_disburse_account(}Err(err) => {let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {- connector_payout_id: String::default(),+ connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),status: storage_enums::PayoutStatus::Failed,error_code: Some(err.code),error_message: Some(err.message),@@ -1659,7 +1659,7 @@ pub async fn cancel_payout(Err(err) => {let status = storage_enums::PayoutStatus::Failed;let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {- connector_payout_id: String::default(),+ connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),status,error_code: Some(err.code),error_message: Some(err.message),@@ -1799,7 +1799,7 @@ pub async fn fulfill_payout(Err(err) => {let status = storage_enums::PayoutStatus::Failed;let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {- connector_payout_id: String::default(),+ connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),status,error_code: Some(err.code),error_message: Some(err.message),diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rsindex 792309920c..12fe3a48e1 100644--- a/crates/router/src/core/payouts/retry.rs+++ b/crates/router/src/core/payouts/retry.rs@@ -346,6 +346,9 @@ impl GsmValidation for PayoutData {common_enums::PayoutStatus::Success| common_enums::PayoutStatus::Cancelled| common_enums::PayoutStatus::Pending+ | common_enums::PayoutStatus::Initiated+ | common_enums::PayoutStatus::Reversed+ | common_enums::PayoutStatus::Expired| common_enums::PayoutStatus::Ineligible| common_enums::PayoutStatus::RequiresCreation| common_enums::PayoutStatus::RequiresPayoutMethodDatadiff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex 679838a6dd..4791ea823d 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -169,7 +169,7 @@ pub async fn construct_payout_router_data<'a, F>(request: types::PayoutsData {payout_id: payouts.payout_id.to_owned(),amount: payouts.amount,- connector_payout_id: Some(payout_attempt.connector_payout_id.to_owned()),+ connector_payout_id: payout_attempt.connector_payout_id.clone(),destination_currency: payouts.destination_currency,source_currency: payouts.source_currency,entity_type: payouts.entity_type.to_owned(),@@ -192,8 +192,7 @@ pub async fn construct_payout_router_data<'a, F>(payment_method_token: None,recurring_mandate_payment_data: None,preprocessing_id: None,- connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW- .to_string(),+ connector_request_reference_id: payout_attempt.payout_attempt_id.clone(),payout_method_data: payout_data.payout_method_data.to_owned(),quote_id: None,test_mode,diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rsindex 7962e86e12..2256077770 100644--- a/crates/router/src/core/webhooks.rs+++ b/crates/router/src/core/webhooks.rs@@ -6,6 +6,8 @@ pub mod webhook_events;use std::{str::FromStr, time::Instant};use actix_web::FromRequest;+#[cfg(feature = "payouts")]+use api_models::payouts as payout_models;use api_models::{payments::HeaderPayload,webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent},@@ -22,9 +24,13 @@ use router_env::{tracing_actix_web::RequestId,};+#[cfg(feature = "payouts")]+use super::payouts;use super::{errors::StorageErrorExt, metrics};#[cfg(feature = "stripe")]use crate::compatibility::stripe::webhooks as stripe_webhooks;+#[cfg(not(feature = "payouts"))]+use crate::routes::SessionState;use crate::{consts,core::{@@ -42,7 +48,6 @@ use crate::{app::{ReqState, SessionStateInfo},lock_utils,metrics::request::add_attributes,- SessionState,},services::{self, authentication as auth},types::{@@ -54,6 +59,8 @@ use crate::{utils::{self as helper_utils, generate_id, OptionExt, ValueExt},workflows::outgoing_webhook_retry,};+#[cfg(feature = "payouts")]+use crate::{routes::SessionState, types::storage::PayoutAttemptUpdate};const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5;const MERCHANT_ID: &str = "merchant_id";@@ -201,6 +208,130 @@ pub async fn payments_incoming_webhook_flow(}}+#[cfg(feature = "payouts")]+pub async fn payouts_incoming_webhook_flow(+ state: SessionState,+ merchant_account: domain::MerchantAccount,+ business_profile: diesel_models::business_profile::BusinessProfile,+ key_store: domain::MerchantKeyStore,+ webhook_details: api::IncomingWebhookDetails,+ event_type: webhooks::IncomingWebhookEvent,+ source_verified: bool,+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {+ metrics::INCOMING_PAYOUT_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]);+ if source_verified {+ let db = &*state.store;+ //find payout_attempt by object_reference_id+ let payout_attempt = match webhook_details.object_reference_id {+ webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type {+ webhooks::PayoutIdType::PayoutAttemptId(id) => db+ .find_payout_attempt_by_merchant_id_payout_attempt_id(+ &merchant_account.merchant_id,+ &id,+ merchant_account.storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)+ .attach_printable("Failed to fetch the payout attempt")?,+ webhooks::PayoutIdType::ConnectorPayoutId(id) => db+ .find_payout_attempt_by_merchant_id_connector_payout_id(+ &merchant_account.merchant_id,+ &id,+ merchant_account.storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)+ .attach_printable("Failed to fetch the payout attempt")?,+ },+ _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("received a non-payout id when processing payout webhooks")?,+ };++ let payouts = db+ .find_payout_by_merchant_id_payout_id(+ &merchant_account.merchant_id,+ &payout_attempt.payout_id,+ merchant_account.storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)+ .attach_printable("Failed to fetch the payout")?;++ let payout_attempt_update = PayoutAttemptUpdate::StatusUpdate {+ connector_payout_id: payout_attempt.connector_payout_id.clone(),+ status: common_enums::PayoutStatus::foreign_try_from(event_type)+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("failed payout status mapping from event type")?,+ error_message: None,+ error_code: None,+ is_eligible: payout_attempt.is_eligible,+ };++ let action_req =+ payout_models::PayoutRequest::PayoutActionRequest(payout_models::PayoutActionRequest {+ payout_id: payouts.payout_id.clone(),+ });++ let payout_data =+ payouts::make_payout_data(&state, &merchant_account, &key_store, &action_req).await?;++ let updated_payout_attempt = db+ .update_payout_attempt(+ &payout_attempt,+ payout_attempt_update,+ &payout_data.payouts,+ merchant_account.storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)+ .attach_printable_lazy(|| {+ format!(+ "Failed while updating payout attempt: payout_attempt_id: {}",+ payout_attempt.payout_attempt_id+ )+ })?;++ let event_type: Option<enums::EventType> = updated_payout_attempt.status.foreign_into();++ // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook+ if let Some(outgoing_event_type) = event_type {+ let router_response =+ payouts::response_handler(&merchant_account, &payout_data).await?;++ let payout_create_response: payout_models::PayoutCreateResponse = match router_response+ {+ services::ApplicationResponse::Json(response) => response,+ _ => Err(errors::ApiErrorResponse::WebhookResourceNotFound)+ .attach_printable("Failed to fetch the payout create response")?,+ };++ create_event_and_trigger_outgoing_webhook(+ state,+ merchant_account,+ business_profile,+ &key_store,+ outgoing_event_type,+ enums::EventClass::Payouts,+ updated_payout_attempt.payout_id.clone(),+ enums::EventObjectType::PayoutDetails,+ api::OutgoingWebhookContent::PayoutDetails(payout_create_response),+ Some(updated_payout_attempt.created_at),+ )+ .await?;+ }++ Ok(WebhookResponseTracker::Payout {+ payout_id: updated_payout_attempt.payout_id,+ status: updated_payout_attempt.status,+ })+ } else {+ metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(&metrics::CONTEXT, 1, &[]);+ Err(report!(+ errors::ApiErrorResponse::WebhookAuthenticationFailed+ ))+ }+}+#[instrument(skip_all)]#[allow(clippy::too_many_arguments)]pub async fn refunds_incoming_webhook_flow(@@ -1953,6 +2084,19 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>(.await.attach_printable("Incoming webhook flow for fraud check failed")?,+ #[cfg(feature = "payouts")]+ api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow(+ state.clone(),+ merchant_account,+ business_profile,+ key_store,+ webhook_details,+ event_type,+ source_verified,+ ))+ .await+ .attach_printable("Incoming webhook flow for payouts failed")?,+_ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable("Unsupported Flow Type received in incoming webhooks")?,}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 910ad085f6..6fe86e70f1 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -1560,6 +1560,21 @@ impl PayoutAttemptInterface for KafkaStore {.await}+ async fn find_payout_attempt_by_merchant_id_connector_payout_id(+ &self,+ merchant_id: &str,+ connector_payout_id: &str,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<storage::PayoutAttempt, errors::DataStorageError> {+ self.diesel_store+ .find_payout_attempt_by_merchant_id_connector_payout_id(+ merchant_id,+ connector_payout_id,+ storage_scheme,+ )+ .await+ }+async fn update_payout_attempt(&self,this: &storage::PayoutAttempt,diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rsindex 5c1e3d31c1..9accf0ff0d 100644--- a/crates/router/src/events/outgoing_webhook_logs.rs+++ b/crates/router/src/events/outgoing_webhook_logs.rs@@ -27,6 +27,10 @@ pub enum OutgoingWebhookEventContent {payment_id: Option<String>,content: Value,},+ Payout {+ payout_id: String,+ content: Value,+ },Refund {payment_id: String,refund_id: String,@@ -74,6 +78,12 @@ impl OutgoingWebhookEventMetric for OutgoingWebhookContent {content: masking::masked_serialize(&mandate_payload).unwrap_or(serde_json::json!({"error":"failed to serialize"})),}),+ #[cfg(feature = "payouts")]+ Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout {+ payout_id: payout_payload.payout_id.clone(),+ content: masking::masked_serialize(&payout_payload)+ .unwrap_or(serde_json::json!({"error":"failed to serialize"})),+ }),}}}diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rsindex fd781c7df9..517ae3de0e 100644--- a/crates/router/src/services/kafka/payout.rs+++ b/crates/router/src/services/kafka/payout.rs@@ -30,7 +30,7 @@ pub struct KafkaPayout<'a> {pub status: storage_enums::PayoutStatus,pub connector: Option<&'a String>,- pub connector_payout_id: &'a String,+ pub connector_payout_id: Option<&'a String>,pub is_eligible: Option<bool>,pub error_message: Option<&'a String>,pub error_code: Option<&'a String>,@@ -64,7 +64,7 @@ impl<'a> KafkaPayout<'a> {attempt_count: payouts.attempt_count,status: payouts.status,connector: payout_attempt.connector.as_ref(),- connector_payout_id: &payout_attempt.connector_payout_id,+ connector_payout_id: payout_attempt.connector_payout_id.as_ref(),is_eligible: payout_attempt.is_eligible,error_message: payout_attempt.error_message.as_ref(),error_code: payout_attempt.error_code.as_ref(),diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex 3391b52a22..a073d52375 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -551,6 +551,29 @@ impl ForeignFrom<storage_enums::RefundStatus> for Option<storage_enums::EventTyp}}+impl ForeignFrom<storage_enums::PayoutStatus> for Option<storage_enums::EventType> {+ fn foreign_from(value: storage_enums::PayoutStatus) -> Self {+ match value {+ storage_enums::PayoutStatus::Success => Some(storage_enums::EventType::PayoutSuccess),+ storage_enums::PayoutStatus::Failed => Some(storage_enums::EventType::PayoutFailed),+ storage_enums::PayoutStatus::Cancelled => {+ Some(storage_enums::EventType::PayoutCancelled)+ }+ storage_enums::PayoutStatus::Initiated => {+ Some(storage_enums::EventType::PayoutInitiated)+ }+ storage_enums::PayoutStatus::Expired => Some(storage_enums::EventType::PayoutExpired),+ storage_enums::PayoutStatus::Reversed => Some(storage_enums::EventType::PayoutReversed),+ storage_enums::PayoutStatus::Ineligible+ | storage_enums::PayoutStatus::Pending+ | storage_enums::PayoutStatus::RequiresCreation+ | storage_enums::PayoutStatus::RequiresFulfillment+ | storage_enums::PayoutStatus::RequiresPayoutMethodData+ | storage_enums::PayoutStatus::RequiresVendorAccountCreation => None,+ }+ }+}+impl ForeignFrom<storage_enums::DisputeStatus> for storage_enums::EventType {fn foreign_from(value: storage_enums::DisputeStatus) -> Self {match value {@@ -591,6 +614,28 @@ impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enum}}+#[cfg(feature = "payouts")]+impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::PayoutStatus {+ type Error = errors::ValidationError;++ fn foreign_try_from(+ value: api_models::webhooks::IncomingWebhookEvent,+ ) -> Result<Self, Self::Error> {+ match value {+ api_models::webhooks::IncomingWebhookEvent::PayoutSuccess => Ok(Self::Success),+ api_models::webhooks::IncomingWebhookEvent::PayoutFailure => Ok(Self::Failed),+ api_models::webhooks::IncomingWebhookEvent::PayoutCancelled => Ok(Self::Cancelled),+ api_models::webhooks::IncomingWebhookEvent::PayoutProcessing => Ok(Self::Pending),+ api_models::webhooks::IncomingWebhookEvent::PayoutCreated => Ok(Self::Initiated),+ api_models::webhooks::IncomingWebhookEvent::PayoutExpired => Ok(Self::Expired),+ api_models::webhooks::IncomingWebhookEvent::PayoutReversed => Ok(Self::Reversed),+ _ => Err(errors::ValidationError::IncorrectValueProvided {+ field_name: "incoming_webhook_event_type",+ }),+ }+ }+}+impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::MandateStatus {type Error = errors::ValidationError;diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex b83d3138b7..328d4fbdc6 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -415,6 +415,60 @@ pub async fn get_mca_from_payment_intent(}}+#[cfg(feature = "payouts")]+pub async fn get_mca_from_payout_attempt(+ db: &dyn StorageInterface,+ merchant_account: &domain::MerchantAccount,+ payout_id_type: webhooks::PayoutIdType,+ connector_name: &str,+ key_store: &domain::MerchantKeyStore,+) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {+ let payout = match payout_id_type {+ webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db+ .find_payout_attempt_by_merchant_id_payout_attempt_id(+ &merchant_account.merchant_id,+ &payout_attempt_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,+ webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db+ .find_payout_attempt_by_merchant_id_connector_payout_id(+ &merchant_account.merchant_id,+ &connector_payout_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,+ };++ match payout.merchant_connector_id {+ Some(merchant_connector_id) => db+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ &merchant_account.merchant_id,+ &merchant_connector_id,+ key_store,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_connector_id,+ }),+ None => db+ .find_merchant_connector_account_by_profile_id_connector_name(+ &payout.profile_id,+ connector_name,+ key_store,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: format!(+ "profile_id {} and connector_name {}",+ payout.profile_id, connector_name+ ),+ }),+ }+}+pub async fn get_mca_from_object_reference_id(db: &dyn StorageInterface,object_reference_id: webhooks::ObjectReferenceId,@@ -481,6 +535,17 @@ pub async fn get_mca_from_object_reference_id().await}+ #[cfg(feature = "payouts")]+ webhooks::ObjectReferenceId::PayoutId(payout_id_type) => {+ get_mca_from_payout_attempt(+ db,+ merchant_account,+ payout_id_type,+ connector_name,+ key_store,+ )+ .await+ }},}}diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rsindex 53b275dfeb..9184a78b6b 100644--- a/crates/router/src/workflows/outgoing_webhook_retry.rs+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs@@ -1,3 +1,5 @@+#[cfg(feature = "payouts")]+use api_models::payouts as payout_models;use api_models::{enums::EventType,webhook_events::OutgoingWebhookRequestContent,@@ -13,6 +15,8 @@ use scheduler::{utils as scheduler_utils,};+#[cfg(feature = "payouts")]+use crate::core::payouts;use crate::{core::webhooks::{self as webhooks_core, types::OutgoingWebhookTrackingData},db::StorageInterface,@@ -474,5 +478,33 @@ async fn get_outgoing_webhook_content_and_event_type(event_type,))}+ #[cfg(feature = "payouts")]+ diesel_models::enums::EventClass::Payouts => {+ let payout_id = tracking_data.primary_object_id.clone();+ let request = payout_models::PayoutRequest::PayoutActionRequest(+ payout_models::PayoutActionRequest { payout_id },+ );++ let payout_data =+ payouts::make_payout_data(&state, &merchant_account, &key_store, &request).await?;++ let router_response =+ payouts::response_handler(&merchant_account, &payout_data).await?;++ let payout_create_response: payout_models::PayoutCreateResponse = match router_response+ {+ ApplicationResponse::Json(response) => response,+ _ => Err(errors::ApiErrorResponse::WebhookResourceNotFound)+ .attach_printable("Failed to fetch the payout create response")?,+ };++ let event_type = Option::<EventType>::foreign_from(payout_data.payout_attempt.status);+ logger::debug!(current_resource_status=%payout_data.payout_attempt.status);++ Ok((+ OutgoingWebhookContent::PayoutDetails(payout_create_response),+ event_type,+ ))+ }}}diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rsindex 0de19f17b5..134777dc09 100644--- a/crates/router/tests/connectors/utils.rs+++ b/crates/router/tests/connectors/utils.rs@@ -784,7 +784,7 @@ pub trait ConnectorActions: Connector {);let fulfill_res = self.fulfill_payout(- Some(create_res.connector_payout_id),+ create_res.connector_payout_id,payout_type,payment_info.to_owned(),)@@ -808,7 +808,11 @@ pub trait ConnectorActions: Connector {);let cancel_res = self.cancel_payout(- create_res.connector_payout_id,+ create_res+ .connector_payout_id+ .ok_or(ConnectorError::MissingRequiredField {+ field_name: "connector_payout_id",+ })?,payout_type,payment_info.to_owned(),)diff --git a/crates/router/tests/connectors/wise.rs b/crates/router/tests/connectors/wise.rsindex 36a16635e0..161fd27f03 100644--- a/crates/router/tests/connectors/wise.rs+++ b/crates/router/tests/connectors/wise.rs@@ -121,11 +121,7 @@ async fn should_create_bacs_payout() {// Create payoutlet create_res: types::PayoutsResponseData = CONNECTOR- .create_payout(- Some(recipient_res.connector_payout_id),- payout_type,- payout_info,- )+ .create_payout(recipient_res.connector_payout_id, payout_type, payout_info).await.expect("Payout bank creation response");assert_eq!(@@ -150,11 +146,7 @@ async fn should_create_and_fulfill_bacs_payout() {enums::PayoutStatus::RequiresCreation);let response = CONNECTOR- .create_and_fulfill_payout(- Some(recipient_res.connector_payout_id),- payout_type,- payout_info,- )+ .create_and_fulfill_payout(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/storage_impl/src/mock_db/payout_attempt.rs b/crates/storage_impl/src/mock_db/payout_attempt.rsindex 8f26b8c581..652dde93a6 100644--- a/crates/storage_impl/src/mock_db/payout_attempt.rs+++ b/crates/storage_impl/src/mock_db/payout_attempt.rs@@ -45,6 +45,16 @@ impl PayoutAttemptInterface for MockDb {Err(StorageError::MockDbError)?}+ async fn find_payout_attempt_by_merchant_id_connector_payout_id(+ &self,+ _merchant_id: &str,+ _connector_payout_id: &str,+ _storage_scheme: storage_enums::MerchantStorageScheme,+ ) -> CustomResult<PayoutAttempt, StorageError> {+ // TODO: Implement function for `MockDb`+ Err(StorageError::MockDbError)?+ }+async fn get_filters_for_payouts(&self,_payouts: &[Payouts],diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rsindex 91c1669db3..5f04592596 100644--- a/crates/storage_impl/src/payouts/payout_attempt.rs+++ b/crates/storage_impl/src/payouts/payout_attempt.rs@@ -9,6 +9,7 @@ use diesel_models::{PayoutAttempt as DieselPayoutAttempt, PayoutAttemptNew as DieselPayoutAttemptNew,PayoutAttemptUpdate as DieselPayoutAttemptUpdate,},+ reverse_lookup::ReverseLookup,ReverseLookupNew,};use error_stack::ResultExt;@@ -158,7 +159,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {MerchantStorageScheme::RedisKv => {let key_str = key.to_string();- let diesel_payout_update = payout_update.to_storage_model();+ let diesel_payout_update = payout_update.clone().to_storage_model();let origin_diesel_payout = this.clone().to_storage_model();let diesel_payout = diesel_payout_update@@ -181,6 +182,42 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {},};+ let updated_attempt = PayoutAttempt::from_storage_model(+ payout_update+ .to_storage_model()+ .apply_changeset(this.clone().to_storage_model()),+ );+ let old_connector_payout_id = this.connector_payout_id.clone();++ match (+ old_connector_payout_id,+ updated_attempt.connector_payout_id.clone(),+ ) {+ (Some(old), Some(new)) if old != new => {+ add_connector_payout_id_to_reverse_lookup(+ self,+ key_str.as_str(),+ this.merchant_id.as_str(),+ updated_attempt.payout_attempt_id.as_str(),+ new.as_str(),+ storage_scheme,+ )+ .await?;+ }+ (None, Some(new)) => {+ add_connector_payout_id_to_reverse_lookup(+ self,+ key_str.as_str(),+ this.merchant_id.as_str(),+ updated_attempt.payout_attempt_id.as_str(),+ new.as_str(),+ storage_scheme,+ )+ .await?;+ }+ _ => {}+ }+kv_wrapper::<(), _, _>(self,KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), redis_entry),@@ -256,6 +293,64 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {}}+ #[instrument(skip_all)]+ async fn find_payout_attempt_by_merchant_id_connector_payout_id(+ &self,+ merchant_id: &str,+ connector_payout_id: &str,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<PayoutAttempt, errors::StorageError> {+ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => {+ self.router_store+ .find_payout_attempt_by_merchant_id_connector_payout_id(+ merchant_id,+ connector_payout_id,+ storage_scheme,+ )+ .await+ }+ MerchantStorageScheme::RedisKv => {+ let lookup_id = format!("po_conn_payout_{merchant_id}_{connector_payout_id}");+ let lookup = fallback_reverse_lookup_not_found!(+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)+ .await,+ self.router_store+ .find_payout_attempt_by_merchant_id_connector_payout_id(+ merchant_id,+ connector_payout_id,+ storage_scheme,+ )+ .await+ );+ let key = PartitionKey::CombinationKey {+ combination: &lookup.pk_id,+ };+ Box::pin(utils::try_redis_get_else_try_database_get(+ async {+ kv_wrapper(+ self,+ KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id),+ key,+ )+ .await?+ .try_into_hget()+ },+ || async {+ self.router_store+ .find_payout_attempt_by_merchant_id_connector_payout_id(+ merchant_id,+ connector_payout_id,+ storage_scheme,+ )+ .await+ },+ ))+ .await+ }+ }+ }+#[instrument(skip_all)]async fn get_filters_for_payouts(&self,@@ -330,6 +425,27 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {})}+ #[instrument(skip_all)]+ async fn find_payout_attempt_by_merchant_id_connector_payout_id(+ &self,+ merchant_id: &str,+ connector_payout_id: &str,+ _storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<PayoutAttempt, errors::StorageError> {+ let conn = pg_connection_read(self).await?;+ DieselPayoutAttempt::find_by_merchant_id_connector_payout_id(+ &conn,+ merchant_id,+ connector_payout_id,+ )+ .await+ .map(PayoutAttempt::from_storage_model)+ .map_err(|er| {+ let new_err = diesel_error_to_data_error(er.current_context());+ er.change_context(new_err)+ })+ }+#[instrument(skip_all)]async fn get_filters_for_payouts(&self,@@ -517,3 +633,26 @@ impl DataModelExt for PayoutAttemptUpdate {todo!("Reverse map should no longer be needed")}}++#[inline]+#[instrument(skip_all)]+async fn add_connector_payout_id_to_reverse_lookup<T: DatabaseStore>(+ store: &KVRouterStore<T>,+ key: &str,+ merchant_id: &str,+ updated_attempt_attempt_id: &str,+ connector_payout_id: &str,+ storage_scheme: MerchantStorageScheme,+) -> CustomResult<ReverseLookup, errors::StorageError> {+ let field = format!("poa_{}", updated_attempt_attempt_id);+ let reverse_lookup_new = ReverseLookupNew {+ lookup_id: format!("po_conn_payout_{}_{}", merchant_id, connector_payout_id),+ pk_id: key.to_owned(),+ sk_id: field.clone(),+ source: "payout_attempt".to_string(),+ updated_by: storage_scheme.to_string(),+ };+ store+ .insert_reverse_lookup(reverse_lookup_new, storage_scheme)+ .await+}diff --git a/migrations/2024-05-16-133628_make_connector_payout_id_nullalble/down.sql b/migrations/2024-05-16-133628_make_connector_payout_id_nullalble/down.sqlnew file mode 100644index 0000000000..d2c43f15d6--- /dev/null+++ b/migrations/2024-05-16-133628_make_connector_payout_id_nullalble/down.sql@@ -0,0 +1,7 @@+-- This file should undo anything in `up.sql`+UPDATE payout_attempt+SET connector_payout_id = ''+WHERE connector_payout_id IS NULL;++ALTER TABLE payout_attempt+ALTER COLUMN connector_payout_id SET NOT NULL;\ No newline at end of filediff --git a/migrations/2024-05-16-133628_make_connector_payout_id_nullalble/up.sql b/migrations/2024-05-16-133628_make_connector_payout_id_nullalble/up.sqlnew file mode 100644index 0000000000..f98a2d78c6--- /dev/null+++ b/migrations/2024-05-16-133628_make_connector_payout_id_nullalble/up.sql@@ -0,0 +1,4 @@+-- Your SQL goes here+ALTER TABLE payout_attempt ALTER COLUMN connector_payout_id DROP NOT NULL;++UPDATE payout_attempt SET connector_payout_id = NULL WHERE connector_payout_id = '';\ No newline at end of filediff --git a/migrations/2024-05-19-144009_add_new_value_to_event_type/down.sql b/migrations/2024-05-19-144009_add_new_value_to_event_type/down.sqlnew file mode 100644index 0000000000..027b7d63fd--- /dev/null+++ b/migrations/2024-05-19-144009_add_new_value_to_event_type/down.sql@@ -0,0 +1 @@+SELECT 1;\ No newline at end of filediff --git a/migrations/2024-05-19-144009_add_new_value_to_event_type/up.sql b/migrations/2024-05-19-144009_add_new_value_to_event_type/up.sqlnew file mode 100644index 0000000000..825a7df4e0--- /dev/null+++ b/migrations/2024-05-19-144009_add_new_value_to_event_type/up.sql@@ -0,0 +1,12 @@+-- Your SQL goes here+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payout_success';+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payout_failed';+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payout_processing';+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payout_cancelled';+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payout_initiated';+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payout_expired';+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payout_reversed';++ALTER TYPE "EventObjectType" ADD VALUE IF NOT EXISTS 'payout_details';++ALTER TYPE "EventClass" ADD VALUE IF NOT EXISTS 'payouts';\ No newline at end of filediff --git a/migrations/2024-05-27-190323_add_new_status_to_payout_status/down.sql b/migrations/2024-05-27-190323_add_new_status_to_payout_status/down.sqlnew file mode 100644index 0000000000..027b7d63fd--- /dev/null+++ b/migrations/2024-05-27-190323_add_new_status_to_payout_status/down.sql@@ -0,0 +1 @@+SELECT 1;\ No newline at end of filediff --git a/migrations/2024-05-27-190323_add_new_status_to_payout_status/up.sql b/migrations/2024-05-27-190323_add_new_status_to_payout_status/up.sqlnew file mode 100644index 0000000000..51cabba90f--- /dev/null+++ b/migrations/2024-05-27-190323_add_new_status_to_payout_status/up.sql@@ -0,0 +1,4 @@+-- Your SQL goes here+ALTER TYPE "PayoutStatus" ADD VALUE IF NOT EXISTS 'initiated';+ALTER TYPE "PayoutStatus" ADD VALUE IF NOT EXISTS 'expired';+ALTER TYPE "PayoutStatus" ADD VALUE IF NOT EXISTS 'reversed';\ No newline at end of filediff --git a/migrations/2024-06-04-140449_create_index_for_connector_payout_id_and_merchant_id_in_payout_attempt/down.sql b/migrations/2024-06-04-140449_create_index_for_connector_payout_id_and_merchant_id_in_payout_attempt/down.sqlnew file mode 100644index 0000000000..a839f17e8c--- /dev/null+++ b/migrations/2024-06-04-140449_create_index_for_connector_payout_id_and_merchant_id_in_payout_attempt/down.sql@@ -0,0 +1 @@+DROP INDEX IF EXISTS connector_payout_id_merchant_id_index;\ No newline at end of filediff --git a/migrations/2024-06-04-140449_create_index_for_connector_payout_id_and_merchant_id_in_payout_attempt/up.sql b/migrations/2024-06-04-140449_create_index_for_connector_payout_id_and_merchant_id_in_payout_attempt/up.sqlnew file mode 100644index 0000000000..cd52c02b9e--- /dev/null+++ b/migrations/2024-06-04-140449_create_index_for_connector_payout_id_and_merchant_id_in_payout_attempt/up.sql@@ -0,0 +1 @@+CREATE INDEX connector_payout_id_merchant_id_index ON payout_attempt (connector_payout_id, merchant_id);\ No newline at end of filediff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.jsonindex 87f05f3b67..cffea67133 100644--- a/openapi/openapi_spec.json+++ b/openapi/openapi_spec.json@@ -9045,7 +9045,14 @@"dispute_won","dispute_lost","mandate_active",- "mandate_revoked"+ "mandate_revoked",+ "payout_success",+ "payout_failed",+ "payout_initiated",+ "payout_processing",+ "payout_cancelled",+ "payout_expired",+ "payout_reversed"]},"ExtendedCardInfo": {@@ -12367,6 +12374,25 @@"$ref": "#/components/schemas/MandateResponse"}}+ },+ {+ "type": "object",+ "title": "PayoutCreateResponse",+ "required": [+ "type",+ "object"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "payout_details"+ ]+ },+ "object": {+ "$ref": "#/components/schemas/PayoutCreateResponse"+ }+ }}],"discriminator": {@@ -16947,6 +16973,9 @@"success","failed","cancelled",+ "initiated",+ "expired",+ "reversed","pending","ineligible","requires_creation",