Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(platform): support platform-aware outgoing webhook delivery (#11643)

Sandeep Kumar91ff74e2058c
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index bdbcc7dd05..efb5f18233 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -20324,6 +20324,12 @@
"example": "evt_018e31720d1b7a2b82677d3032cab959",
"maxLength": 64
},
+ "processor_merchant_id": {
+ "type": "string",
+ "description": "The identifier for the Processor Merchant Account.",
+ "nullable": true,
+ "maxLength": 64
+ },
"created": {
"type": "string",
"format": "date-time",
@@ -26754,7 +26760,7 @@
"properties": {
"merchant_id": {
"type": "string",
- "description": "The merchant id of the merchant"
+ "description": "The provider merchant id (platform/business owner)"
},
"event_id": {
"type": "string",
@@ -26770,6 +26776,11 @@
"type": "string",
"format": "date-time",
"description": "The time at which webhook was sent"
+ },
+ "processor_merchant_id": {
+ "type": "string",
+ "description": "The merchant id of the merchant account whose connector credentials are used for payment processing",
+ "nullable": true
}
}
},
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 5c950a39b1..8d56a94bed 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -13948,6 +13948,12 @@
"example": "evt_018e31720d1b7a2b82677d3032cab959",
"maxLength": 64
},
+ "processor_merchant_id": {
+ "type": "string",
+ "description": "The identifier for the Processor Merchant Account.",
+ "nullable": true,
+ "maxLength": 64
+ },
"created": {
"type": "string",
"format": "date-time",
@@ -19784,7 +19790,7 @@
"properties": {
"merchant_id": {
"type": "string",
- "description": "The merchant id of the merchant"
+ "description": "The provider merchant id (platform/business owner)"
},
"event_id": {
"type": "string",
@@ -19800,6 +19806,11 @@
"type": "string",
"format": "date-time",
"description": "The time at which webhook was sent"
+ },
+ "processor_merchant_id": {
+ "type": "string",
+ "description": "The merchant id of the merchant account whose connector credentials are used for payment processing",
+ "nullable": true
}
}
},
diff --git a/crates/analytics/docs/clickhouse/scripts/outgoing_webhook_events.sql b/crates/analytics/docs/clickhouse/scripts/outgoing_webhook_events.sql
index b703e06948..43fe9764be 100644
--- a/crates/analytics/docs/clickhouse/scripts/outgoing_webhook_events.sql
+++ b/crates/analytics/docs/clickhouse/scripts/outgoing_webhook_events.sql
@@ -16,7 +16,9 @@ CREATE TABLE outgoing_webhook_events_queue (
`initial_attempt_id` Nullable(String),
`status_code` Nullable(UInt16),
`delivery_attempt` LowCardinality(String),
- `created_at_timestamp` DateTime64(3)
+ `created_at_timestamp` DateTime64(3),
+ `processor_merchant_id` Nullable(String),
+ `initiator_merchant_id` Nullable(String)
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-outgoing-webhook-events',
kafka_group_name = 'hyper',
@@ -43,6 +45,8 @@ CREATE TABLE outgoing_webhook_events (
`delivery_attempt` LowCardinality(String),
`created_at` DateTime64(3),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `processor_merchant_id` Nullable(String),
+ `initiator_merchant_id` Nullable(String),
INDEX eventIndex event_type TYPE bloom_filter GRANULARITY 1,
INDEX webhookeventIndex outgoing_webhook_event_type TYPE bloom_filter GRANULARITY 1
) ENGINE = MergeTree PARTITION BY toStartOfDay(created_at)
@@ -73,7 +77,9 @@ CREATE TABLE outgoing_webhook_events_audit (
`status_code` Nullable(UInt16),
`delivery_attempt` LowCardinality(String),
`created_at` DateTime64(3),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4)
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `processor_merchant_id` Nullable(String),
+ `initiator_merchant_id` Nullable(String)
) ENGINE = MergeTree PARTITION BY merchant_id
ORDER BY
(merchant_id, payment_id) TTL inserted_at + toIntervalMonth(18) SETTINGS index_granularity = 8192;
@@ -118,7 +124,9 @@ CREATE MATERIALIZED VIEW outgoing_webhook_events_mv TO outgoing_webhook_events (
`status_code` Nullable(UInt16),
`delivery_attempt` LowCardinality(String),
`created_at` DateTime64(3),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4)
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `processor_merchant_id` Nullable(String),
+ `initiator_merchant_id` Nullable(String)
) AS
SELECT
merchant_id,
@@ -139,7 +147,9 @@ SELECT
status_code,
delivery_attempt,
created_at_timestamp AS created_at,
- now() AS inserted_at
+ now() AS inserted_at,
+ processor_merchant_id,
+ initiator_merchant_id
FROM
outgoing_webhook_events_queue
WHERE
@@ -163,7 +173,9 @@ CREATE MATERIALIZED VIEW outgoing_webhook_events_audit_mv TO outgoing_webhook_ev
`status_code` Nullable(UInt16),
`delivery_attempt` LowCardinality(String),
`created_at` DateTime64(3),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4)
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `processor_merchant_id` Nullable(String),
+ `initiator_merchant_id` Nullable(String)
) AS
SELECT
merchant_id,
@@ -183,7 +195,9 @@ SELECT
status_code,
delivery_attempt,
created_at_timestamp AS created_at,
- now() AS inserted_at
+ now() AS inserted_at,
+ processor_merchant_id,
+ initiator_merchant_id
FROM
outgoing_webhook_events_queue
WHERE
@@ -249,4 +263,4 @@ SELECT
FROM
outgoing_webhook_events_queue
WHERE
- length(_error) > 0;
\ No newline at end of file
+ length(_error) > 0;
diff --git a/crates/analytics/src/outgoing_webhook_event/events.rs b/crates/analytics/src/outgoing_webhook_event/events.rs
index 441a2fe6e6..b7ee89aaec 100644
--- a/crates/analytics/src/outgoing_webhook_event/events.rs
+++ b/crates/analytics/src/outgoing_webhook_event/events.rs
@@ -97,6 +97,7 @@ pub struct OutgoingWebhookLogsResult {
pub content: Option<String>,
pub is_error: bool,
pub error: Option<String>,
+ pub initiator_merchant_id: Option<common_utils::id_type::MerchantId>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
}
diff --git a/crates/api_models/src/webhook_events.rs b/crates/api_models/src/webhook_events.rs
index 0537dec0ca..f7878b1693 100644
--- a/crates/api_models/src/webhook_events.rs
+++ b/crates/api_models/src/webhook_events.rs
@@ -95,6 +95,10 @@ pub struct EventListItemResponse {
#[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")]
pub initial_attempt_id: String,
+ /// The identifier for the Processor Merchant Account.
+ #[schema(max_length = 64, value_type = Option<String>)]
+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+
/// Time at which the event was created.
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601")]
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index 58b2d444b7..62acb9658f 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -443,7 +443,7 @@ pub struct PayoutWebhookUpdate {
#[derive(Debug, Serialize, ToSchema)]
pub struct OutgoingWebhook {
- /// The merchant id of the merchant
+ /// The provider merchant id (platform/business owner)
#[schema(value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
@@ -460,6 +460,10 @@ pub struct OutgoingWebhook {
/// The time at which webhook was sent
#[serde(default, with = "custom_serde::iso8601")]
pub timestamp: PrimitiveDateTime,
+
+ /// The merchant id of the merchant account whose connector credentials are used for payment processing
+ #[schema(value_type = Option<String>)]
+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 4eb1df519d..2c30511112 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -1459,6 +1459,19 @@ impl_enum_str!(
}
);
+impl CreatedBy {
+ /// Returns `true` if the creator is the provider (platform) merchant, i.e. an API-triggered
+ /// creation whose `merchant_id` matches `provider_merchant_id`.
+ pub fn is_provider_initiated(&self, provider_merchant_id: &id_type::MerchantId) -> bool {
+ match self {
+ Self::Api { merchant_id } => id_type::MerchantId::wrap(merchant_id.clone())
+ .map(|parsed_merchant_id| parsed_merchant_id == *provider_merchant_id)
+ .unwrap_or_default(),
+ Self::Jwt { .. } | Self::Invalid | Self::EmbeddedToken { .. } => false,
+ }
+ }
+}
+
/// Trait for enums created with `impl_enum_str!` macro that have an `Invalid` variant.
/// This trait allows generic functions to check if a parsed enum value is invalid.
pub trait HasInvalidVariant {
diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs
index 588cad3779..305a276a63 100644
--- a/crates/diesel_models/src/events.rs
+++ b/crates/diesel_models/src/events.rs
@@ -27,6 +27,8 @@ pub struct EventNew {
pub delivery_attempt: Option<storage_enums::WebhookDeliveryAttempt>,
pub metadata: Option<EventMetadata>,
pub is_overall_delivery_successful: Option<bool>,
+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+ pub initiator_merchant_id: Option<common_utils::id_type::MerchantId>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -60,6 +62,8 @@ pub struct Event {
pub delivery_attempt: Option<storage_enums::WebhookDeliveryAttempt>,
pub metadata: Option<EventMetadata>,
pub is_overall_delivery_successful: Option<bool>,
+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+ pub initiator_merchant_id: Option<common_utils::id_type::MerchantId>,
}
#[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)]
diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rs
index 5d9694ba3e..173d57a9e3 100644
--- a/crates/diesel_models/src/query/events.rs
+++ b/crates/diesel_models/src/query/events.rs
@@ -1,11 +1,17 @@
use std::collections::HashSet;
+use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{
- associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods,
+ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods,
+ NullableExpressionMethods, QueryDsl,
};
use error_stack::ResultExt;
+use router_env::logger;
-use super::generics;
+use super::{
+ generics,
+ generics::db_metrics::{track_database_call, DatabaseOperation},
+};
use crate::{
errors::DatabaseError,
events::{Event, EventNew, EventUpdateInternal},
@@ -20,6 +26,14 @@ impl EventNew {
}
impl Event {
+ pub async fn find_by_event_id(conn: &PgPooledConn, event_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::event_id.eq(event_id.to_owned()),
+ )
+ .await
+ }
+
pub async fn find_by_merchant_id_event_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
@@ -48,6 +62,28 @@ impl Event {
.await
}
+ pub async fn find_by_initiator_merchant_id_idempotent_event_id(
+ conn: &PgPooledConn,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ idempotent_event_id: &str,
+ ) -> StorageResult<Self> {
+ // Fallback on merchant_id for rows with NULL initiator_merchant_id to
+ // handle events created during staggered rollout by older code.
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::idempotent_event_id
+ .eq(idempotent_event_id.to_owned())
+ .and(
+ dsl::initiator_merchant_id
+ .eq(initiator_merchant_id.to_owned())
+ .or(dsl::initiator_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
+ ),
+ )
+ .await
+ }
+
pub async fn list_initial_attempts_by_merchant_id_primary_object_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
@@ -99,14 +135,6 @@ impl Event {
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<Vec<Self>> {
- use async_bb8_diesel::AsyncRunQueryDsl;
- use diesel::{debug_query, pg::Pg, QueryDsl};
- use error_stack::ResultExt;
- use router_env::logger;
-
- use super::generics::db_metrics::{track_database_call, DatabaseOperation};
- use crate::errors::DatabaseError;
-
let mut query = Self::table()
.filter(
dsl::event_id
@@ -152,6 +180,121 @@ impl Event {
.await
}
+ pub async fn list_initial_attempts_by_initiator_merchant_id_primary_object_id(
+ conn: &PgPooledConn,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ primary_object_id: &str,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ ) -> StorageResult<Vec<Self>> {
+ // Fallback on merchant_id for rows with NULL initiator_merchant_id to
+ // handle events created during staggered rollout by older code. This
+ // fallback is correct for standard merchants where merchant_id equals
+ // the webhook recipient.
+ let mut query = Self::table()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(
+ dsl::initiator_merchant_id
+ .eq(initiator_merchant_id.to_owned())
+ .or(dsl::initiator_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
+ )
+ .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
+ )
+ .order(dsl::created_at.desc())
+ .into_boxed();
+
+ if let Some(profile_id) = profile_id {
+ query = query.filter(dsl::business_profile_id.eq(profile_id));
+ }
+
+ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
+
+ track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
+ .await
+ .change_context(DatabaseError::Others)
+ .attach_printable(
+ "Error filtering initial events by initiator merchant ID and primary object ID",
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub async fn list_initial_attempts_by_initiator_merchant_id_constraints(
+ conn: &PgPooledConn,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> StorageResult<Vec<Self>> {
+ // Fallback on merchant_id for rows with NULL initiator_merchant_id to
+ // handle events created during staggered rollout by older code. This
+ // fallback is correct for standard merchants where merchant_id equals
+ // the webhook recipient.
+ let mut query = Self::table()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(
+ dsl::initiator_merchant_id
+ .eq(initiator_merchant_id.to_owned())
+ .or(dsl::initiator_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
+ ),
+ )
+ .order(dsl::created_at.desc())
+ .into_boxed();
+
+ query = Self::apply_filters(
+ query,
+ None,
+ (dsl::created_at, created_after, created_before),
+ limit,
+ offset,
+ event_types,
+ is_delivered,
+ );
+
+ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
+
+ track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
+ .await
+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
+ .attach_printable("Error filtering events by constraints")
+ }
+
+ pub async fn list_by_initiator_merchant_id_initial_attempt_id(
+ conn: &PgPooledConn,
+ initial_attempt_id: &str,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ ) -> StorageResult<Vec<Self>> {
+ // Fallback on merchant_id for rows with NULL initiator_merchant_id to
+ // handle events created during staggered rollout by older code.
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::initial_attempt_id
+ .eq(initial_attempt_id.to_owned())
+ .and(
+ dsl::initiator_merchant_id
+ .eq(initiator_merchant_id.to_owned())
+ .or(dsl::initiator_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
+ ),
+ None,
+ None,
+ Some(dsl::created_at.desc()),
+ )
+ .await
+ }
+
pub async fn list_initial_attempts_by_profile_id_primary_object_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
@@ -203,14 +346,6 @@ impl Event {
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<Vec<Self>> {
- use async_bb8_diesel::AsyncRunQueryDsl;
- use diesel::{debug_query, pg::Pg, QueryDsl};
- use error_stack::ResultExt;
- use router_env::logger;
-
- use super::generics::db_metrics::{track_database_call, DatabaseOperation};
- use crate::errors::DatabaseError;
-
let mut query = Self::table()
.filter(
dsl::event_id
@@ -256,6 +391,20 @@ impl Event {
.await
}
+ pub async fn update_by_event_id(
+ conn: &PgPooledConn,
+ event_id: &str,
+ event: EventUpdateInternal,
+ ) -> StorageResult<Self> {
+ generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(conn, dsl::event_id.eq(event_id.to_owned()), event)
+ .await
+ }
+
pub async fn update_by_merchant_id_event_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
@@ -350,21 +499,102 @@ impl Event {
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<i64> {
- use async_bb8_diesel::AsyncRunQueryDsl;
- use diesel::{debug_query, pg::Pg, QueryDsl};
- use error_stack::ResultExt;
- use router_env::logger;
+ let mut query = Self::table()
+ .count()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(dsl::merchant_id.eq(merchant_id.to_owned())),
+ )
+ .into_boxed();
+
+ query = Self::apply_filters(
+ query,
+ profile_id,
+ (dsl::created_at, created_after, created_before),
+ None,
+ None,
+ event_types,
+ is_delivered,
+ );
- use super::generics::db_metrics::{track_database_call, DatabaseOperation};
- use crate::errors::DatabaseError;
+ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
+ track_database_call::<Self, _, _>(
+ query.get_result_async::<i64>(conn),
+ DatabaseOperation::Count,
+ )
+ .await
+ .change_context(DatabaseError::Others)
+ .attach_printable("Error counting events by constraints")
+ }
+
+ pub async fn count_initial_attempts_by_profile_id_constraints(
+ conn: &PgPooledConn,
+ profile_id: &common_utils::id_type::ProfileId,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> StorageResult<i64> {
let mut query = Self::table()
.count()
.filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
- .and(dsl::merchant_id.eq(merchant_id.to_owned())),
+ .and(dsl::business_profile_id.eq(profile_id.to_owned())),
+ )
+ .into_boxed();
+
+ query = Self::apply_filters(
+ query,
+ None,
+ (dsl::created_at, created_after, created_before),
+ None,
+ None,
+ event_types,
+ is_delivered,
+ );
+
+ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
+
+ track_database_call::<Self, _, _>(
+ query.get_result_async::<i64>(conn),
+ DatabaseOperation::Count,
+ )
+ .await
+ .change_context(DatabaseError::Others)
+ .attach_printable("Error counting events by profile_id constraints")
+ }
+
+ pub async fn count_initial_attempts_by_initiator_merchant_id_constraints(
+ conn: &PgPooledConn,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> StorageResult<i64> {
+ // Fallback on merchant_id for rows with NULL initiator_merchant_id to
+ // handle events created during staggered rollout by older code. This
+ // fallback is correct for standard merchants where merchant_id equals
+ // the webhook recipient.
+ let mut query = Self::table()
+ .count()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(
+ dsl::initiator_merchant_id
+ .eq(initiator_merchant_id.to_owned())
+ .or(dsl::initiator_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
+ ),
)
.into_boxed();
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 763d1f031b..37ce81a283 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -601,6 +601,10 @@ diesel::table! {
delivery_attempt -> Nullable<WebhookDeliveryAttempt>,
metadata -> Nullable<Jsonb>,
is_overall_delivery_successful -> Nullable<Bool>,
+ #[max_length = 64]
+ processor_merchant_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ initiator_merchant_id -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index c0c5cda6a3..a37519dfe6 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -612,6 +612,10 @@ diesel::table! {
delivery_attempt -> Nullable<WebhookDeliveryAttempt>,
metadata -> Nullable<Jsonb>,
is_overall_delivery_successful -> Nullable<Bool>,
+ #[max_length = 64]
+ processor_merchant_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ initiator_merchant_id -> Nullable<Varchar>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/platform.rs b/crates/hyperswitch_domain_models/src/platform.rs
index 4b68cbfab4..9a7ea46421 100644
--- a/crates/hyperswitch_domain_models/src/platform.rs
+++ b/crates/hyperswitch_domain_models/src/platform.rs
@@ -122,6 +122,31 @@ impl Initiator {
}
}
+ /// Returns the merchant_id of the entity that initiated the operation.
+ ///
+ /// Available for `Api` and `EmbeddedToken` initiators which carry a merchant_id.
+ /// Returns `None` for `Jwt` (user-based) and `Admin` initiators.
+ pub fn get_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId> {
+ match self {
+ Self::Api { merchant_id, .. } | Self::EmbeddedToken { merchant_id, .. } => {
+ Some(merchant_id)
+ }
+ Self::Jwt { .. } | Self::Admin => None,
+ }
+ }
+
+ /// Returns `true` if the initiator is a platform merchant
+ /// (i.e. the merchant account type is `Platform`).
+ pub fn is_platform(&self) -> bool {
+ matches!(
+ self,
+ Self::Api {
+ merchant_account_type: common_enums::MerchantAccountType::Platform,
+ ..
+ }
+ )
+ }
+
/// Computes the initiator context for API responses.
///
/// # Returns
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index c8f6f5a78b..4bc1caa3c8 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -147,7 +147,7 @@ pub async fn retrieve_dispute(
id: payment_attempt.profile_id.get_string_repr().to_owned(),
})?;
- update_dispute_data(
+ Box::pin(update_dispute_data(
&state,
platform.clone(),
business_profile,
@@ -155,7 +155,7 @@ pub async fn retrieve_dispute(
dispute_sync_response,
payment_attempt,
dispute.connector.as_str(),
- )
+ ))
.await
.attach_printable("Dispute update failed")?
} else {
@@ -924,16 +924,24 @@ pub async fn update_dispute_data(
let disputes_response: dispute_models::DisputeResponse = dispute_object.clone().foreign_into();
let event_type: storage_enums::EventType = dispute_details.dispute_status.into();
+ let webhook_recipient = webhooks::utils::resolve_webhook_recipient_from_created_by(
+ state,
+ &platform,
+ &business_profile,
+ payment_attempt.created_by.as_ref(),
+ )
+ .await?;
+
Box::pin(webhooks::create_event_and_trigger_outgoing_webhook(
state.clone(),
- platform.get_processor().clone(),
- business_profile,
+ platform.clone(),
event_type,
storage_enums::EventClass::Disputes,
dispute_object.dispute_id.clone(),
storage_enums::EventObjectType::DisputeDetails,
api::OutgoingWebhookContent::DisputeDetails(Box::new(disputes_response.clone())),
Some(dispute_object.created_at),
+ webhook_recipient,
))
.await?;
Ok(disputes_response)
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a7c89e9c10..bb52ce2a55 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1460,8 +1460,7 @@ where
.await?;
utils::trigger_payments_webhook(
- platform.get_processor(),
- platform.get_initiator(),
+ platform,
business_profile,
cloned_payment_data,
state,
@@ -1710,8 +1709,7 @@ where
let cloned_payment_data = payment_data.clone();
utils::trigger_payments_webhook(
- platform.get_processor(),
- platform.get_initiator(),
+ &platform,
business_profile,
cloned_payment_data,
state,
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 94a159ee73..3e3860320e 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -2895,7 +2895,13 @@ pub async fn trigger_webhook_and_handle_response(
payout_data: &PayoutData,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let response = response_handler(state, platform, payout_data).await?;
- utils::trigger_payouts_webhook(state, platform, &response).await?;
+ utils::trigger_payouts_webhook(
+ state,
+ platform,
+ &response,
+ payout_data.payouts.created_by.as_ref(),
+ )
+ .await?;
Ok(services::ApplicationResponse::Json(response))
}
diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs
index 8b8d7cb6c2..20289298d1 100644
--- a/crates/router/src/core/revenue_recovery/types.rs
+++ b/crates/router/src/core/revenue_recovery/types.rs
@@ -41,6 +41,7 @@ use crate::{
revenue_recovery::{self as revenue_recovery_core, pcr, perform_calculate_workflow},
webhooks::{
create_event_and_trigger_outgoing_webhook, recovery_incoming as recovery_incoming_flow,
+ utils,
},
},
db::StorageInterface,
@@ -1592,16 +1593,26 @@ impl RevenueRecoveryOutgoingWebhook {
api_models::webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(
response,
));
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ state,
+ platform,
+ profile,
+ payment_intent.created_by.as_ref(),
+ )
+ .await
+ .change_context(errors::RecoveryError::InvalidTask)
+ .attach_printable("Failed to resolve webhook recipient for revenue recovery")?;
+
create_event_and_trigger_outgoing_webhook(
state.clone(),
- profile.clone(),
- platform.get_processor().get_key_store(),
+ platform.clone(),
event_status,
event_class,
payment_attempt_id,
common_enums::EventObjectType::PaymentDetails,
outgoing_webhook_content,
payment_intent.created_at,
+ webhook_recipient,
)
.await
.change_context(errors::RecoveryError::InvalidTask)
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 232cd37484..cae45bef12 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -37,15 +37,15 @@ use crate::{
api_locking,
configs::dimension_state,
errors::{self, CustomResult, RouterResponse, StorageErrorExt},
- metrics, payment_methods,
- payment_methods::cards,
+ metrics,
+ payment_methods::{self, cards},
payments::{self, tokenization, PaymentIntentStateMetadataExt},
refunds, relay,
unified_authentication_service::{
types::UNIFIED_AUTHENTICATION_SERVICE, utils as uas_utils,
},
unified_connector_service, utils as core_utils,
- webhooks::network_tokenization_incoming,
+ webhooks::{network_tokenization_incoming, utils},
},
events::api_logs::ApiEvent,
logger,
@@ -818,8 +818,8 @@ async fn network_token_incoming_webhooks_core<W: types::OutgoingWebhookType>(
let payment_method =
network_tokenization_incoming::fetch_payment_method_for_network_token_webhooks(
state,
- platform.get_processor().get_account(),
- platform.get_processor().get_key_store(),
+ platform.get_provider().get_account(),
+ platform.get_provider().get_key_store(),
&payment_method_id,
)
.await?;
@@ -1017,16 +1017,23 @@ async fn payments_incoming_webhook_flow(
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ payment_attempt.created_by.as_ref(),
+ )
+ .await?;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
+ webhook_recipient,
))
.await?;
};
@@ -1320,10 +1327,17 @@ async fn payout_incoming_webhook_update_status(
let payout_create_response =
payouts::response_handler(&state, &platform, payout_data).await?;
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ payout_data.payouts.created_by.as_ref(),
+ )
+ .await?;
+
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
outgoing_event_type,
enums::EventClass::Payouts,
payout_data
@@ -1334,6 +1348,7 @@ async fn payout_incoming_webhook_update_status(
enums::EventObjectType::PayoutDetails,
api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)),
Some(payout_data.payout_attempt.created_at),
+ webhook_recipient,
))
.await?;
}
@@ -1390,10 +1405,17 @@ async fn payout_incoming_webhook_retrieve_status(
if let Some(outgoing_event_type) = event_type {
let payout_response = payouts::response_handler(&state, &platform, payout_data).await?;
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ payout_data.payouts.created_by.as_ref(),
+ )
+ .await?;
+
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
outgoing_event_type,
enums::EventClass::Payouts,
payout_data
@@ -1404,6 +1426,7 @@ async fn payout_incoming_webhook_retrieve_status(
enums::EventObjectType::PayoutDetails,
api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_response)),
Some(payout_data.payout_attempt.created_at),
+ webhook_recipient,
))
.await?;
}
@@ -1617,16 +1640,27 @@ async fn refunds_incoming_webhook_flow(
if let Some(outgoing_event_type) = event_type {
let refund_response: api_models::refunds::RefundResponse =
updated_refund.clone().foreign_into();
+ let refund_created_by = updated_refund
+ .created_by
+ .as_deref()
+ .and_then(|created_by| created_by.parse::<common_utils::types::CreatedBy>().ok());
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ refund_created_by.as_ref(),
+ )
+ .await?;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
outgoing_event_type,
enums::EventClass::Refunds,
refund_id,
enums::EventObjectType::RefundDetails,
api::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
Some(updated_refund.created_at),
+ webhook_recipient,
))
.await?;
}
@@ -2003,10 +2037,17 @@ async fn external_authentication_incoming_webhook_flow(
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
+ let webhook_recipient =
+ utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ updated_authentication.created_by.as_ref(),
+ )
+ .await?;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
@@ -2015,6 +2056,7 @@ async fn external_authentication_incoming_webhook_flow(
payments_response,
)),
primary_object_created_at,
+ webhook_recipient,
))
.await?;
};
@@ -2101,16 +2143,23 @@ async fn mandates_incoming_webhook_flow(
);
let event_type: Option<enums::EventType> = updated_mandate.mandate_status.into();
if let Some(outgoing_event_type) = event_type {
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ None, // Mandates do not carry created_by, default to processor
+ )
+ .await?;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
outgoing_event_type,
enums::EventClass::Mandates,
updated_mandate.mandate_id.clone(),
enums::EventObjectType::MandateDetails,
api::OutgoingWebhookContent::MandateDetails(mandates_response),
Some(updated_mandate.created_at),
+ webhook_recipient,
))
.await?;
}
@@ -2210,16 +2259,23 @@ async fn frm_incoming_webhook_flow(
let event_type: Option<enums::EventType> = payments_response.status.into();
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ payment_attempt.created_by.as_ref(),
+ )
+ .await?;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
+ webhook_recipient,
))
.await?;
};
@@ -2339,16 +2395,24 @@ async fn disputes_incoming_webhook_flow(
let disputes_response = Box::new(dispute_object.clone().foreign_into());
let event_type: enums::EventType = dispute_object.dispute_status.into();
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ payment_attempt.created_by.as_ref(),
+ )
+ .await?;
+
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
event_type,
enums::EventClass::Disputes,
dispute_object.dispute_id.clone(),
enums::EventObjectType::DisputeDetails,
api::OutgoingWebhookContent::DisputeDetails(disputes_response),
Some(dispute_object.created_at),
+ webhook_recipient,
))
.await?;
metrics::INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC.add(1, &[]);
@@ -2374,7 +2438,7 @@ async fn bank_transfer_webhook_flow(
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
- let response = if source_verified {
+ let (response, created_by) = if source_verified {
let payment_attempt = get_payment_attempt_from_object_reference_id(
&state,
webhook_details.object_reference_id,
@@ -2382,6 +2446,7 @@ async fn bank_transfer_webhook_flow(
)
.await?;
let payment_id = payment_attempt.payment_id;
+ let created_by = payment_attempt.created_by.clone();
let request = api::PaymentsRequest {
payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
@@ -2389,7 +2454,7 @@ async fn bank_transfer_webhook_flow(
payment_token: payment_attempt.payment_token,
..Default::default()
};
- Box::pin(payments::payments_core::<
+ let response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
@@ -2409,11 +2474,15 @@ async fn bank_transfer_webhook_flow(
None,
HeaderPayload::with_source(common_enums::PaymentSource::Webhook),
))
- .await
+ .await;
+ (response, created_by)
} else {
- Err(report!(
- errors::ApiErrorResponse::WebhookAuthenticationFailed
- ))
+ (
+ Err(report!(
+ errors::ApiErrorResponse::WebhookAuthenticationFailed
+ )),
+ None,
+ )
};
match response? {
@@ -2426,16 +2495,23 @@ async fn bank_transfer_webhook_flow(
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ created_by.as_ref(),
+ )
+ .await?;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
- platform.get_processor().clone(),
- business_profile,
+ platform,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
+ webhook_recipient,
))
.await?;
}
@@ -2575,9 +2651,9 @@ async fn update_additional_payment_method_data(
let pm = db
.find_payment_method(
- platform.get_processor().get_key_store(),
+ platform.get_provider().get_key_store(),
payment_method_id.as_str(),
- platform.get_processor().get_account().storage_scheme,
+ platform.get_provider().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -2634,9 +2710,9 @@ async fn update_connector_mandate_details(
let payment_method_info = state
.store
.find_payment_method(
- platform.get_processor().get_key_store(),
+ platform.get_provider().get_key_store(),
payment_method_id,
- platform.get_processor().get_account().storage_scheme,
+ platform.get_provider().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -2741,10 +2817,10 @@ async fn update_connector_mandate_details(
state
.store
.update_payment_method(
- platform.get_processor().get_key_store(),
+ platform.get_provider().get_key_store(),
payment_method_info,
pm_update,
- platform.get_processor().get_account().storage_scheme,
+ platform.get_provider().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs
index 06ba942b3c..88ee3e094a 100644
--- a/crates/router/src/core/webhooks/incoming_v2.rs
+++ b/crates/router/src/core/webhooks/incoming_v2.rs
@@ -446,7 +446,7 @@ async fn payments_incoming_webhook_flow(
payments::CallConnectorAction::Trigger
};
let key_manager_state = &(&state).into();
- let payments_response = match webhook_details.object_reference_id {
+ let (payments_response, created_by) = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::PaymentId(id) => {
let get_trackers_response = get_trackers_response_for_payment_get_operation(
state.store.as_ref(),
@@ -508,6 +508,8 @@ async fn payments_incoming_webhook_flow(
))
.await?;
+ let created_by = payment_data.payment_attempt.created_by.clone();
+
let response = payment_data.generate_response(
&state,
connector_http_status_code,
@@ -526,7 +528,7 @@ async fn payments_incoming_webhook_flow(
.await?;
match response {
- Ok(value) => value,
+ Ok(value) => (value, created_by),
Err(err)
if matches!(
err.current_context(),
@@ -548,7 +550,7 @@ async fn payments_incoming_webhook_flow(
);
return Ok(WebhookResponseTracker::NoEffect);
}
- error @ Err(_) => error?,
+ Err(error) => Err(error)?,
}
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
@@ -567,17 +569,23 @@ async fn payments_incoming_webhook_flow(
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
- // TODO: trigger an outgoing webhook to merchant
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &profile,
+ created_by.as_ref(),
+ )
+ .await?;
Box::pin(create_event_and_trigger_outgoing_webhook(
state,
- profile,
- platform.get_processor().get_key_store(),
+ platform,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
+ webhook_recipient,
))
.await?;
};
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs
index de75938bb5..add56be468 100644
--- a/crates/router/src/core/webhooks/outgoing.rs
+++ b/crates/router/src/core/webhooks/outgoing.rs
@@ -49,28 +49,28 @@ use crate::{
#[instrument(skip_all)]
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
- processor: domain::Processor,
- business_profile: domain::Profile,
+ platform: domain::Platform,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: Option<time::PrimitiveDateTime>,
+ webhook_recipient: utils::WebhookRecipientContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
- let webhook_url_result = get_webhook_url_from_business_profile(&business_profile);
+ let webhook_url_result = get_webhook_url_from_business_profile(&webhook_recipient.profile);
if !state.conf.webhooks.outgoing_enabled
|| webhook_url_result.is_err()
|| webhook_url_result.as_ref().is_ok_and(String::is_empty)
{
logger::debug!(
- business_profile_id=?business_profile.get_id(),
+ business_profile_id=?webhook_recipient.profile.get_id(),
%idempotent_event_id,
"Outgoing webhooks are disabled in application configuration, or merchant webhook URL \
could not be obtained; skipping outgoing webhooks for event"
@@ -79,21 +79,26 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
}
let event_id = utils::generate_event_id();
- let merchant_id = business_profile.merchant_id.clone();
+ let provider_merchant_id = platform.get_provider().get_account().get_id().clone();
+ let processor_merchant_id = platform.get_processor().get_account().get_id().clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
- merchant_id: merchant_id.clone(),
+ merchant_id: provider_merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
+ processor_merchant_id: Some(processor_merchant_id.clone()),
};
- let request_content =
- get_outgoing_webhook_request(&processor, outgoing_webhook, &business_profile)
- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
- .attach_printable("Failed to construct outgoing webhook request content")?;
+ let request_content = get_outgoing_webhook_request(
+ &webhook_recipient.merchant_account,
+ outgoing_webhook,
+ &webhook_recipient.profile,
+ )
+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
@@ -105,8 +110,8 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
primary_object_id,
primary_object_type,
created_at: now,
- merchant_id: Some(business_profile.merchant_id.clone()),
- business_profile_id: Some(business_profile.get_id().to_owned()),
+ merchant_id: Some(provider_merchant_id.clone()),
+ business_profile_id: Some(webhook_recipient.profile.get_id().to_owned()),
primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
@@ -121,8 +126,8 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
.attach_printable("Failed to encode outgoing webhook request content")
.map(Secret::new)?,
),
- Identifier::Merchant(processor.get_key_store().merchant_id.clone()),
- processor.get_key_store().key.get_inner().peek(),
+ Identifier::Merchant(webhook_recipient.key_store.merchant_id.clone()),
+ webhook_recipient.key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
@@ -133,12 +138,14 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
+ processor_merchant_id: Some(processor_merchant_id.clone()),
+ initiator_merchant_id: Some(webhook_recipient.key_store.merchant_id.clone()),
};
let lock_value = utils::perform_redis_lock(
&state,
&idempotent_event_id,
- processor.get_account().get_id().to_owned(),
+ webhook_recipient.key_store.merchant_id.clone(),
)
.await?;
@@ -148,10 +155,10 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
if (state
.store
- .find_event_by_merchant_id_idempotent_event_id(
- &merchant_id,
+ .find_event_by_initiator_merchant_id_idempotent_event_id(
+ &webhook_recipient.key_store.merchant_id,
&idempotent_event_id,
- processor.get_key_store(),
+ &webhook_recipient.key_store,
)
.await)
.is_ok()
@@ -162,7 +169,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
utils::free_redis_lock(
&state,
&idempotent_event_id,
- processor.get_account().get_id().to_owned(),
+ webhook_recipient.key_store.merchant_id.clone(),
lock_value,
)
.await?;
@@ -171,7 +178,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
let event_insert_result = state
.store
- .insert_event(new_event, processor.get_key_store())
+ .insert_event(new_event, &webhook_recipient.key_store)
.await;
let event = match event_insert_result {
@@ -187,14 +194,15 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
utils::free_redis_lock(
&state,
&idempotent_event_id,
- processor.get_account().get_id().to_owned(),
+ webhook_recipient.key_store.merchant_id.clone(),
lock_value,
)
.await?;
let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker(
&*state.store,
- &business_profile,
+ &platform,
+ &webhook_recipient,
&event,
state.conf.application_source,
)
@@ -207,15 +215,19 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
})
.ok();
- let cloned_key_store = processor.get_key_store().clone();
+ let cloned_key_store = webhook_recipient.key_store.clone();
+ let cloned_provider_merchant_id = provider_merchant_id.clone();
+ let cloned_processor_merchant_id = processor_merchant_id.clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
- business_profile,
+ webhook_recipient.profile,
&cloned_key_store,
+ cloned_provider_merchant_id,
+ cloned_processor_merchant_id,
event,
request_content,
delivery_attempt,
@@ -236,6 +248,8 @@ pub(crate) async fn trigger_webhook_and_raise_event(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
+ provider_merchant_id: common_utils::id_type::MerchantId,
+ processor_merchant_id: common_utils::id_type::MerchantId,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
@@ -249,7 +263,6 @@ pub(crate) async fn trigger_webhook_and_raise_event(
"Attempting to send webhook"
);
- let merchant_id = business_profile.merchant_id.clone();
let trigger_webhook_result = trigger_webhook_to_merchant(
state.clone(),
business_profile,
@@ -265,7 +278,8 @@ pub(crate) async fn trigger_webhook_and_raise_event(
state,
trigger_webhook_result,
content,
- merchant_id,
+ provider_merchant_id,
+ processor_merchant_id,
event,
merchant_key_store,
)
@@ -334,13 +348,15 @@ async fn trigger_webhook_to_merchant(
);
logger::debug!(outgoing_webhook_response=?response);
+ let webhook_recipient_merchant_id = &business_profile.merchant_id;
+
match delivery_attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
- &business_profile.merchant_id,
+ webhook_recipient_merchant_id,
&event_id,
client_error,
delivery_attempt,
@@ -353,7 +369,6 @@ async fn trigger_webhook_to_merchant(
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
- &business_profile.merchant_id,
&event_id,
response,
)
@@ -363,14 +378,13 @@ async fn trigger_webhook_to_merchant(
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
- &business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
- &business_profile.merchant_id,
+ webhook_recipient_merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
@@ -378,7 +392,7 @@ async fn trigger_webhook_to_merchant(
} else {
error_response_handler(
state.clone(),
- &business_profile.merchant_id,
+ webhook_recipient_merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
@@ -398,7 +412,7 @@ async fn trigger_webhook_to_merchant(
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
- &business_profile.merchant_id,
+ webhook_recipient_merchant_id,
&event_id,
client_error,
delivery_attempt,
@@ -411,7 +425,6 @@ async fn trigger_webhook_to_merchant(
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
- &business_profile.merchant_id,
&event_id,
response,
)
@@ -421,14 +434,13 @@ async fn trigger_webhook_to_merchant(
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
- &business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
- &business_profile.merchant_id,
+ webhook_recipient_merchant_id,
Some(process_tracker),
"COMPLETED_BY_PT",
)
@@ -436,7 +448,7 @@ async fn trigger_webhook_to_merchant(
} else {
error_response_handler(
state.clone(),
- &business_profile.merchant_id,
+ webhook_recipient_merchant_id,
delivery_attempt,
status_code.as_u16(),
"An error occurred when sending webhook to merchant",
@@ -452,7 +464,7 @@ async fn trigger_webhook_to_merchant(
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
- &business_profile.merchant_id,
+ webhook_recipient_merchant_id,
&event_id,
client_error,
delivery_attempt,
@@ -465,18 +477,17 @@ async fn trigger_webhook_to_merchant(
let _updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
- &business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
- increment_webhook_outgoing_received_count(&business_profile.merchant_id);
+ increment_webhook_outgoing_received_count(webhook_recipient_merchant_id);
} else {
error_response_handler(
state,
- &business_profile.merchant_id,
+ webhook_recipient_merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
@@ -495,7 +506,8 @@ async fn raise_webhooks_analytics_event(
state: SessionState,
trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>,
content: Option<api::OutgoingWebhookContent>,
- merchant_id: common_utils::id_type::MerchantId,
+ provider_merchant_id: common_utils::id_type::MerchantId,
+ processor_merchant_id: common_utils::id_type::MerchantId,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) {
@@ -519,10 +531,10 @@ async fn raise_webhooks_analytics_event(
.and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content)
.or_else(|| get_outgoing_webhook_event_content_from_event_metadata(event.metadata));
- // Fetch updated_event from db
+ // Fetch updated_event from db (event_id is globally unique)
let updated_event = state
.store
- .find_event_by_merchant_id_event_id(&merchant_id, &event_id, merchant_key_store)
+ .find_event_by_event_id(&event_id, merchant_key_store)
.await
.attach_printable_lazy(|| format!("event not found for id: {}", &event_id))
.map_err(|error| {
@@ -548,7 +560,9 @@ async fn raise_webhooks_analytics_event(
let webhook_event = OutgoingWebhookEvent::new(
state.tenant.tenant_id.clone(),
- merchant_id,
+ provider_merchant_id,
+ Some(processor_merchant_id),
+ event.initiator_merchant_id,
event_id,
event.event_type,
outgoing_webhook_event_content,
@@ -562,24 +576,30 @@ async fn raise_webhooks_analytics_event(
pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(
db: &dyn StorageInterface,
- business_profile: &domain::Profile,
+ platform: &domain::Platform,
+ webhook_recipient: &utils::WebhookRecipientContext,
event: &domain::Event,
application_source: common_enums::ApplicationSource,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
+ let provider_merchant_id = platform.get_provider().get_account().get_id().clone();
+ let processor_merchant_id = platform.get_processor().get_account().get_id().clone();
+
let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time(
db,
- &business_profile.merchant_id,
+ &webhook_recipient.profile.merchant_id,
0,
)
.await
.ok_or(errors::StorageError::ValueNotFound(
- "Process tracker schedule time".into(), // Can raise a better error here
+ "Process tracker schedule time".into(),
))
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let tracking_data = types::OutgoingWebhookTrackingData {
- merchant_id: business_profile.merchant_id.clone(),
- business_profile_id: business_profile.get_id().to_owned(),
+ merchant_id: provider_merchant_id,
+ business_profile_id: webhook_recipient.profile.get_id().to_owned(),
+ processor_merchant_id: Some(processor_merchant_id),
+ initiator_merchant_id: Some(webhook_recipient.key_store.merchant_id.clone()),
event_type: event.event_type,
event_class: event.event_class,
primary_object_id: event.primary_object_id.clone(),
@@ -594,7 +614,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(
runner,
task,
&event.event_id,
- &business_profile.merchant_id,
+ &webhook_recipient.profile.merchant_id,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
@@ -639,7 +659,7 @@ fn get_webhook_url_from_business_profile(
}
pub(crate) fn get_outgoing_webhook_request(
- processor: &domain::Processor,
+ webhook_recipient_account: &domain::MerchantAccount,
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
@@ -695,7 +715,7 @@ pub(crate) fn get_outgoing_webhook_request(
})
}
- match processor.get_account().get_compatible_connector() {
+ match webhook_recipient_account.get_compatible_connector() {
#[cfg(feature = "stripe")]
Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::<
stripe_webhooks::StripeOutgoingWebhook,
@@ -716,7 +736,6 @@ enum ScheduleWebhookRetry {
async fn update_event_if_client_error(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
error_message: String,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
@@ -755,12 +774,7 @@ async fn update_event_if_client_error(
state
.store
- .update_event_by_merchant_id_event_id(
- merchant_id,
- event_id,
- event_update,
- &merchant_key_store,
- )
+ .update_event_by_event_id(event_id, event_update, &merchant_key_store)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
@@ -768,7 +782,7 @@ async fn update_event_if_client_error(
async fn api_client_error_handler(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
+ webhook_recipient_merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: error_stack::Report<errors::ApiClientError>,
delivery_attempt: enums::WebhookDeliveryAttempt,
@@ -779,7 +793,6 @@ async fn api_client_error_handler(
update_event_if_client_error(
state.clone(),
merchant_key_store,
- merchant_id,
event_id,
"Unable to send request to merchant server".to_string(),
)
@@ -793,10 +806,11 @@ async fn api_client_error_handler(
);
if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
- // Schedule a retry attempt for webhook delivery
+ // Schedule a retry attempt for webhook delivery using the webhook recipient's
+ // merchant_id for retry schedule lookup, consistent with initial scheduling.
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
- merchant_id,
+ webhook_recipient_merchant_id,
*process_tracker,
)
.await
@@ -809,7 +823,6 @@ async fn api_client_error_handler(
async fn update_event_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
response: reqwest::Response,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
@@ -875,12 +888,7 @@ async fn update_event_in_storage(
};
state
.store
- .update_event_by_merchant_id_event_id(
- merchant_id,
- event_id,
- event_update,
- &merchant_key_store,
- )
+ .update_event_by_event_id(event_id, event_update, &merchant_key_store)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
@@ -888,7 +896,6 @@ async fn update_event_in_storage(
async fn update_overall_delivery_status_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
updated_event: domain::Event,
) -> CustomResult<(), errors::WebhooksFlowError> {
let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate {
@@ -906,8 +913,7 @@ async fn update_overall_delivery_status_in_storage(
{
state
.store
- .update_event_by_merchant_id_event_id(
- merchant_id,
+ .update_event_by_event_id(
initial_attempt_id.as_str(),
update_overall_delivery_status,
&merchant_key_store,
@@ -950,7 +956,7 @@ async fn success_response_handler(
async fn error_response_handler(
state: SessionState,
- merchant_id: &common_utils::id_type::MerchantId,
+ webhook_recipient_merchant_id: &common_utils::id_type::MerchantId,
delivery_attempt: enums::WebhookDeliveryAttempt,
status_code: u16,
log_message: &'static str,
@@ -958,17 +964,18 @@ async fn error_response_handler(
) -> CustomResult<(), errors::WebhooksFlowError> {
metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(
1,
- router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
+ router_env::metric_attributes!((MERCHANT_ID, webhook_recipient_merchant_id.clone())),
);
let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);
logger::warn!(?error, ?delivery_attempt, status_code, %log_message);
if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
- // Schedule a retry attempt for webhook delivery
+ // Schedule a retry attempt for webhook delivery using the webhook recipient's
+ // merchant_id for retry schedule lookup, consistent with initial scheduling.
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
- merchant_id,
+ webhook_recipient_merchant_id,
*process_tracker,
)
.await
diff --git a/crates/router/src/core/webhooks/outgoing_v2.rs b/crates/router/src/core/webhooks/outgoing_v2.rs
index ad6e27caf3..74c90626d1 100644
--- a/crates/router/src/core/webhooks/outgoing_v2.rs
+++ b/crates/router/src/core/webhooks/outgoing_v2.rs
@@ -36,48 +36,52 @@ use crate::{
#[instrument(skip_all)]
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
- business_profile: domain::Profile,
- merchant_key_store: &domain::MerchantKeyStore,
+ platform: domain::Platform,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: time::PrimitiveDateTime,
+ webhook_recipient: utils::WebhookRecipientContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
- let webhook_url_result = business_profile
+ let webhook_url_result = webhook_recipient
+ .profile
.get_webhook_url_from_profile()
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured);
if utils::is_outgoing_webhook_disabled(
&state,
&webhook_url_result,
- &business_profile,
+ &webhook_recipient.profile,
&idempotent_event_id,
) {
return Ok(());
}
let event_id = utils::generate_event_id();
- let merchant_id = business_profile.merchant_id.clone();
+ let provider_merchant_id = platform.get_provider().get_account().get_id().clone();
+ let processor_merchant_id = platform.get_processor().get_account().get_id().clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
- merchant_id: merchant_id.clone(),
+ merchant_id: provider_merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
+ processor_merchant_id: Some(processor_merchant_id.clone()),
};
- let request_content = get_outgoing_webhook_request(outgoing_webhook, &business_profile)
- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
- .attach_printable("Failed to construct outgoing webhook request content")?;
+ let request_content =
+ get_outgoing_webhook_request(outgoing_webhook, &webhook_recipient.profile)
+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
@@ -89,8 +93,8 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
primary_object_id,
primary_object_type,
created_at: now,
- merchant_id: Some(business_profile.merchant_id.clone()),
- business_profile_id: Some(business_profile.get_id().to_owned()),
+ merchant_id: Some(provider_merchant_id.clone()),
+ business_profile_id: Some(webhook_recipient.profile.get_id().to_owned()),
primary_object_created_at: Some(primary_object_created_at),
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
@@ -104,8 +108,10 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
.attach_printable("Failed to encode outgoing webhook request content")
.map(hyperswitch_masking::Secret::new)?,
),
- keymanager::Identifier::Merchant(merchant_key_store.merchant_id.clone()),
- hyperswitch_masking::PeekInterface::peek(merchant_key_store.key.get_inner()),
+ keymanager::Identifier::Merchant(webhook_recipient.key_store.merchant_id.clone()),
+ hyperswitch_masking::PeekInterface::peek(
+ webhook_recipient.key_store.key.get_inner(),
+ ),
)
.await
.and_then(|val| val.try_into_operation())
@@ -116,11 +122,13 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
+ processor_merchant_id: Some(processor_merchant_id.clone()),
+ initiator_merchant_id: Some(webhook_recipient.key_store.merchant_id.clone()),
};
let event_insert_result = state
.store
- .insert_event(new_event, merchant_key_store)
+ .insert_event(new_event, &webhook_recipient.key_store)
.await;
let event = match event_insert_result {
@@ -139,15 +147,19 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
}
}?;
- let cloned_key_store = merchant_key_store.clone();
+ let cloned_key_store = webhook_recipient.key_store.clone();
+ let cloned_provider_merchant_id = provider_merchant_id.clone();
+ let cloned_processor_merchant_id = processor_merchant_id.clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
- business_profile,
+ webhook_recipient.profile,
&cloned_key_store,
+ cloned_provider_merchant_id,
+ cloned_processor_merchant_id,
event,
request_content,
delivery_attempt,
@@ -167,6 +179,8 @@ pub(crate) async fn trigger_webhook_and_raise_event(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
+ provider_merchant_id: common_utils::id_type::MerchantId,
+ processor_merchant_id: common_utils::id_type::MerchantId,
event: domain::Event,
request_content: webhook_events::OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
@@ -179,26 +193,33 @@ pub(crate) async fn trigger_webhook_and_raise_event(
"Attempting to send webhook"
);
- let merchant_id = business_profile.merchant_id.clone();
let trigger_webhook_result = trigger_webhook_to_merchant(
state.clone(),
business_profile,
merchant_key_store,
+ &provider_merchant_id,
event.clone(),
request_content,
delivery_attempt,
)
.await;
- let _ =
- raise_webhooks_analytics_event(state, trigger_webhook_result, content, merchant_id, event)
- .await;
+ let _ = raise_webhooks_analytics_event(
+ state,
+ trigger_webhook_result,
+ content,
+ provider_merchant_id,
+ processor_merchant_id,
+ event,
+ )
+ .await;
}
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
+ provider_merchant_id: &common_utils::id_type::MerchantId,
event: domain::Event,
request_content: webhook_events::OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
@@ -224,7 +245,7 @@ async fn trigger_webhook_to_merchant(
.handle_success_response(
state,
merchant_key_store.clone(),
- &business_profile.merchant_id,
+ provider_merchant_id,
&event.event_id,
None,
response,
@@ -236,7 +257,7 @@ async fn trigger_webhook_to_merchant(
.handle_error_response(
state,
merchant_key_store.clone(),
- &business_profile.merchant_id,
+ provider_merchant_id,
&event.event_id,
client_error,
)
@@ -252,7 +273,8 @@ async fn raise_webhooks_analytics_event(
errors::WebhooksFlowError,
>,
content: Option<api::OutgoingWebhookContent>,
- merchant_id: common_utils::id_type::MerchantId,
+ provider_merchant_id: common_utils::id_type::MerchantId,
+ processor_merchant_id: common_utils::id_type::MerchantId,
fallback_event: domain::Event,
) {
let (updated_event, optional_error) = match trigger_webhook_result {
@@ -300,7 +322,9 @@ async fn raise_webhooks_analytics_event(
let webhook_event = outgoing_webhook_logs::OutgoingWebhookEvent::new(
state.tenant.tenant_id.clone(),
- merchant_id,
+ provider_merchant_id,
+ Some(processor_merchant_id),
+ updated_event.initiator_merchant_id,
updated_event.event_id,
updated_event.event_type,
outgoing_webhook_event_content,
@@ -489,12 +513,7 @@ async fn update_event_in_storage(
};
state
.store
- .update_event_by_merchant_id_event_id(
- merchant_id,
- event_id,
- event_update,
- &merchant_key_store,
- )
+ .update_event_by_event_id(event_id, event_update, &merchant_key_store)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
@@ -520,8 +539,7 @@ async fn update_overall_delivery_status_in_storage(
{
state
.store
- .update_event_by_merchant_id_event_id(
- merchant_id,
+ .update_event_by_event_id(
initial_attempt_id.as_str(),
update_overall_delivery_status,
&merchant_key_store,
diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rs
index 9035de4ad1..a0e3c662df 100644
--- a/crates/router/src/core/webhooks/types.rs
+++ b/crates/router/src/core/webhooks/types.rs
@@ -67,10 +67,24 @@ impl OutgoingWebhookType for webhooks::OutgoingWebhook {
}
}
+/// Tracking data serialized into the process tracker for outgoing webhook retries.
+///
+/// This data is persisted so that the retry workflow can reconstruct the correct
+/// context (merchant account, keystore, business profile) for webhook redelivery.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct OutgoingWebhookTrackingData {
+ /// The provider (business owner) merchant id. Always populated.
pub(crate) merchant_id: common_utils::id_type::MerchantId,
+ /// The business profile of the webhook recipient (initiator's profile).
pub(crate) business_profile_id: common_utils::id_type::ProfileId,
+ /// The merchant_id of the merchant whose connector credentials were used for payment processing.
+ /// In standard setups this equals `merchant_id`.
+ pub(crate) processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+ /// The merchant_id of the webhook recipient (the merchant that initiated the
+ /// operation). Used during retries to look up the correct keystore directly.
+ /// `None` for tracking data created by older deployments (falls back to `merchant_id`).
+ #[serde(default)]
+ pub(crate) initiator_merchant_id: Option<common_utils::id_type::MerchantId>,
pub(crate) event_type: enums::EventType,
pub(crate) event_class: enums::EventClass,
pub(crate) primary_object_id: String,
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index 5571af511a..a7764f1486 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -6,6 +6,7 @@ use common_utils::{
crypto::{self, GenerateDigest},
errors::CustomResult,
ext_traits::ValueExt,
+ fp_utils,
};
use error_stack::{Report, ResultExt};
use hyperswitch_domain_models::{
@@ -285,6 +286,149 @@ pub fn is_outgoing_webhook_disabled(
false
}
+/// Context resolved for outgoing webhook delivery, containing the recipient's
+/// merchant account, keystore, and business profile.
+pub(crate) struct WebhookRecipientContext {
+ /// The webhook recipient's merchant account.
+ pub merchant_account: domain::MerchantAccount,
+ /// The webhook recipient's keystore (used for encryption/decryption).
+ pub key_store: domain::MerchantKeyStore,
+ /// The business profile from which the webhook URL and config are read.
+ pub profile: domain::Profile,
+}
+
+/// Resolves the webhook recipient from the `created_by` field on the resource.
+///
+/// Used in the incoming webhook flow where the Platform struct has no initiator populated.
+/// Falls back to processor/connected merchant when `created_by` is absent.
+///
+/// Only `CreatedBy::Api` is considered for platform initiation — `EmbeddedToken`
+/// and `Jwt` variants do not carry platform context.
+pub(crate) async fn resolve_webhook_recipient_from_created_by(
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ created_by: Option<&common_utils::types::CreatedBy>,
+) -> CustomResult<WebhookRecipientContext, errors::ApiErrorResponse> {
+ let provider_merchant_id = platform.get_provider().get_account().get_id();
+ let processor_merchant_id = platform.get_processor().get_account().get_id();
+
+ let is_platform_initiated = if provider_merchant_id == processor_merchant_id {
+ // Standard merchant setup — provider and processor are the same entity.
+ false
+ } else {
+ // Platform setup — check if the creator is the provider (platform merchant).
+ created_by
+ .map(|created_by| created_by.is_provider_initiated(provider_merchant_id))
+ .unwrap_or_default()
+ };
+
+ logger::debug!(
+ ?created_by,
+ provider_merchant_id=?provider_merchant_id,
+ processor_merchant_id=?processor_merchant_id,
+ is_platform_initiated,
+ "Resolving webhook recipient context from created_by field"
+ );
+ resolve_webhook_recipient_inner(state, platform, profile, is_platform_initiated).await
+}
+
+/// Shared resolution logic: fetch the correct account, keystore, and profile
+/// based on whether the operation was platform-initiated.
+async fn resolve_webhook_recipient_inner(
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ is_platform_initiated: bool,
+) -> CustomResult<WebhookRecipientContext, errors::ApiErrorResponse> {
+ let (merchant_account, key_store, profile) = if is_platform_initiated {
+ let provider = platform.get_provider();
+ let provider_profile = get_default_profile_for_platform_merchant(state, provider).await?;
+
+ (
+ provider.get_account().clone(),
+ provider.get_key_store().clone(),
+ provider_profile,
+ )
+ } else {
+ let processor = platform.get_processor();
+
+ (
+ processor.get_account().clone(),
+ processor.get_key_store().clone(),
+ profile.clone(),
+ )
+ };
+
+ Ok(WebhookRecipientContext {
+ merchant_account,
+ key_store,
+ profile,
+ })
+}
+
+/// Fetches the default business profile for a platform merchant.
+///
+/// Platform merchants are restricted to a single profile. This function must
+/// only be called when the provider is confirmed to be a platform merchant.
+///
+/// In V1, this uses the `default_profile` field on the merchant account.
+/// In V2, this lists all profiles and returns the single configured profile.
+#[cfg(feature = "v1")]
+async fn get_default_profile_for_platform_merchant(
+ state: &SessionState,
+ provider: &domain::Provider,
+) -> CustomResult<domain::Profile, errors::ApiErrorResponse> {
+ // Validate that merchant account type is platform
+ fp_utils::when(!provider.get_account().is_platform_account(), || {
+ Err(error_stack::report!(
+ errors::ApiErrorResponse::InternalServerError
+ ))
+ .attach_printable("Expected provider merchant to be a platform account")
+ })?;
+
+ let profile_id = provider
+ .get_account()
+ .default_profile
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Platform merchant does not have a default profile configured")?;
+
+ state
+ .store
+ .find_business_profile_by_profile_id(provider.get_key_store(), profile_id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch platform merchant's default business profile")
+}
+
+#[cfg(feature = "v2")]
+async fn get_default_profile_for_platform_merchant(
+ state: &SessionState,
+ provider: &domain::Provider,
+) -> CustomResult<domain::Profile, errors::ApiErrorResponse> {
+ // Validate that merchant account type is platform
+ fp_utils::when(!provider.get_account().is_platform_account(), || {
+ Err(error_stack::report!(
+ errors::ApiErrorResponse::InternalServerError
+ ))
+ .attach_printable("Expected provider merchant to be a platform account")
+ })?;
+
+ let profiles = state
+ .store
+ .list_profile_by_merchant_id(provider.get_key_store(), provider.get_account().get_id())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to list business profiles for platform merchant")?;
+
+ profiles
+ .into_iter()
+ .next()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Platform merchant has no business profiles configured")
+}
+
const WEBHOOK_LOCK_PREFIX: &str = "WEBHOOK_LOCK";
pub(super) async fn perform_redis_lock<A>(
diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs
index 5ebb0f93c8..a6ecb14246 100644
--- a/crates/router/src/core/webhooks/webhook_events.rs
+++ b/crates/router/src/core/webhooks/webhook_events.rs
@@ -16,12 +16,6 @@ use crate::{
const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT: i64 = 100;
const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS: i64 = 90;
-#[derive(Debug)]
-enum MerchantAccountOrProfile {
- MerchantAccount(Box<domain::MerchantAccount>),
- Profile(Box<domain::Profile>),
-}
-
#[instrument(skip(state))]
pub async fn list_initial_delivery_attempts(
state: SessionState,
@@ -34,8 +28,27 @@ pub async fn list_initial_delivery_attempts(
)?;
let store = state.store.as_ref();
- let (account, key_store) =
- get_account_and_key_store(state.clone(), merchant_id.clone(), profile_id.clone()).await?;
+ let master_key = &store.get_master_key().to_vec().into();
+
+ // The authenticated merchant is always the webhook recipient, so their
+ // keystore is the correct one for decrypting any events that were sent
+ // to them. Events are filtered by `initiator_merchant_id = merchant_id`
+ // (with a fallback on `merchant_id` column for rows created before the
+ // initiator column existed).
+ let key_store = store
+ .get_merchant_key_store_by_merchant_id(&merchant_id, master_key)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+
+ // Validate the profile_id if provided.
+ if let Some(ref profile_id) = profile_id {
+ store
+ .find_business_profile_by_merchant_id_profile_id(&key_store, &merchant_id, profile_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
+ id: profile_id.get_string_repr().to_owned(),
+ })?;
+ }
let now = common_utils::date_time::now();
let events_list_begin_time =
@@ -43,28 +56,16 @@ pub async fn list_initial_delivery_attempts(
let (events, total_count) = match constraints {
api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => {
- let events = match account {
- MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
- store
- .list_initial_events_by_merchant_id_primary_object_id(
- merchant_account.get_id(),
- object_id.as_str(),
- &key_store,
- )
- .await
- }
- MerchantAccountOrProfile::Profile(business_profile) => {
- store
- .list_initial_events_by_profile_id_primary_object_id(
- business_profile.get_id(),
- object_id.as_str(),
- &key_store,
- )
- .await
- }
- }
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to list events with specified constraints")?;
+ let events = store
+ .list_initial_events_by_initiator_merchant_id_primary_object_id(
+ &merchant_id,
+ object_id.as_str(),
+ profile_id.clone(),
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to list events with specified constraints")?;
let total_count = i64::try_from(events.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -72,28 +73,33 @@ pub async fn list_initial_delivery_attempts(
(events, total_count)
}
api_models::webhook_events::EventListConstraintsInternal::EventIdFilter { event_id } => {
- let event_opt = match account {
- MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
- store
- .find_initial_event_by_merchant_id_initial_attempt_id(
- merchant_account.get_id(),
- event_id.as_str(),
- &key_store,
- )
- .await
- }
- MerchantAccountOrProfile::Profile(business_profile) => {
- store
- .find_initial_event_by_profile_id_initial_attempt_id(
- business_profile.get_id(),
- event_id.as_str(),
- &key_store,
- )
- .await
+ let event_opt = match store
+ .find_event_by_event_id(event_id.as_str(), &key_store)
+ .await
+ {
+ Ok(event) => Some(event),
+ Err(err) if err.current_context().is_db_not_found() => None,
+ Err(err) => {
+ return Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to find event with specified event_id");
}
- }
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to find event with specified event_id")?;
+ };
+
+ // Scope the returned event to the calling merchant as the initiator and
+ // (optionally) the provided profile_id. This prevents a merchant from
+ // querying an event belonging to another merchant by guessing its event_id.
+ let event_opt = event_opt.filter(|event| {
+ let matches_initiator = event.initiator_merchant_id.as_ref() == Some(&merchant_id)
+ || (event.initiator_merchant_id.is_none()
+ && event.merchant_id.as_ref() == Some(&merchant_id));
+ let matches_profile = profile_id
+ .as_ref()
+ .is_none_or(|pid| event.business_profile_id.as_ref() == Some(pid));
+ matches_initiator
+ && matches_profile
+ && event.initial_attempt_id.as_deref() == Some(&event.event_id)
+ });
let (events, total_count) = event_opt.map_or((vec![], 0), |event| (vec![event], 1));
(events, total_count)
@@ -159,11 +165,11 @@ pub async fn list_initial_delivery_attempts(
None => Ok(now),
}?;
- let events = match account {
- MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
+ let events = match profile_id.clone() {
+ Some(profile_id) => {
store
- .list_initial_events_by_merchant_id_constraints(
- merchant_account.get_id(),
+ .list_initial_events_by_profile_id_constraints(
+ &profile_id,
created_after,
created_before,
limit,
@@ -174,10 +180,10 @@ pub async fn list_initial_delivery_attempts(
)
.await
}
- MerchantAccountOrProfile::Profile(business_profile) => {
+ None => {
store
- .list_initial_events_by_profile_id_constraints(
- business_profile.get_id(),
+ .list_initial_events_by_initiator_merchant_id_constraints(
+ &merchant_id,
created_after,
created_before,
limit,
@@ -192,18 +198,33 @@ pub async fn list_initial_delivery_attempts(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list events with specified constraints")?;
- let total_count = store
- .count_initial_events_by_constraints(
- &merchant_id,
- profile_id,
- created_after,
- created_before,
- event_types,
- is_delivered,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get total events count")?;
+ let total_count = match profile_id {
+ Some(profile_id) => {
+ store
+ .count_initial_events_by_profile_id_constraints(
+ &profile_id,
+ created_after,
+ created_before,
+ event_types,
+ is_delivered,
+ )
+ .await
+ }
+ None => {
+ store
+ .count_initial_events_by_initiator_merchant_id_constraints(
+ &merchant_id,
+ None,
+ created_after,
+ created_before,
+ event_types,
+ is_delivered,
+ )
+ .await
+ }
+ }
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get total events count")?;
(events, total_count)
}
@@ -226,19 +247,22 @@ pub async fn list_delivery_attempts(
initial_attempt_id: String,
) -> RouterResponse<Vec<api::webhook_events::EventRetrieveResponse>> {
let store = state.store.as_ref();
+ let master_key = &store.get_master_key().to_vec().into();
+ // The calling merchant is the webhook recipient, so their keystore is the
+ // one that was used to encrypt the event chain. Events in the chain are
+ // scoped by the unique `initial_attempt_id`, so no merchant filter is
+ // required in the query — but we verify ownership below to prevent a
+ // merchant from reading another merchant's event chain.
let key_store = store
- .get_merchant_key_store_by_merchant_id(
- &merchant_id,
- &store.get_master_key().to_vec().into(),
- )
+ .get_merchant_key_store_by_merchant_id(&merchant_id, master_key)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let events = store
- .list_events_by_merchant_id_initial_attempt_id(
- &merchant_id,
+ .list_events_by_initiator_merchant_id_initial_attempt_id(
&initial_attempt_id,
+ &merchant_id,
&key_store,
)
.await
@@ -268,22 +292,47 @@ pub async fn retry_delivery_attempt(
event_id: String,
) -> RouterResponse<api::webhook_events::EventRetrieveResponse> {
let store = state.store.as_ref();
+ let master_key = &store.get_master_key().to_vec().into();
+ // The calling merchant is the webhook recipient, so their keystore was used
+ // to encrypt the original event. Use it for decryption.
let key_store = store
- .get_merchant_key_store_by_merchant_id(
- &merchant_id,
- &store.get_master_key().to_vec().into(),
- )
+ .get_merchant_key_store_by_merchant_id(&merchant_id, master_key)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+ // Look up the event by its globally-unique event_id.
let event_to_retry = store
- .find_event_by_merchant_id_event_id(&key_store.merchant_id, &event_id, &key_store)
+ .find_event_by_event_id(&event_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
+ // Ensure the calling merchant is the initiator (webhook recipient) of this
+ // event. Fall back to `merchant_id` column for events created before the
+ // `initiator_merchant_id` column existed.
+ let caller_owns_event = event_to_retry.initiator_merchant_id.as_ref() == Some(&merchant_id)
+ || (event_to_retry.initiator_merchant_id.is_none()
+ && event_to_retry.merchant_id.as_ref() == Some(&merchant_id));
+ if !caller_owns_event {
+ return Err(error_stack::report!(
+ errors::ApiErrorResponse::EventNotFound
+ ));
+ }
+
+ let provider_merchant_id = event_to_retry
+ .merchant_id
+ .clone()
+ .get_required_value("merchant_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to read merchant ID from event to retry")?;
+ let processor_merchant_id = event_to_retry
+ .processor_merchant_id
+ .clone()
+ .unwrap_or_else(|| provider_merchant_id.clone());
+
let business_profile_id = event_to_retry
.business_profile_id
+ .clone()
.get_required_value("business_profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to read business profile ID from event to retry")?;
@@ -312,7 +361,7 @@ pub async fn retry_delivery_attempt(
primary_object_id: event_to_retry.primary_object_id,
primary_object_type: event_to_retry.primary_object_type,
created_at: now,
- merchant_id: Some(business_profile.merchant_id.clone()),
+ merchant_id: Some(provider_merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: event_to_retry.primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id),
@@ -322,6 +371,8 @@ pub async fn retry_delivery_attempt(
delivery_attempt: Some(delivery_attempt),
metadata: event_to_retry.metadata,
is_overall_delivery_successful: Some(false),
+ processor_merchant_id: Some(processor_merchant_id.clone()),
+ initiator_merchant_id: Some(merchant_id.clone()),
};
let event = store
@@ -345,6 +396,8 @@ pub async fn retry_delivery_attempt(
state.clone(),
business_profile,
&key_store,
+ provider_merchant_id,
+ processor_merchant_id,
event,
request_content,
delivery_attempt,
@@ -354,7 +407,7 @@ pub async fn retry_delivery_attempt(
.await;
let updated_event = store
- .find_event_by_merchant_id_event_id(&key_store.merchant_id, &new_event_id, &key_store)
+ .find_event_by_event_id(&new_event_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
@@ -363,63 +416,6 @@ pub async fn retry_delivery_attempt(
))
}
-async fn get_account_and_key_store(
- state: SessionState,
- merchant_id: common_utils::id_type::MerchantId,
- profile_id: Option<common_utils::id_type::ProfileId>,
-) -> errors::RouterResult<(MerchantAccountOrProfile, domain::MerchantKeyStore)> {
- let store = state.store.as_ref();
-
- let merchant_key_store = store
- .get_merchant_key_store_by_merchant_id(
- &merchant_id,
- &store.get_master_key().to_vec().into(),
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
-
- match profile_id {
- // If profile ID is specified, return business profile, since a business profile is more
- // specific than a merchant account.
- Some(profile_id) => {
- let business_profile = store
- .find_business_profile_by_merchant_id_profile_id(
- &merchant_key_store,
- &merchant_id,
- &profile_id,
- )
- .await
- .attach_printable_lazy(|| {
- format!(
- "Failed to find business profile by merchant_id `{merchant_id:?}` and profile_id `{profile_id:?}`. \
- The merchant_id associated with the business profile `{profile_id:?}` may be \
- different than the merchant_id specified (`{merchant_id:?}`)."
- )
- })
- .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
- id: profile_id.get_string_repr().to_owned(),
- })?;
-
- Ok((
- MerchantAccountOrProfile::Profile(Box::new(business_profile)),
- merchant_key_store,
- ))
- }
-
- None => {
- let merchant_account = store
- .find_merchant_account_by_merchant_id(&merchant_id, &merchant_key_store)
- .await
- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
-
- Ok((
- MerchantAccountOrProfile::MerchantAccount(Box::new(merchant_account)),
- merchant_key_store,
- ))
- }
- }
-}
-
async fn finalize_event_types(
event_classes: HashSet<common_enums::EventClass>,
mut event_types: HashSet<common_enums::EventType>,
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index 7d7f327297..5545044ba1 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -30,6 +30,12 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
+ async fn find_event_by_event_id(
+ &self,
+ event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError>;
+
async fn find_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -37,6 +43,13 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
+ async fn find_event_by_initiator_merchant_id_idempotent_event_id(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ idempotent_event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError>;
+
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -44,6 +57,19 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
+ #[allow(clippy::too_many_arguments)]
+ async fn list_initial_events_by_initiator_merchant_id_constraints(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
+
#[allow(clippy::too_many_arguments)]
async fn list_initial_events_by_merchant_id_constraints(
&self,
@@ -57,6 +83,13 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
+ async fn list_events_by_initiator_merchant_id_initial_attempt_id(
+ &self,
+ initial_attempt_id: &str,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
+
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -64,6 +97,14 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
+ async fn list_initial_events_by_initiator_merchant_id_primary_object_id(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ primary_object_id: &str,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
+
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -105,6 +146,13 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError>;
+ async fn update_event_by_event_id(
+ &self,
+ event_id: &str,
+ event: domain::EventUpdate,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError>;
+
async fn update_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -113,6 +161,25 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
+ async fn count_initial_events_by_initiator_merchant_id_constraints(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> CustomResult<i64, errors::StorageError>;
+
+ async fn count_initial_events_by_profile_id_constraints(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> CustomResult<i64, errors::StorageError>;
+
async fn count_initial_events_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -150,6 +217,26 @@ impl EventInterface for Store {
.change_context(errors::StorageError::DecryptionError)
}
+ #[instrument(skip_all)]
+ async fn find_event_by_event_id(
+ &self,
+ event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::find_by_event_id(&conn, event_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
#[instrument(skip_all)]
async fn find_event_by_merchant_id_event_id(
&self,
@@ -196,6 +283,72 @@ impl EventInterface for Store {
.change_context(errors::StorageError::DecryptionError)
}
+ #[instrument(skip_all)]
+ async fn find_event_by_initiator_merchant_id_idempotent_event_id(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ idempotent_event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::find_by_initiator_merchant_id_idempotent_event_id(
+ &conn,
+ initiator_merchant_id,
+ idempotent_event_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn list_initial_events_by_initiator_merchant_id_constraints(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::list_initial_attempts_by_initiator_merchant_id_constraints(
+ &conn,
+ initiator_merchant_id,
+ created_after,
+ created_before,
+ limit,
+ offset,
+ event_types,
+ is_delivered,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ .async_and_then(|events| {
+ try_join_all(events.into_iter().map(|event| async move {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }))
+ })
+ .await
+ }
+
#[instrument(skip_all)]
async fn list_initial_events_by_merchant_id_constraints(
&self,
@@ -237,6 +390,37 @@ impl EventInterface for Store {
.await
}
+ #[instrument(skip_all)]
+ async fn list_events_by_initiator_merchant_id_initial_attempt_id(
+ &self,
+ initial_attempt_id: &str,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::list_by_initiator_merchant_id_initial_attempt_id(
+ &conn,
+ initial_attempt_id,
+ initiator_merchant_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ .async_and_then(|events| {
+ try_join_all(events.into_iter().map(|event| async move {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }))
+ })
+ .await
+ }
+
#[instrument(skip_all)]
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
@@ -268,6 +452,39 @@ impl EventInterface for Store {
.await
}
+ #[instrument(skip_all)]
+ async fn list_initial_events_by_initiator_merchant_id_primary_object_id(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ primary_object_id: &str,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::list_initial_attempts_by_initiator_merchant_id_primary_object_id(
+ &conn,
+ initiator_merchant_id,
+ primary_object_id,
+ profile_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ .async_and_then(|events| {
+ try_join_all(events.into_iter().map(|event| async move {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }))
+ })
+ .await
+ }
+
#[instrument(skip_all)]
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
@@ -443,6 +660,27 @@ impl EventInterface for Store {
.await
}
+ #[instrument(skip_all)]
+ async fn update_event_by_event_id(
+ &self,
+ event_id: &str,
+ event: domain::EventUpdate,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Event::update_by_event_id(&conn, event_id, event.into())
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
#[instrument(skip_all)]
async fn update_event_by_merchant_id_event_id(
&self,
@@ -465,6 +703,50 @@ impl EventInterface for Store {
.change_context(errors::StorageError::DecryptionError)
}
+ async fn count_initial_events_by_profile_id_constraints(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::count_initial_attempts_by_profile_id_constraints(
+ &conn,
+ profile_id,
+ created_after,
+ created_before,
+ event_types,
+ is_delivered,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ async fn count_initial_events_by_initiator_merchant_id_constraints(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::count_initial_attempts_by_initiator_merchant_id_constraints(
+ &conn,
+ initiator_merchant_id,
+ profile_id,
+ created_after,
+ created_before,
+ event_types,
+ is_delivered,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
async fn count_initial_events_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -511,8 +793,39 @@ impl EventInterface for MockDb {
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
- .await
- .change_context(errors::StorageError::DecryptionError)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ async fn find_event_by_event_id(
+ &self,
+ event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+ locked_events
+ .iter()
+ .find(|event| event.event_id == event_id)
+ .cloned()
+ .async_map(|event| async {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "No event available with event_id = {event_id}"
+ ))
+ .into(),
+ )
}
async fn find_event_by_merchant_id_event_id(
@@ -579,6 +892,45 @@ impl EventInterface for MockDb {
)
}
+ async fn find_event_by_initiator_merchant_id_idempotent_event_id(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ idempotent_event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+ locked_events
+ .iter()
+ .find(|event| {
+ let matches_initiator = event.initiator_merchant_id.as_ref()
+ == Some(initiator_merchant_id)
+ || (event.initiator_merchant_id.is_none()
+ && event.merchant_id.as_ref() == Some(initiator_merchant_id));
+ matches_initiator
+ && event.idempotent_event_id == Some(idempotent_event_id.to_string())
+ })
+ .cloned()
+ .async_map(|event| async {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "No event available with initiator_merchant_id = {initiator_merchant_id:?} and idempotent_event_id = {idempotent_event_id}"
+ ))
+ .into(),
+ )
+ }
+
async fn list_initial_events_by_merchant_id_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -952,6 +1304,264 @@ impl EventInterface for MockDb {
.change_context(errors::StorageError::MockDbError)
.attach_printable("Failed to convert usize to i64")
}
+
+ async fn list_initial_events_by_initiator_merchant_id_constraints(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+ let events_iter = locked_events.iter().filter(|event| {
+ // Fallback to merchant_id for NULL initiator_merchant_id to handle
+ // events created during staggered rollout by older code.
+ let matches_initiator = event.initiator_merchant_id.as_ref()
+ == Some(initiator_merchant_id)
+ || (event.initiator_merchant_id.is_none()
+ && event.merchant_id.as_ref() == Some(initiator_merchant_id));
+ let check = matches_initiator
+ && event.initial_attempt_id.as_ref() == Some(&event.event_id)
+ && (event.created_at >= created_after)
+ && (event.created_at <= created_before)
+ && (event_types.is_empty() || event_types.contains(&event.event_type))
+ && (event.is_overall_delivery_successful == is_delivered);
+
+ check
+ });
+
+ let offset: usize = if let Some(offset) = offset {
+ if offset < 0 {
+ Err(errors::StorageError::MockDbError)?;
+ }
+ offset
+ .try_into()
+ .map_err(|_| errors::StorageError::MockDbError)?
+ } else {
+ 0
+ };
+
+ let limit: usize = if let Some(limit) = limit {
+ if limit < 0 {
+ Err(errors::StorageError::MockDbError)?;
+ }
+ limit
+ .try_into()
+ .map_err(|_| errors::StorageError::MockDbError)?
+ } else {
+ usize::MAX
+ };
+
+ let events = events_iter
+ .skip(offset)
+ .take(limit)
+ .cloned()
+ .collect::<Vec<_>>();
+ let mut domain_events = Vec::with_capacity(events.len());
+
+ for event in events {
+ let domain_event = event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ domain_events.push(domain_event);
+ }
+
+ Ok(domain_events)
+ }
+
+ async fn list_events_by_initiator_merchant_id_initial_attempt_id(
+ &self,
+ initial_attempt_id: &str,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+ let events = locked_events
+ .iter()
+ .filter(|event| {
+ let matches_initiator = event.initiator_merchant_id.as_ref()
+ == Some(initiator_merchant_id)
+ || (event.initiator_merchant_id.is_none()
+ && event.merchant_id.as_ref() == Some(initiator_merchant_id));
+ event.initial_attempt_id.as_deref() == Some(initial_attempt_id) && matches_initiator
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+ let mut domain_events = Vec::with_capacity(events.len());
+
+ for event in events {
+ let domain_event = event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ domain_events.push(domain_event);
+ }
+
+ Ok(domain_events)
+ }
+
+ async fn list_initial_events_by_initiator_merchant_id_primary_object_id(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ primary_object_id: &str,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+ let events = locked_events
+ .iter()
+ .filter(|event| {
+ // Fallback to merchant_id for NULL initiator_merchant_id.
+ let matches_initiator = event.initiator_merchant_id.as_ref()
+ == Some(initiator_merchant_id)
+ || (event.initiator_merchant_id.is_none()
+ && event.merchant_id.as_ref() == Some(initiator_merchant_id));
+ let matches_profile = profile_id
+ .as_ref()
+ .is_none_or(|pid| event.business_profile_id.as_ref() == Some(pid));
+ matches_initiator
+ && matches_profile
+ && event.initial_attempt_id.as_deref() == Some(&event.event_id)
+ && event.primary_object_id.as_str() == primary_object_id
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+
+ let mut domain_events = Vec::with_capacity(events.len());
+
+ for event in events {
+ let domain_event = event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ domain_events.push(domain_event);
+ }
+
+ Ok(domain_events)
+ }
+
+ async fn update_event_by_event_id(
+ &self,
+ event_id: &str,
+ event: domain::EventUpdate,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ let mut locked_events = self.events.lock().await;
+ let event_to_update = locked_events
+ .iter_mut()
+ .find(|event| event.event_id == event_id)
+ .ok_or(errors::StorageError::MockDbError)?;
+
+ match event {
+ domain::EventUpdate::UpdateResponse {
+ is_webhook_notified,
+ response,
+ } => {
+ event_to_update.is_webhook_notified = is_webhook_notified;
+ event_to_update.response = response.map(Into::into);
+ }
+ domain::EventUpdate::OverallDeliveryStatusUpdate {
+ is_overall_delivery_successful,
+ } => {
+ event_to_update.is_overall_delivery_successful =
+ Some(is_overall_delivery_successful)
+ }
+ }
+
+ event_to_update
+ .clone()
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ async fn count_initial_events_by_profile_id_constraints(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+
+ let iter_events = locked_events.iter().filter(|event| {
+ let check = event.initial_attempt_id.as_ref() == Some(&event.event_id)
+ && event.business_profile_id.as_ref() == Some(profile_id)
+ && (event.created_at >= created_after)
+ && (event.created_at <= created_before)
+ && (event_types.is_empty() || event_types.contains(&event.event_type))
+ && (event.is_overall_delivery_successful == is_delivered);
+
+ check
+ });
+
+ let events = iter_events.cloned().collect::<Vec<_>>();
+
+ i64::try_from(events.len())
+ .change_context(errors::StorageError::MockDbError)
+ .attach_printable("Failed to convert usize to i64")
+ }
+
+ async fn count_initial_events_by_initiator_merchant_id_constraints(
+ &self,
+ initiator_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ created_after: time::PrimitiveDateTime,
+ created_before: time::PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+
+ let iter_events = locked_events.iter().filter(|event| {
+ // Fallback to merchant_id for NULL initiator_merchant_id.
+ let matches_initiator = event.initiator_merchant_id.as_ref()
+ == Some(initiator_merchant_id)
+ || (event.initiator_merchant_id.is_none()
+ && event.merchant_id.as_ref() == Some(initiator_merchant_id));
+ let check = event.initial_attempt_id.as_ref() == Some(&event.event_id)
+ && matches_initiator
+ && (event.business_profile_id == profile_id)
+ && (event.created_at >= created_after)
+ && (event.created_at <= created_before)
+ && (event_types.is_empty() || event_types.contains(&event.event_type))
+ && (event.is_overall_delivery_successful == is_delivered);
+
+ check
+ });
+
+ let events = iter_events.cloned().collect::<Vec<_>>();
+
+ i64::try_from(events.len())
+ .change_context(errors::StorageError::MockDbError)
+ .attach_printable("Failed to convert usize to i64")
+ }
}
#[cfg(test)]
@@ -1081,6 +1691,8 @@ mod tests {
.unwrap(),
}),
is_overall_delivery_successful: Some(false),
+ processor_merchant_id: Some(merchant_id.to_owned()),
+ initiator_merchant_id: Some(merchant_id.to_owned()),
},
&merchant_key_store,
)
@@ -1195,6 +1807,8 @@ mod tests {
.unwrap(),
}),
is_overall_delivery_successful: Some(false),
+ processor_merchant_id: Some(merchant_id.to_owned()),
+ initiator_merchant_id: Some(merchant_id.to_owned()),
},
&merchant_key_store,
)
@@ -1549,22 +2163,31 @@ mod tests {
let mut handles = vec![];
for _ in 0..10 {
let state_clone = state.clone();
- let cloned_processor = platform.get_processor().clone();
+ let cloned_platform = platform.clone();
let business_profile_clone = business_profile.clone();
let content_clone = content.clone();
let primary_object_id_clone = primary_object_id.clone();
let handle = tokio::spawn(async move {
+ let webhook_recipient =
+ webhooks_core::utils::resolve_webhook_recipient_from_created_by(
+ &state_clone,
+ &cloned_platform,
+ &business_profile_clone,
+ None,
+ )
+ .await
+ .map_err(|e| format!("resolve_webhook_recipient failed: {e}"))?;
webhooks_core::create_event_and_trigger_outgoing_webhook(
state_clone,
- cloned_processor,
- business_profile_clone,
+ cloned_platform,
event_type,
event_class,
(*primary_object_id_clone).to_string(),
primary_object_type,
content_clone,
primary_object_created_at,
+ webhook_recipient,
)
.await
.map_err(|e| format!("create_event_and_trigger_outgoing_webhook failed: {e}"))
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 89ecbbf97a..9dc2e4d892 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -723,6 +723,16 @@ impl EventInterface for KafkaStore {
.await
}
+ async fn find_event_by_event_id(
+ &self,
+ event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ self.diesel_store
+ .find_event_by_event_id(event_id, merchant_key_store)
+ .await
+ }
+
async fn find_event_by_merchant_id_event_id(
&self,
merchant_id: &id_type::MerchantId,
@@ -749,6 +759,46 @@ impl EventInterface for KafkaStore {
.await
}
+ async fn find_event_by_initiator_merchant_id_idempotent_event_id(
+ &self,
+ initiator_merchant_id: &id_type::MerchantId,
+ idempotent_event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ self.diesel_store
+ .find_event_by_initiator_merchant_id_idempotent_event_id(
+ initiator_merchant_id,
+ idempotent_event_id,
+ merchant_key_store,
+ )
+ .await
+ }
+
+ async fn list_initial_events_by_initiator_merchant_id_constraints(
+ &self,
+ initiator_merchant_id: &id_type::MerchantId,
+ created_after: PrimitiveDateTime,
+ created_before: PrimitiveDateTime,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ self.diesel_store
+ .list_initial_events_by_initiator_merchant_id_constraints(
+ initiator_merchant_id,
+ created_after,
+ created_before,
+ limit,
+ offset,
+ event_types,
+ is_delivered,
+ merchant_key_store,
+ )
+ .await
+ }
+
async fn list_initial_events_by_merchant_id_constraints(
&self,
merchant_id: &id_type::MerchantId,
@@ -774,6 +824,21 @@ impl EventInterface for KafkaStore {
.await
}
+ async fn list_events_by_initiator_merchant_id_initial_attempt_id(
+ &self,
+ initial_attempt_id: &str,
+ initiator_merchant_id: &id_type::MerchantId,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ self.diesel_store
+ .list_events_by_initiator_merchant_id_initial_attempt_id(
+ initial_attempt_id,
+ initiator_merchant_id,
+ merchant_key_store,
+ )
+ .await
+ }
+
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &id_type::MerchantId,
@@ -789,6 +854,23 @@ impl EventInterface for KafkaStore {
.await
}
+ async fn list_initial_events_by_initiator_merchant_id_primary_object_id(
+ &self,
+ initiator_merchant_id: &id_type::MerchantId,
+ primary_object_id: &str,
+ profile_id: Option<id_type::ProfileId>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ self.diesel_store
+ .list_initial_events_by_initiator_merchant_id_primary_object_id(
+ initiator_merchant_id,
+ primary_object_id,
+ profile_id,
+ merchant_key_store,
+ )
+ .await
+ }
+
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
merchant_id: &id_type::MerchantId,
@@ -874,6 +956,17 @@ impl EventInterface for KafkaStore {
.await
}
+ async fn update_event_by_event_id(
+ &self,
+ event_id: &str,
+ event: domain::EventUpdate,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ self.diesel_store
+ .update_event_by_event_id(event_id, event, merchant_key_store)
+ .await
+ }
+
async fn update_event_by_merchant_id_event_id(
&self,
merchant_id: &id_type::MerchantId,
@@ -886,6 +979,46 @@ impl EventInterface for KafkaStore {
.await
}
+ async fn count_initial_events_by_profile_id_constraints(
+ &self,
+ profile_id: &id_type::ProfileId,
+ created_after: PrimitiveDateTime,
+ created_before: PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> CustomResult<i64, errors::StorageError> {
+ self.diesel_store
+ .count_initial_events_by_profile_id_constraints(
+ profile_id,
+ created_after,
+ created_before,
+ event_types,
+ is_delivered,
+ )
+ .await
+ }
+
+ async fn count_initial_events_by_initiator_merchant_id_constraints(
+ &self,
+ initiator_merchant_id: &id_type::MerchantId,
+ profile_id: Option<id_type::ProfileId>,
+ created_after: PrimitiveDateTime,
+ created_before: PrimitiveDateTime,
+ event_types: HashSet<common_enums::EventType>,
+ is_delivered: Option<bool>,
+ ) -> CustomResult<i64, errors::StorageError> {
+ self.diesel_store
+ .count_initial_events_by_initiator_merchant_id_constraints(
+ initiator_merchant_id,
+ profile_id,
+ created_after,
+ created_before,
+ event_types,
+ is_delivered,
+ )
+ .await
+ }
+
async fn count_initial_events_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs
index c08cb654b4..3e62ff4787 100644
--- a/crates/router/src/events/outgoing_webhook_logs.rs
+++ b/crates/router/src/events/outgoing_webhook_logs.rs
@@ -22,6 +22,8 @@ pub struct OutgoingWebhookEvent {
initial_attempt_id: Option<String>,
status_code: Option<u16>,
delivery_attempt: Option<WebhookDeliveryAttempt>,
+ processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+ initiator_merchant_id: Option<common_utils::id_type::MerchantId>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
@@ -170,6 +172,8 @@ impl OutgoingWebhookEvent {
pub fn new(
tenant_id: common_utils::id_type::TenantId,
merchant_id: common_utils::id_type::MerchantId,
+ processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+ initiator_merchant_id: Option<common_utils::id_type::MerchantId>,
event_id: String,
event_type: OutgoingWebhookEventType,
content: Option<OutgoingWebhookEventContent>,
@@ -181,6 +185,8 @@ impl OutgoingWebhookEvent {
Self {
tenant_id,
merchant_id,
+ processor_merchant_id,
+ initiator_merchant_id,
event_id,
event_type,
content,
diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rs
index 104a9c8dd9..5bed12a279 100644
--- a/crates/router/src/routes/webhook_events.rs
+++ b/crates/router/src/routes/webhook_events.rs
@@ -51,7 +51,7 @@ pub async fn list_initial_webhook_delivery_attempts(
merchant_id,
required_permission: Permission::MerchantWebhookEventRead,
allow_connected: true,
- allow_platform: false,
+ allow_platform: true,
},
req.headers(),
),
@@ -111,7 +111,7 @@ pub async fn list_initial_webhook_delivery_attempts_with_jwtauth(
&auth::JWTAuth {
permission: Permission::ProfileWebhookEventRead,
allow_connected: true,
- allow_platform: false,
+ allow_platform: true,
},
api_locking::LockAction::NotApplicable,
))
@@ -150,7 +150,7 @@ pub async fn list_webhook_delivery_attempts(
merchant_id,
required_permission: Permission::MerchantWebhookEventRead,
allow_connected: true,
- allow_platform: false,
+ allow_platform: true,
},
req.headers(),
),
@@ -192,7 +192,7 @@ pub async fn retry_webhook_delivery_attempt(
merchant_id,
required_permission: Permission::MerchantWebhookEventWrite,
allow_connected: true,
- allow_platform: false,
+ allow_platform: true,
},
req.headers(),
),
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 606b18a39f..62bb8390cc 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -6429,7 +6429,7 @@ where
}
/// Fetches the platform merchant account and key store
-async fn get_platform_account_and_key_store<A>(
+pub(crate) async fn get_platform_account_and_key_store<A>(
state: &A,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<(domain::MerchantAccount, domain::MerchantKeyStore)>
diff --git a/crates/router/src/types/domain/event.rs b/crates/router/src/types/domain/event.rs
index bb0657f27c..3141758451 100644
--- a/crates/router/src/types/domain/event.rs
+++ b/crates/router/src/types/domain/event.rs
@@ -71,6 +71,13 @@ pub struct Event {
/// Indicates whether the event was ultimately delivered.
pub is_overall_delivery_successful: Option<bool>,
+
+ /// The merchant_id of the merchant whose connector credentials are used for payment processing.
+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+
+ /// The merchant_id of the merchant that initiated the operation for which this event was
+ /// generated. This is also the webhook recipient.
+ pub initiator_merchant_id: Option<common_utils::id_type::MerchantId>,
}
#[derive(Debug)]
@@ -130,6 +137,8 @@ impl super::behaviour::Conversion for Event {
delivery_attempt: self.delivery_attempt,
metadata: self.metadata,
is_overall_delivery_successful: self.is_overall_delivery_successful,
+ processor_merchant_id: self.processor_merchant_id,
+ initiator_merchant_id: self.initiator_merchant_id,
})
}
@@ -180,6 +189,8 @@ impl super::behaviour::Conversion for Event {
delivery_attempt: item.delivery_attempt,
metadata: item.metadata,
is_overall_delivery_successful: item.is_overall_delivery_successful,
+ processor_merchant_id: item.processor_merchant_id,
+ initiator_merchant_id: item.initiator_merchant_id,
})
}
@@ -202,6 +213,8 @@ impl super::behaviour::Conversion for Event {
delivery_attempt: self.delivery_attempt,
metadata: self.metadata,
is_overall_delivery_successful: self.is_overall_delivery_successful,
+ processor_merchant_id: self.processor_merchant_id,
+ initiator_merchant_id: self.initiator_merchant_id,
})
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 381f460d65..ddd7616fee 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -2082,6 +2082,7 @@ impl TryFrom<domain::Event> for api_models::webhook_events::EventListItemRespons
event_class: item.event_class,
is_delivery_successful: item.is_overall_delivery_successful,
initial_attempt_id,
+ processor_merchant_id: item.processor_merchant_id,
created: item.created_at,
})
}
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 5969dffe34..d32288fd04 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -1148,8 +1148,7 @@ pub fn check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn trigger_payments_webhook<F, Op, D>(
- processor: &domain::Processor,
- initiator: Option<&domain::Initiator>,
+ platform: &domain::Platform,
business_profile: domain::Profile,
payment_data: D,
customer: Option<domain::Customer>,
@@ -1167,8 +1166,7 @@ where
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn trigger_payments_webhook<F, Op, D>(
- processor: &domain::Processor,
- initiator: Option<&domain::Initiator>,
+ platform: &domain::Platform,
business_profile: domain::Profile,
payment_data: D,
state: &SessionState,
@@ -1198,6 +1196,7 @@ where
.collect()
});
let payment_id = payment_data.get_payment_intent().get_id().to_owned();
+ let created_by = payment_data.get_payment_attempt().created_by.clone();
let payments_response = crate::core::payments::transformers::payments_to_payments_response(
payment_data,
captures,
@@ -1208,8 +1207,8 @@ where
None,
None,
None,
- processor,
- initiator,
+ platform.get_processor(),
+ platform.get_initiator(),
)?;
let event_type = status.into();
@@ -1223,14 +1222,21 @@ where
// So when server shutdown won't wait for this thread's completion.
if let Some(event_type) = event_type {
- let cloned_processor = processor.clone();
+ let webhook_recipient =
+ webhooks_core::utils::resolve_webhook_recipient_from_created_by(
+ state,
+ platform,
+ &business_profile,
+ created_by.as_ref(),
+ )
+ .await?;
+ let cloned_platform = platform.clone();
tokio::spawn(
async move {
let primary_object_created_at = payments_response_json.created;
Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(
cloned_state,
- cloned_processor,
- business_profile,
+ cloned_platform,
event_type,
diesel_models::enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
@@ -1239,6 +1245,7 @@ where
payments_response_json,
)),
primary_object_created_at,
+ webhook_recipient,
))
.await
}
@@ -1297,19 +1304,31 @@ pub async fn trigger_refund_outgoing_webhook(
let cloned_state = state.clone();
let primary_object_created_at = refund_response.created_at;
if let Some(outgoing_event_type) = event_type {
- let processor = platform.get_processor().clone();
+ let created_by = refund
+ .created_by
+ .as_deref()
+ .and_then(|s| s.parse::<common_utils::types::CreatedBy>().ok());
+ let webhook_recipient =
+ webhooks_core::utils::resolve_webhook_recipient_from_created_by(
+ state,
+ platform,
+ &business_profile,
+ created_by.as_ref(),
+ )
+ .await?;
+ let cloned_platform = platform.clone();
tokio::spawn(
async move {
Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(
cloned_state,
- processor,
- business_profile,
+ cloned_platform,
outgoing_event_type,
diesel_models::enums::EventClass::Refunds,
refund_id.to_string(),
common_enums::EventObjectType::RefundDetails,
webhooks::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
primary_object_created_at,
+ webhook_recipient,
))
.await
}
@@ -1325,10 +1344,9 @@ pub async fn trigger_refund_outgoing_webhook(
#[cfg(feature = "v2")]
pub async fn trigger_refund_outgoing_webhook(
state: &SessionState,
- merchant_account: &domain::MerchantAccount,
+ platform: &domain::Platform,
refund: &diesel_models::Refund,
profile_id: id_type::ProfileId,
- key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
todo!()
}
@@ -1346,6 +1364,7 @@ pub async fn trigger_payouts_webhook(
state: &SessionState,
platform: &domain::Platform,
payout_response: &api_models::payouts::PayoutCreateResponse,
+ created_by: Option<&common_utils::types::CreatedBy>,
) -> RouterResult<()> {
let profile_id = &payout_response.profile_id;
let business_profile = state
@@ -1369,7 +1388,16 @@ pub async fn trigger_payouts_webhook(
if let Some(event_type) = event_type {
let cloned_state = state.clone();
let cloned_response = payout_response.clone();
- let processor = platform.get_processor().clone();
+
+ let webhook_recipient =
+ webhooks_core::utils::resolve_webhook_recipient_from_created_by(
+ state,
+ platform,
+ &business_profile,
+ created_by,
+ )
+ .await?;
+ let cloned_platform = platform.clone();
// This spawns this futures in a background thread, the exception inside this future won't affect
// the current thread and the lifecycle of spawn thread is not handled by runtime.
@@ -1379,14 +1407,14 @@ pub async fn trigger_payouts_webhook(
let primary_object_created_at = cloned_response.created;
Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(
cloned_state,
- processor,
- business_profile,
+ cloned_platform,
event_type,
diesel_models::enums::EventClass::Payouts,
cloned_response.payout_id.get_string_repr().to_owned(),
common_enums::EventObjectType::PayoutDetails,
webhooks::OutgoingWebhookContent::PayoutDetails(Box::new(cloned_response)),
primary_object_created_at,
+ webhook_recipient,
))
.await
}
@@ -1404,6 +1432,7 @@ pub async fn trigger_payouts_webhook(
state: &SessionState,
platform: &domain::Platform,
payout_response: &api_models::payouts::PayoutCreateResponse,
+ created_by: Option<&common_utils::types::CreatedBy>,
) -> RouterResult<()> {
todo!()
}
@@ -1433,23 +1462,26 @@ pub async fn trigger_subscriptions_outgoing_webhook(
None,
);
+ let webhook_recipient = webhooks_core::utils::resolve_webhook_recipient_from_created_by(
+ state, &platform, profile, None,
+ )
+ .await?;
+
let cloned_state = state.clone();
- let cloned_profile = profile.clone();
let invoice_id = invoice.id.get_string_repr().to_owned();
let created_at = subscription.created_at;
- let processor = platform.get_processor().clone();
tokio::spawn(async move {
Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(
cloned_state,
- processor,
- cloned_profile,
+ platform,
common_enums::enums::EventType::InvoicePaid,
common_enums::enums::EventClass::Subscriptions,
invoice_id,
common_enums::EventObjectType::SubscriptionDetails,
webhooks::OutgoingWebhookContent::SubscriptionDetails(Box::new(response)),
Some(created_at),
+ webhook_recipient,
))
.await
});
diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs
index 14b601b465..d020c33b7a 100644
--- a/crates/router/src/workflows/outgoing_webhook_retry.rs
+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs
@@ -53,14 +53,29 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
.parse_value("OutgoingWebhookTrackingData")?;
let db = &*state.store;
- let key_store = db
- .get_merchant_key_store_by_merchant_id(
- &tracking_data.merchant_id,
- &db.get_master_key().to_vec().into(),
- )
+ let master_key = &db.get_master_key().to_vec().into();
+ let provider_merchant_id = tracking_data.merchant_id.clone();
+
+ // Resolve the webhook recipient's merchant_id for keystore lookup.
+ // `initiator_merchant_id` is populated by new deployments; fall back to
+ // `merchant_id` for tracking data written by older deployments.
+ let webhook_recipient_merchant_id = tracking_data
+ .initiator_merchant_id
+ .clone()
+ .unwrap_or_else(|| tracking_data.merchant_id.clone());
+ let processor_merchant_id = tracking_data
+ .processor_merchant_id
+ .clone()
+ .unwrap_or_else(|| tracking_data.merchant_id.clone());
+
+ let webhook_key_store = db
+ .get_merchant_key_store_by_merchant_id(&webhook_recipient_merchant_id, master_key)
.await?;
let business_profile = db
- .find_business_profile_by_profile_id(&key_store, &tracking_data.business_profile_id)
+ .find_business_profile_by_profile_id(
+ &webhook_key_store,
+ &tracking_data.business_profile_id,
+ )
.await?;
let event_id = webhooks_core::utils::generate_event_id();
@@ -72,30 +87,18 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
- let initial_event = match &tracking_data.initial_attempt_id {
- Some(initial_attempt_id) => {
- db.find_event_by_merchant_id_event_id(
- &business_profile.merchant_id,
- initial_attempt_id,
- &key_store,
- )
- .await?
- }
- // Tracking data inserted by old version of application, fetch event using old event ID
- // format
- None => {
- let old_event_id = format!(
- "{}_{}",
- tracking_data.primary_object_id, tracking_data.event_type
- );
- db.find_event_by_merchant_id_event_id(
- &business_profile.merchant_id,
- &old_event_id,
- &key_store,
- )
- .await?
- }
- };
+ // Look up the initial event by event_id alone (event_id is globally unique).
+ // This works regardless of which merchant owns the event and also handles
+ // old tracking data created before `initial_attempt_id` was tracked.
+ let initial_attempt_id = tracking_data.initial_attempt_id.clone().unwrap_or_else(|| {
+ format!(
+ "{}_{}",
+ tracking_data.primary_object_id, tracking_data.event_type
+ )
+ });
+ let initial_event = db
+ .find_event_by_event_id(&initial_attempt_id, &webhook_key_store)
+ .await?;
let now = common_utils::date_time::now();
let new_event = domain::Event {
@@ -106,7 +109,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
primary_object_id: initial_event.primary_object_id,
primary_object_type: initial_event.primary_object_type,
created_at: now,
- merchant_id: Some(business_profile.merchant_id.clone()),
+ merchant_id: Some(provider_merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: initial_event.primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id),
@@ -116,10 +119,16 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
delivery_attempt: Some(delivery_attempt),
metadata: initial_event.metadata,
is_overall_delivery_successful: Some(false),
+ processor_merchant_id: initial_event
+ .processor_merchant_id
+ .or(Some(processor_merchant_id.clone())),
+ initiator_merchant_id: initial_event
+ .initiator_merchant_id
+ .or(Some(webhook_key_store.merchant_id.clone())),
};
let event = db
- .insert_event(new_event, &key_store)
+ .insert_event(new_event, &webhook_key_store)
.await
.inspect_err(|error| {
logger::error!(?error, "Failed to insert event in events table");
@@ -135,7 +144,9 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
Box::pin(webhooks_core::trigger_webhook_and_raise_event(
state.clone(),
business_profile,
- &key_store,
+ &webhook_key_store,
+ provider_merchant_id,
+ processor_merchant_id,
event,
request_content,
delivery_attempt,
@@ -148,23 +159,48 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
// Event inserted by old version of application, fetch current information about
// resource
None => {
- let merchant_account = db
- .find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store)
+ // Fetch provider merchant account and keystore
+ let provider_key_store = db
+ .get_merchant_key_store_by_merchant_id(&provider_merchant_id, master_key)
.await?;
+ let provider_account = db
+ .find_merchant_account_by_merchant_id(
+ &provider_merchant_id,
+ &provider_key_store,
+ )
+ .await?;
+
+ // Fetch processor merchant account and keystore (may be same as provider)
+ let (processor_account, processor_key_store) = if provider_merchant_id
+ == processor_merchant_id
+ {
+ (provider_account.clone(), provider_key_store.clone())
+ } else {
+ let processor_key_store = db
+ .get_merchant_key_store_by_merchant_id(&processor_merchant_id, master_key)
+ .await?;
+ let processor_account = db
+ .find_merchant_account_by_merchant_id(
+ &processor_merchant_id,
+ &processor_key_store,
+ )
+ .await?;
+ (processor_account, processor_key_store)
+ };
let platform = domain::Platform::new(
- merchant_account.clone(),
- key_store.clone(),
- merchant_account.clone(),
- key_store.clone(),
+ provider_account,
+ provider_key_store,
+ processor_account,
+ processor_key_store,
None,
);
+
// TODO: Add request state for the PT flows as well
let (content, event_type) = Box::pin(get_outgoing_webhook_content_and_event_type(
state.clone(),
state.get_req_state(),
- merchant_account.clone(),
- key_store.clone(),
+ &platform,
&tracking_data,
))
.await?;
@@ -173,15 +209,26 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
// Resource status is same as the event type of the current event
Some(event_type) if event_type == tracking_data.event_type => {
let outgoing_webhook = OutgoingWebhook {
- merchant_id: tracking_data.merchant_id.clone(),
+ merchant_id: provider_merchant_id.clone(),
event_id: event.event_id.clone(),
event_type,
content: content.clone(),
timestamp: event.created_at,
+ processor_merchant_id: Some(processor_merchant_id.clone()),
};
+ // Use the webhook recipient's merchant account for request construction.
+ // If the recipient is the provider, use the provider account (platform-initiated);
+ // otherwise use the processor account (connected-merchant-initiated).
+ let webhook_recipient_account =
+ if webhook_recipient_merchant_id == provider_merchant_id {
+ platform.get_provider().get_account()
+ } else {
+ platform.get_processor().get_account()
+ };
+
let request_content = webhooks_core::get_outgoing_webhook_request(
- platform.get_processor(),
+ webhook_recipient_account,
outgoing_webhook,
&business_profile,
)
@@ -196,7 +243,9 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
Box::pin(webhooks_core::trigger_webhook_and_raise_event(
state.clone(),
business_profile,
- &key_store,
+ &webhook_key_store,
+ provider_merchant_id,
+ processor_merchant_id,
event,
request_content,
delivery_attempt,
@@ -351,8 +400,7 @@ pub(crate) async fn retry_webhook_delivery_task(
async fn get_outgoing_webhook_content_and_event_type(
state: SessionState,
req_state: ReqState,
- merchant_account: domain::MerchantAccount,
- key_store: domain::MerchantKeyStore,
+ platform: &domain::Platform,
tracking_data: &OutgoingWebhookTrackingData,
) -> Result<(OutgoingWebhookContent, Option<EventType>), errors::ProcessTrackerError> {
use api_models::{
@@ -373,14 +421,6 @@ async fn get_outgoing_webhook_content_and_event_type(
types::{api::PSync, transformers::ForeignFrom},
};
- let platform = domain::Platform::new(
- merchant_account.clone(),
- key_store.clone(),
- merchant_account.clone(),
- key_store.clone(),
- None,
- );
-
match tracking_data.event_class {
diesel_models::enums::EventClass::Payments => {
let payment_id = tracking_data.primary_object_id.clone();
@@ -548,7 +588,7 @@ async fn get_outgoing_webhook_content_and_event_type(
let payout_data = Box::pin(payouts::make_payout_data(
&state,
- &platform,
+ platform,
None,
&request,
DEFAULT_LOCALE,
@@ -556,7 +596,7 @@ async fn get_outgoing_webhook_content_and_event_type(
.await?;
let payout_create_response =
- payouts::response_handler(&state, &platform, &payout_data).await?;
+ payouts::response_handler(&state, platform, &payout_data).await?;
let event_type: Option<EventType> = payout_data.payout_attempt.status.into();
logger::debug!(current_resource_status=%payout_data.payout_attempt.status);
@@ -573,10 +613,10 @@ async fn get_outgoing_webhook_content_and_event_type(
let response = Box::pin(
invoice_sync::InvoiceSyncHandler::form_response_for_retry_outgoing_webhook_task(
state.clone().into(),
- &key_store,
+ platform.get_processor().get_key_store(),
invoice_id,
profile_id,
- &merchant_account,
+ platform.get_processor().get_account(),
),
)
.await
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index 0d9c8adc24..fb7986cf63 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -217,8 +217,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
// Trigger the outgoing webhook to notify the merchant about failed payment
let operation = operations::PaymentStatus;
Box::pin(utils::trigger_payments_webhook(
- platform.get_processor(),
- platform.get_initiator(),
+ &platform,
business_profile,
payment_data,
state,
diff --git a/crates/router/src/workflows/payout_sync.rs b/crates/router/src/workflows/payout_sync.rs
index 1aa7b4ed55..76e3669e3f 100644
--- a/crates/router/src/workflows/payout_sync.rs
+++ b/crates/router/src/workflows/payout_sync.rs
@@ -272,16 +272,24 @@ impl PayoutSyncWorkFlow {
if let Some(outgoing_event_type) = event_type {
let payout_response = payouts::response_handler(state, platform, payout_data).await?;
+ let webhook_recipient = webhooks::utils::resolve_webhook_recipient_from_created_by(
+ state,
+ platform,
+ &business_profile,
+ payout_data.payouts.created_by.as_ref(),
+ )
+ .await?;
+
Box::pin(webhooks::create_event_and_trigger_outgoing_webhook(
state.clone(),
- platform.get_processor().clone(),
- business_profile,
+ platform.clone(),
outgoing_event_type,
enums::EventClass::Payouts,
payout_data.payouts.payout_id.get_string_repr().to_string(),
enums::EventObjectType::PayoutDetails,
api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_response)),
Some(payout_data.payout_attempt.created_at),
+ webhook_recipient,
))
.await?;
}
diff --git a/crates/router/src/workflows/process_dispute.rs b/crates/router/src/workflows/process_dispute.rs
index 9a6136400e..11e4d8ca21 100644
--- a/crates/router/src/workflows/process_dispute.rs
+++ b/crates/router/src/workflows/process_dispute.rs
@@ -111,7 +111,7 @@ impl ProcessTrackerWorkflow<SessionState> for ProcessDisputeWorkflow {
.await?;
} else {
// Update dispute data
- let response = disputes::update_dispute_data(
+ let response = Box::pin(disputes::update_dispute_data(
state,
platform,
business_profile,
@@ -119,7 +119,7 @@ impl ProcessTrackerWorkflow<SessionState> for ProcessDisputeWorkflow {
tracking_data.dispute_payload,
payment_attempt,
tracking_data.connector_name.as_str(),
- )
+ ))
.await
.map_err(|error| logger::error!("Dispute update failed: {error}"));
diff --git a/migrations/2026-03-28-142607_add_processor_merchant_id_to_events/down.sql b/migrations/2026-03-28-142607_add_processor_merchant_id_to_events/down.sql
new file mode 100644
index 0000000000..13477930ce
--- /dev/null
+++ b/migrations/2026-03-28-142607_add_processor_merchant_id_to_events/down.sql
@@ -0,0 +1 @@
+ALTER TABLE events DROP COLUMN IF EXISTS processor_merchant_id;
diff --git a/migrations/2026-03-28-142607_add_processor_merchant_id_to_events/up.sql b/migrations/2026-03-28-142607_add_processor_merchant_id_to_events/up.sql
new file mode 100644
index 0000000000..b3f6ee0990
--- /dev/null
+++ b/migrations/2026-03-28-142607_add_processor_merchant_id_to_events/up.sql
@@ -0,0 +1,4 @@
+ALTER TABLE events ADD COLUMN IF NOT EXISTS processor_merchant_id VARCHAR(64);
+
+-- This backfill should be executed after deployment is complete.
+UPDATE events SET processor_merchant_id = merchant_id WHERE processor_merchant_id IS NULL;
\ No newline at end of file
diff --git a/migrations/2026-04-09-103802_add_initiator_merchant_id_to_events/down.sql b/migrations/2026-04-09-103802_add_initiator_merchant_id_to_events/down.sql
new file mode 100644
index 0000000000..fb76f2e8f7
--- /dev/null
+++ b/migrations/2026-04-09-103802_add_initiator_merchant_id_to_events/down.sql
@@ -0,0 +1,5 @@
+DROP INDEX IF EXISTS events_initiator_merchant_id_initial_attempt_id_index;
+DROP INDEX IF EXISTS events_initiator_merchant_id_event_id_index;
+
+ALTER TABLE events
+DROP COLUMN IF EXISTS initiator_merchant_id;
diff --git a/migrations/2026-04-09-103802_add_initiator_merchant_id_to_events/up.sql b/migrations/2026-04-09-103802_add_initiator_merchant_id_to_events/up.sql
new file mode 100644
index 0000000000..33dbe7e2a4
--- /dev/null
+++ b/migrations/2026-04-09-103802_add_initiator_merchant_id_to_events/up.sql
@@ -0,0 +1,16 @@
+-- Add initiator_merchant_id column to events table: the merchant that
+-- initiated the operation for which the webhook event was generated.
+ALTER TABLE events
+ADD COLUMN IF NOT EXISTS initiator_merchant_id VARCHAR(64);
+
+-- Backfill existing rows by defaulting initiator_merchant_id to merchant_id.
+-- This backfill should be executed again after deployment is complete.
+UPDATE events
+SET initiator_merchant_id = merchant_id
+WHERE initiator_merchant_id IS NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS events_initiator_merchant_id_event_id_index
+ ON events (initiator_merchant_id, event_id);
+
+CREATE INDEX IF NOT EXISTS events_initiator_merchant_id_initial_attempt_id_index
+ ON events (initiator_merchant_id, initial_attempt_id);