Skip to content

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

feat(router): add payment incoming webhooks support for v2 (#6551)

Sai Harsha Vardhan8e9c3ec89318
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 37389308aa..2f7f796aef 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3691,6 +3691,7 @@ pub struct PaymentMethodDataResponseWithBilling {
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)]
+#[cfg(feature = "v1")]
pub enum PaymentIdType {
/// The identifier for payment intent
PaymentIntentId(id_type::PaymentId),
@@ -3702,6 +3703,20 @@ pub enum PaymentIdType {
PreprocessingId(String),
}
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)]
+#[cfg(feature = "v2")]
+pub enum PaymentIdType {
+ /// The identifier for payment intent
+ PaymentIntentId(id_type::GlobalPaymentId),
+ /// The identifier for connector transaction
+ ConnectorTransactionId(String),
+ /// The identifier for payment attempt
+ PaymentAttemptId(String),
+ /// The identifier for preprocessing step
+ PreprocessingId(String),
+}
+
+#[cfg(feature = "v1")]
impl fmt::Display for PaymentIdType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -3726,6 +3741,7 @@ impl fmt::Display for PaymentIdType {
}
}
+#[cfg(feature = "v1")]
impl Default for PaymentIdType {
fn default() -> Self {
Self::PaymentIntentId(Default::default())
@@ -4566,7 +4582,7 @@ pub struct PaymentsRetrieveRequest {
/// Error details for the payment
#[cfg(feature = "v2")]
-#[derive(Debug, serde::Serialize, ToSchema)]
+#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct ErrorDetails {
/// The error code
pub code: String,
@@ -4651,7 +4667,7 @@ pub struct PaymentsConfirmIntentResponse {
// TODO: have a separate response for detailed, summarized
/// Response for Payment Intent Confirm
#[cfg(feature = "v2")]
-#[derive(Debug, serde::Serialize, ToSchema)]
+#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsRetrieveResponse {
/// Unique identifier for the payment. This ensures idempotency for multiple payments
/// that have been done by a single merchant.
@@ -6307,6 +6323,85 @@ pub struct FrmMessage {
pub frm_error: Option<String>,
}
+#[cfg(feature = "v2")]
+mod payment_id_type {
+ use std::{borrow::Cow, fmt};
+
+ use serde::{
+ de::{self, Visitor},
+ Deserializer,
+ };
+
+ use super::PaymentIdType;
+
+ struct PaymentIdVisitor;
+ struct OptionalPaymentIdVisitor;
+
+ impl<'de> Visitor<'de> for PaymentIdVisitor {
+ type Value = PaymentIdType;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("payment id")
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string()))
+ .map_err(de::Error::custom)
+ .map(PaymentIdType::PaymentIntentId)
+ }
+ }
+
+ impl<'de> Visitor<'de> for OptionalPaymentIdVisitor {
+ type Value = Option<PaymentIdType>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("payment id")
+ }
+
+ fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ deserializer.deserialize_any(PaymentIdVisitor).map(Some)
+ }
+
+ fn visit_none<E>(self) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(None)
+ }
+
+ fn visit_unit<E>(self) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(None)
+ }
+ }
+
+ #[allow(dead_code)]
+ pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error>
+ where
+ D: Deserializer<'a>,
+ {
+ deserializer.deserialize_any(PaymentIdVisitor)
+ }
+
+ pub(crate) fn deserialize_option<'a, D>(
+ deserializer: D,
+ ) -> Result<Option<PaymentIdType>, D::Error>
+ where
+ D: Deserializer<'a>,
+ {
+ deserializer.deserialize_option(OptionalPaymentIdVisitor)
+ }
+}
+
+#[cfg(feature = "v1")]
mod payment_id_type {
use std::{borrow::Cow, fmt};
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index 56a566d170..e6f4065eb7 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -76,25 +76,45 @@ pub enum WebhookFlow {
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// This enum tells about the affect a webhook had on an object
pub enum WebhookResponseTracker {
+ #[cfg(feature = "v1")]
Payment {
payment_id: common_utils::id_type::PaymentId,
status: common_enums::IntentStatus,
},
+ #[cfg(feature = "v2")]
+ Payment {
+ payment_id: common_utils::id_type::GlobalPaymentId,
+ status: common_enums::IntentStatus,
+ },
#[cfg(feature = "payouts")]
Payout {
payout_id: String,
status: common_enums::PayoutStatus,
},
+ #[cfg(feature = "v1")]
Refund {
payment_id: common_utils::id_type::PaymentId,
refund_id: String,
status: common_enums::RefundStatus,
},
+ #[cfg(feature = "v2")]
+ Refund {
+ payment_id: common_utils::id_type::GlobalPaymentId,
+ refund_id: String,
+ status: common_enums::RefundStatus,
+ },
+ #[cfg(feature = "v1")]
Dispute {
dispute_id: String,
payment_id: common_utils::id_type::PaymentId,
status: common_enums::DisputeStatus,
},
+ #[cfg(feature = "v2")]
+ Dispute {
+ dispute_id: String,
+ payment_id: common_utils::id_type::GlobalPaymentId,
+ status: common_enums::DisputeStatus,
+ },
Mandate {
mandate_id: String,
status: common_enums::MandateStatus,
@@ -103,6 +123,7 @@ pub enum WebhookResponseTracker {
}
impl WebhookResponseTracker {
+ #[cfg(feature = "v1")]
pub fn get_payment_id(&self) -> Option<common_utils::id_type::PaymentId> {
match self {
Self::Payment { payment_id, .. }
@@ -113,6 +134,18 @@ impl WebhookResponseTracker {
Self::Payout { .. } => None,
}
}
+
+ #[cfg(feature = "v2")]
+ pub fn get_payment_id(&self) -> Option<common_utils::id_type::GlobalPaymentId> {
+ match self {
+ Self::Payment { payment_id, .. }
+ | Self::Refund { payment_id, .. }
+ | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()),
+ Self::NoEffect | Self::Mandate { .. } => None,
+ #[cfg(feature = "payouts")]
+ Self::Payout { .. } => None,
+ }
+ }
}
impl From<IncomingWebhookEvent> for WebhookFlow {
@@ -227,6 +260,7 @@ pub struct OutgoingWebhook {
#[derive(Debug, Clone, Serialize, ToSchema)]
#[serde(tag = "type", content = "object", rename_all = "snake_case")]
+#[cfg(feature = "v1")]
pub enum OutgoingWebhookContent {
#[schema(value_type = PaymentsResponse, title = "PaymentsResponse")]
PaymentDetails(Box<payments::PaymentsResponse>),
@@ -241,6 +275,23 @@ pub enum OutgoingWebhookContent {
PayoutDetails(Box<payouts::PayoutCreateResponse>),
}
+#[derive(Debug, Clone, Serialize, ToSchema)]
+#[serde(tag = "type", content = "object", rename_all = "snake_case")]
+#[cfg(feature = "v2")]
+pub enum OutgoingWebhookContent {
+ #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")]
+ PaymentDetails(Box<payments::PaymentsRetrieveResponse>),
+ #[schema(value_type = RefundResponse, title = "RefundResponse")]
+ RefundDetails(Box<refunds::RefundResponse>),
+ #[schema(value_type = DisputeResponse, title = "DisputeResponse")]
+ DisputeDetails(Box<disputes::DisputeResponse>),
+ #[schema(value_type = MandateResponse, title = "MandateResponse")]
+ MandateDetails(Box<mandates::MandateResponse>),
+ #[cfg(feature = "payouts")]
+ #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]
+ PayoutDetails(Box<payouts::PayoutCreateResponse>),
+}
+
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorWebhookSecrets {
pub secret: Vec<u8>,
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index afe19d4123..3b86ea8e88 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -60,10 +60,16 @@ pub enum ApiEventsType {
PaymentMethodList {
payment_id: Option<String>,
},
+ #[cfg(feature = "v1")]
Webhooks {
connector: String,
payment_id: Option<id_type::PaymentId>,
},
+ #[cfg(feature = "v2")]
+ Webhooks {
+ connector: id_type::MerchantConnectorAccountId,
+ payment_id: Option<id_type::GlobalPaymentId>,
+ },
Routing,
ResourceListAPI,
#[cfg(feature = "v1")]
diff --git a/crates/common_utils/src/id_type/global_id/payment.rs b/crates/common_utils/src/id_type/global_id/payment.rs
index 6e5848e5a3..934d710604 100644
--- a/crates/common_utils/src/id_type/global_id/payment.rs
+++ b/crates/common_utils/src/id_type/global_id/payment.rs
@@ -66,3 +66,16 @@ impl GlobalAttemptId {
self.0.get_string_repr()
}
}
+
+impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptId {
+ type Error = error_stack::Report<errors::ValidationError>;
+ fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
+ use error_stack::ResultExt;
+ let global_attempt_id = super::GlobalId::from_string(value).change_context(
+ errors::ValidationError::IncorrectValueProvided {
+ field_name: "payment_id",
+ },
+ )?;
+ Ok(Self(global_attempt_id))
+ }
+}
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 527d0e7c02..7760ea76c5 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -765,7 +765,7 @@ pub struct PaymentAttemptUpdateInternal {
pub browser_info: Option<serde_json::Value>,
// payment_token: Option<String>,
pub error_code: Option<String>,
- // connector_metadata: Option<serde_json::Value>,
+ pub connector_metadata: Option<pii::SecretSerdeValue>,
// payment_method_data: Option<serde_json::Value>,
// payment_experience: Option<storage_enums::PaymentExperience>,
// preprocessing_step_id: Option<String>,
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index b52e3e2d33..46a8448889 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -188,6 +188,33 @@ impl PaymentAttempt {
.await
}
+ #[cfg(feature = "v2")]
+ pub async fn find_by_profile_id_connector_transaction_id(
+ conn: &PgPooledConn,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_txn_id: &str,
+ ) -> StorageResult<Self> {
+ let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data(
+ connector_txn_id.to_string(),
+ );
+ let connector_transaction_id = txn_id
+ .get_txn_id(txn_data.as_ref())
+ .change_context(DatabaseError::Others)
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed to retrieve txn_id for ({:?}, {:?})",
+ txn_id, txn_data
+ )
+ })?;
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .and(dsl::connector_payment_id.eq(connector_transaction_id.to_owned())),
+ )
+ .await
+ }
+
#[cfg(feature = "v1")]
pub async fn find_by_merchant_id_attempt_id(
conn: &PgPooledConn,
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 5c629f6198..1bab8ae3b7 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -574,3 +574,13 @@ where
/// This will depend on the payment status and the force sync flag in the request
pub should_sync_with_connector: bool,
}
+
+#[cfg(feature = "v2")]
+impl<F> PaymentStatusData<F>
+where
+ F: Clone,
+{
+ pub fn get_payment_id(&self) -> &id_type::GlobalPaymentId {
+ &self.payment_intent.id
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index db3ae20177..ec1463d1b7 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -102,6 +102,16 @@ pub trait PaymentAttemptInterface {
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
+ #[cfg(feature = "v2")]
+ async fn find_payment_attempt_by_profile_id_connector_transaction_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_id: &id_type::ProfileId,
+ connector_transaction_id: &str,
+ _storage_scheme: storage_enums::MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError>;
+
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
@@ -1309,6 +1319,7 @@ pub enum PaymentAttemptUpdate {
connector_payment_id: Option<String>,
updated_by: String,
redirection_data: Option<router_response_types::RedirectForm>,
+ connector_metadata: Option<pii::SecretSerdeValue>,
},
/// Update the payment attempt after force syncing with the connector
SyncUpdate {
@@ -1943,6 +1954,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
connector_payment_id: None,
connector: Some(connector),
redirection_data: None,
+ connector_metadata: None,
},
PaymentAttemptUpdate::ErrorUpdate {
status,
@@ -1963,12 +1975,14 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
connector_payment_id,
connector: None,
redirection_data: None,
+ connector_metadata: None,
},
PaymentAttemptUpdate::ConfirmIntentResponse {
status,
connector_payment_id,
updated_by,
redirection_data,
+ connector_metadata,
} => Self {
status: Some(status),
error_message: None,
@@ -1984,6 +1998,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
connector: None,
redirection_data: redirection_data
.map(diesel_models::payment_attempt::RedirectForm::from),
+ connector_metadata,
},
PaymentAttemptUpdate::SyncUpdate { status, updated_by } => Self {
status: Some(status),
@@ -1999,6 +2014,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
connector_payment_id: None,
connector: None,
redirection_data: None,
+ connector_metadata: None,
},
}
}
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index f995c9a1e5..0863ab59b4 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -471,6 +471,7 @@ impl
connector_payment_id,
updated_by: storage_scheme.to_string(),
redirection_data: *redirection_data.clone(),
+ connector_metadata: connector_metadata.clone().map(Secret::new),
}
}
router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index e2ccca4629..a2da338419 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -51,5 +51,4 @@ pub mod utils;
pub mod verification;
#[cfg(feature = "olap")]
pub mod verify_connector;
-#[cfg(feature = "v1")]
pub mod webhooks;
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index ed41650840..dd481467f1 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1642,11 +1642,16 @@ pub trait PaymentRedirectFlow: Sync {
let query_params = req.param.clone().get_required_value("param")?;
+ #[cfg(feature = "v1")]
let resource_id = api::PaymentIdTypeExt::get_payment_intent_id(&req.resource_id)
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_id",
})?;
+ #[cfg(feature = "v2")]
+ //TODO: Will get the global payment id from the resource id, we need to handle this in the further flow
+ let resource_id: id_type::PaymentId = todo!();
+
// This connector data is ephemeral, the call payment flow will get new connector data
// with merchant account details, so the connector_id can be safely set to None here
let connector_data = api::ConnectorData::get_connector_by_name(
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index a209d90f31..64c5617398 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -1,10 +1,17 @@
+#[cfg(feature = "v1")]
mod incoming;
+#[cfg(feature = "v2")]
+mod incoming_v2;
+#[cfg(feature = "v1")]
mod outgoing;
pub mod types;
pub mod utils;
#[cfg(feature = "olap")]
pub mod webhook_events;
+#[cfg(feature = "v2")]
+pub(crate) use self::incoming_v2::incoming_webhooks_wrapper;
+#[cfg(feature = "v1")]
pub(crate) use self::{
incoming::incoming_webhooks_wrapper,
outgoing::{
diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs
new file mode 100644
index 0000000000..0deb91efaa
--- /dev/null
+++ b/crates/router/src/core/webhooks/incoming_v2.rs
@@ -0,0 +1,753 @@
+use std::{marker::PhantomData, str::FromStr, time::Instant};
+
+use actix_web::FromRequest;
+use api_models::webhooks::{self, WebhookResponseTracker};
+use common_utils::{
+ errors::ReportSwitchExt, events::ApiEventsType, types::keymanager::KeyManagerState,
+};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payments::{HeaderPayload, PaymentStatusData},
+ router_request_types::VerifyWebhookSourceRequestData,
+ router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},
+};
+use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails;
+use router_env::{instrument, metrics::add_attributes, tracing, tracing_actix_web::RequestId};
+
+use super::{types, utils, MERCHANT_ID};
+use crate::{
+ core::{
+ api_locking,
+ errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},
+ metrics,
+ payments::{self, transformers::ToResponse},
+ webhooks::utils::construct_webhook_router_data,
+ },
+ db::StorageInterface,
+ events::api_logs::ApiEvent,
+ logger,
+ routes::{
+ app::{ReqState, SessionStateInfo},
+ lock_utils, SessionState,
+ },
+ services::{
+ self, authentication as auth, connector_integration_interface::ConnectorEnum,
+ ConnectorValidation,
+ },
+ types::{
+ api::{self, ConnectorData, GetToken, IncomingWebhook},
+ domain,
+ storage::enums,
+ transformers::ForeignInto,
+ },
+};
+
+#[allow(clippy::too_many_arguments)]
+pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
+ flow: &impl router_env::types::FlowMetric,
+ state: SessionState,
+ req_state: ReqState,
+ req: &actix_web::HttpRequest,
+ merchant_account: domain::MerchantAccount,
+ profile: domain::Profile,
+ key_store: domain::MerchantKeyStore,
+ connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ body: actix_web::web::Bytes,
+) -> RouterResponse<serde_json::Value> {
+ let start_instant = Instant::now();
+ let (application_response, webhooks_response_tracker, serialized_req) =
+ Box::pin(incoming_webhooks_core::<W>(
+ state.clone(),
+ req_state,
+ req,
+ merchant_account.clone(),
+ profile,
+ key_store,
+ connector_id,
+ body.clone(),
+ ))
+ .await?;
+
+ logger::info!(incoming_webhook_payload = ?serialized_req);
+
+ let request_duration = Instant::now()
+ .saturating_duration_since(start_instant)
+ .as_millis();
+
+ let request_id = RequestId::extract(req)
+ .await
+ .attach_printable("Unable to extract request id from request")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let auth_type = auth::AuthenticationType::WebhookAuth {
+ merchant_id: merchant_account.get_id().clone(),
+ };
+ let status_code = 200;
+ let api_event = ApiEventsType::Webhooks {
+ connector: connector_id.clone(),
+ payment_id: webhooks_response_tracker.get_payment_id(),
+ };
+ let response_value = serde_json::to_value(&webhooks_response_tracker)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not convert webhook effect to string")?;
+
+ let api_event = ApiEvent::new(
+ Some(merchant_account.get_id().clone()),
+ flow,
+ &request_id,
+ request_duration,
+ status_code,
+ serialized_req,
+ Some(response_value),
+ None,
+ auth_type,
+ None,
+ api_event,
+ req,
+ req.method(),
+ );
+ state.event_handler().log_event(&api_event);
+ Ok(application_response)
+}
+
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
+ state: SessionState,
+ req_state: ReqState,
+ req: &actix_web::HttpRequest,
+ merchant_account: domain::MerchantAccount,
+ profile: domain::Profile,
+ key_store: domain::MerchantKeyStore,
+ connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ body: actix_web::web::Bytes,
+) -> errors::RouterResult<(
+ services::ApplicationResponse<serde_json::Value>,
+ WebhookResponseTracker,
+ serde_json::Value,
+)> {
+ metrics::WEBHOOK_INCOMING_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::KeyValue::new(
+ MERCHANT_ID,
+ merchant_account.get_id().get_string_repr().to_owned(),
+ )],
+ );
+ let mut request_details = IncomingWebhookRequestDetails {
+ method: req.method().clone(),
+ uri: req.uri().clone(),
+ headers: req.headers(),
+ query_params: req.query_string().to_string(),
+ body: &body,
+ };
+
+ // Fetch the merchant connector account to get the webhooks source secret
+ // `webhooks source secret` is a secret shared between the merchant and connector
+ // This is used for source verification and webhooks integrity
+ let (merchant_connector_account, connector, connector_name) =
+ fetch_mca_and_connector(&state, connector_id, &key_store).await?;
+
+ let decoded_body = connector
+ .decode_webhook_body(
+ &request_details,
+ merchant_account.get_id(),
+ merchant_connector_account.connector_webhook_details.clone(),
+ connector_name.as_str(),
+ )
+ .await
+ .switch()
+ .attach_printable("There was an error in incoming webhook body decoding")?;
+
+ request_details.body = &decoded_body;
+
+ let event_type = match connector
+ .get_webhook_event_type(&request_details)
+ .allow_webhook_event_type_not_found(
+ state
+ .clone()
+ .conf
+ .webhooks
+ .ignore_error
+ .event_type
+ .unwrap_or(true),
+ )
+ .switch()
+ .attach_printable("Could not find event type in incoming webhook body")?
+ {
+ Some(event_type) => event_type,
+ // Early return allows us to acknowledge the webhooks that we do not support
+ None => {
+ logger::error!(
+ webhook_payload =? request_details.body,
+ "Failed while identifying the event type",
+ );
+
+ metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[
+ metrics::KeyValue::new(MERCHANT_ID, merchant_account.get_id().clone()),
+ metrics::KeyValue::new("connector", connector_name.to_string()),
+ ],
+ );
+
+ let response = connector
+ .get_webhook_api_response(&request_details)
+ .switch()
+ .attach_printable("Failed while early return in case of event type parsing")?;
+
+ return Ok((
+ response,
+ WebhookResponseTracker::NoEffect,
+ serde_json::Value::Null,
+ ));
+ }
+ };
+ logger::info!(event_type=?event_type);
+
+ let is_webhook_event_supported = !matches!(
+ event_type,
+ webhooks::IncomingWebhookEvent::EventNotSupported
+ );
+ let is_webhook_event_enabled = !utils::is_webhook_event_disabled(
+ &*state.clone().store,
+ connector_name.as_str(),
+ merchant_account.get_id(),
+ &event_type,
+ )
+ .await;
+
+ //process webhook further only if webhook event is enabled and is not event_not_supported
+ let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported;
+
+ logger::info!(process_webhook=?process_webhook_further);
+
+ let flow_type: api::WebhookFlow = event_type.into();
+ let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null);
+ let webhook_effect = if process_webhook_further
+ && !matches!(flow_type, api::WebhookFlow::ReturnResponse)
+ {
+ let object_ref_id = connector
+ .get_webhook_object_reference_id(&request_details)
+ .switch()
+ .attach_printable("Could not find object reference id in incoming webhook body")?;
+ let connector_enum = api_models::enums::Connector::from_str(&connector_name)
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "connector",
+ })
+ .attach_printable_lazy(|| {
+ format!("unable to parse connector name {connector_name:?}")
+ })?;
+ let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;
+
+ let source_verified = if connectors_with_source_verification_call
+ .connectors_with_webhook_source_verification_call
+ .contains(&connector_enum)
+ {
+ verify_webhook_source_verification_call(
+ connector.clone(),
+ &state,
+ &merchant_account,
+ merchant_connector_account.clone(),
+ &connector_name,
+ &request_details,
+ )
+ .await
+ .or_else(|error| match error.current_context() {
+ errors::ConnectorError::WebhookSourceVerificationFailed => {
+ logger::error!(?error, "Source Verification Failed");
+ Ok(false)
+ }
+ _ => Err(error),
+ })
+ .switch()
+ .attach_printable("There was an issue in incoming webhook source verification")?
+ } else {
+ connector
+ .clone()
+ .verify_webhook_source(
+ &request_details,
+ merchant_account.get_id(),
+ merchant_connector_account.connector_webhook_details.clone(),
+ merchant_connector_account.connector_account_details.clone(),
+ connector_name.as_str(),
+ )
+ .await
+ .or_else(|error| match error.current_context() {
+ errors::ConnectorError::WebhookSourceVerificationFailed => {
+ logger::error!(?error, "Source Verification Failed");
+ Ok(false)
+ }
+ _ => Err(error),
+ })
+ .switch()
+ .attach_printable("There was an issue in incoming webhook source verification")?
+ };
+
+ logger::info!(source_verified=?source_verified);
+
+ if source_verified {
+ metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::KeyValue::new(
+ MERCHANT_ID,
+ merchant_account.get_id().clone(),
+ )],
+ );
+ }
+
+ // If source verification is mandatory and source is not verified, fail with webhook authentication error
+ // else continue the flow
+ match (
+ connector.is_webhook_source_verification_mandatory(),
+ source_verified,
+ ) {
+ (true, false) => Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)?,
+ _ => {
+ event_object = connector
+ .get_webhook_resource_object(&request_details)
+ .switch()
+ .attach_printable("Could not find resource object in incoming webhook body")?;
+
+ let webhook_details = api::IncomingWebhookDetails {
+ object_reference_id: object_ref_id.clone(),
+ resource_object: serde_json::to_vec(&event_object)
+ .change_context(errors::ParsingError::EncodeError("byte-vec"))
+ .attach_printable("Unable to convert webhook payload to a value")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "There was an issue when encoding the incoming webhook body to bytes",
+ )?,
+ };
+
+ match flow_type {
+ api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
+ state.clone(),
+ req_state,
+ merchant_account,
+ profile,
+ key_store,
+ webhook_details,
+ source_verified,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for payments failed")?,
+
+ api::WebhookFlow::Refund => todo!(),
+
+ api::WebhookFlow::Dispute => todo!(),
+
+ api::WebhookFlow::BankTransfer => todo!(),
+
+ api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect,
+
+ api::WebhookFlow::Mandate => todo!(),
+
+ api::WebhookFlow::ExternalAuthentication => todo!(),
+ api::WebhookFlow::FraudCheck => todo!(),
+
+ #[cfg(feature = "payouts")]
+ api::WebhookFlow::Payout => todo!(),
+
+ api::WebhookFlow::Subscription => todo!(),
+ }
+ }
+ }
+ } else {
+ metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::KeyValue::new(
+ MERCHANT_ID,
+ merchant_account.get_id().get_string_repr().to_owned(),
+ )],
+ );
+ WebhookResponseTracker::NoEffect
+ };
+
+ let response = connector
+ .get_webhook_api_response(&request_details)
+ .switch()
+ .attach_printable("Could not get incoming webhook api response from connector")?;
+
+ let serialized_request = event_object
+ .masked_serialize()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not convert webhook effect to string")?;
+ Ok((response, webhook_effect, serialized_request))
+}
+
+#[instrument(skip_all)]
+async fn payments_incoming_webhook_flow(
+ state: SessionState,
+ req_state: ReqState,
+ merchant_account: domain::MerchantAccount,
+ profile: domain::Profile,
+ key_store: domain::MerchantKeyStore,
+ webhook_details: api::IncomingWebhookDetails,
+ source_verified: bool,
+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
+ let consume_or_trigger_flow = if source_verified {
+ payments::CallConnectorAction::HandleResponse(webhook_details.resource_object)
+ } else {
+ payments::CallConnectorAction::Trigger
+ };
+ let key_manager_state = &(&state).into();
+ let payments_response = 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(),
+ &id,
+ profile.get_id(),
+ key_manager_state,
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await?;
+
+ let payment_id = get_trackers_response.payment_data.get_payment_id();
+
+ let lock_action = api_locking::LockAction::Hold {
+ input: api_locking::LockingInput {
+ unique_locking_key: payment_id.get_string_repr().to_owned(),
+ api_identifier: lock_utils::ApiIdentifier::Payments,
+ override_lock_retries: None,
+ },
+ };
+
+ lock_action
+ .clone()
+ .perform_locking_action(&state, merchant_account.get_id().to_owned())
+ .await?;
+
+ let (payment_data, _req, customer, connector_http_status_code, external_latency) =
+ Box::pin(payments::payments_operation_core::<
+ api::PSync,
+ _,
+ _,
+ _,
+ PaymentStatusData<api::PSync>,
+ >(
+ &state,
+ req_state,
+ merchant_account.clone(),
+ key_store.clone(),
+ profile,
+ payments::operations::PaymentGet,
+ api::PaymentsRetrieveRequest {
+ force_sync: true,
+ param: None,
+ },
+ get_trackers_response,
+ consume_or_trigger_flow,
+ HeaderPayload::default(),
+ ))
+ .await?;
+
+ let response = api_models::payments::PaymentsRetrieveResponse::generate_response(
+ payment_data,
+ customer,
+ &state.base_url,
+ payments::operations::PaymentGet,
+ &state.conf.connector_request_reference_id_config,
+ connector_http_status_code,
+ external_latency,
+ None,
+ &merchant_account,
+ );
+
+ lock_action
+ .free_lock_action(&state, merchant_account.get_id().to_owned())
+ .await?;
+
+ match response {
+ Ok(value) => value,
+ Err(err)
+ if matches!(
+ err.current_context(),
+ &errors::ApiErrorResponse::PaymentNotFound
+ ) && state
+ .clone()
+ .conf
+ .webhooks
+ .ignore_error
+ .payment_not_found
+ .unwrap_or(true) =>
+ {
+ metrics::WEBHOOK_PAYMENT_NOT_FOUND.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("merchant_id", merchant_account.get_id().clone())]),
+ );
+ return Ok(WebhookResponseTracker::NoEffect);
+ }
+ error @ Err(_) => error?,
+ }
+ }
+ _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
+ "Did not get payment id as object reference id in webhook payments flow",
+ )?,
+ };
+
+ match payments_response {
+ services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
+ let payment_id = payments_response.id.clone();
+
+ let status = payments_response.status;
+
+ let event_type: Option<enums::EventType> = payments_response.status.foreign_into();
+
+ // 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
+ // Box::pin(super::create_event_and_trigger_outgoing_webhook(
+ // state,
+ // merchant_account,
+ // profile,
+ // &key_store,
+ // outgoing_event_type,
+ // enums::EventClass::Payments,
+ // payment_id.get_string_repr().to_owned(),
+ // enums::EventObjectType::PaymentDetails,
+ // api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
+ // Some(primary_object_created_at),
+ // ))
+ // .await?;
+ };
+
+ let response = WebhookResponseTracker::Payment { payment_id, status };
+
+ Ok(response)
+ }
+
+ _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("received non-json response from payments core")?,
+ }
+}
+
+async fn get_trackers_response_for_payment_get_operation<F>(
+ db: &dyn StorageInterface,
+ payment_id: &api::PaymentIdType,
+ profile_id: &common_utils::id_type::ProfileId,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
+) -> errors::RouterResult<payments::operations::GetTrackerResponse<PaymentStatusData<F>>>
+where
+ F: Clone,
+{
+ let (payment_intent, payment_attempt) = match payment_id {
+ api_models::payments::PaymentIdType::PaymentIntentId(ref id) => {
+ let payment_intent = db
+ .find_payment_intent_by_id(
+ key_manager_state,
+ id,
+ merchant_key_store,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let payment_attempt = db
+ .find_payment_attempt_by_id(
+ key_manager_state,
+ merchant_key_store,
+ &payment_intent
+ .active_attempt_id
+ .clone()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("active_attempt_id not present in payment_attempt")?,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ (payment_intent, payment_attempt)
+ }
+ api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => {
+ let payment_attempt = db
+ .find_payment_attempt_by_profile_id_connector_transaction_id(
+ key_manager_state,
+ merchant_key_store,
+ profile_id,
+ id,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let payment_intent = db
+ .find_payment_intent_by_id(
+ key_manager_state,
+ &payment_attempt.payment_id,
+ merchant_key_store,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ (payment_intent, payment_attempt)
+ }
+ api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => {
+ let global_attempt_id = common_utils::id_type::GlobalAttemptId::try_from(
+ std::borrow::Cow::Owned(id.to_owned()),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while getting GlobalAttemptId")?;
+ let payment_attempt = db
+ .find_payment_attempt_by_id(
+ key_manager_state,
+ merchant_key_store,
+ &global_attempt_id,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let payment_intent = db
+ .find_payment_intent_by_id(
+ key_manager_state,
+ &payment_attempt.payment_id,
+ merchant_key_store,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ (payment_intent, payment_attempt)
+ }
+ api_models::payments::PaymentIdType::PreprocessingId(ref _id) => todo!(),
+ };
+ Ok(payments::operations::GetTrackerResponse {
+ payment_data: PaymentStatusData {
+ flow: PhantomData,
+ payment_intent,
+ payment_attempt: Some(payment_attempt),
+ should_sync_with_connector: true,
+ },
+ })
+}
+
+#[inline]
+async fn verify_webhook_source_verification_call(
+ connector: ConnectorEnum,
+ state: &SessionState,
+ merchant_account: &domain::MerchantAccount,
+ merchant_connector_account: domain::MerchantConnectorAccount,
+ connector_name: &str,
+ request_details: &IncomingWebhookRequestDetails<'_>,
+) -> CustomResult<bool, errors::ConnectorError> {
+ let connector_data = ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ connector_name,
+ GetToken::Connector,
+ None,
+ )
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("invalid connector name received in payment attempt")?;
+ let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface<
+ hyperswitch_domain_models::router_flow_types::VerifyWebhookSource,
+ VerifyWebhookSourceRequestData,
+ VerifyWebhookSourceResponseData,
+ > = connector_data.connector.get_connector_integration();
+ let connector_webhook_secrets = connector
+ .get_webhook_source_verification_merchant_secret(
+ merchant_account.get_id(),
+ connector_name,
+ merchant_connector_account.connector_webhook_details.clone(),
+ )
+ .await
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
+
+ let router_data = construct_webhook_router_data(
+ connector_name,
+ merchant_connector_account,
+ merchant_account,
+ &connector_webhook_secrets,
+ request_details,
+ )
+ .await
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed while constructing webhook router data")?;
+
+ let response = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ )
+ .await?;
+
+ let verification_result = response
+ .response
+ .map(|response| response.verify_webhook_status);
+ match verification_result {
+ Ok(VerifyWebhookStatus::SourceVerified) => Ok(true),
+ _ => Ok(false),
+ }
+}
+
+fn get_connector_by_connector_name(
+ state: &SessionState,
+ connector_name: &str,
+ merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> {
+ let authentication_connector =
+ api_models::enums::convert_authentication_connector(connector_name);
+ #[cfg(feature = "frm")]
+ {
+ let frm_connector = api_models::enums::convert_frm_connector(connector_name);
+ if frm_connector.is_some() {
+ let frm_connector_data =
+ api::FraudCheckConnectorData::get_connector_by_name(connector_name)?;
+ return Ok((
+ frm_connector_data.connector,
+ frm_connector_data.connector_name.to_string(),
+ ));
+ }
+ }
+
+ let (connector, connector_name) = if authentication_connector.is_some() {
+ let authentication_connector_data =
+ api::AuthenticationConnectorData::get_connector_by_name(connector_name)?;
+ (
+ authentication_connector_data.connector,
+ authentication_connector_data.connector_name.to_string(),
+ )
+ } else {
+ let connector_data = ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ connector_name,
+ GetToken::Connector,
+ merchant_connector_id,
+ )
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "invalid connector name received".to_string(),
+ })
+ .attach_printable("Failed construction of ConnectorData")?;
+ (
+ connector_data.connector,
+ connector_data.connector_name.to_string(),
+ )
+ };
+ Ok((connector, connector_name))
+}
+
+/// This function fetches the merchant connector account and connector details
+async fn fetch_mca_and_connector(
+ state: &SessionState,
+ connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ key_store: &domain::MerchantKeyStore,
+) -> CustomResult<(domain::MerchantConnectorAccount, ConnectorEnum, String), errors::ApiErrorResponse>
+{
+ let db = &state.store;
+ let mca = db
+ .find_merchant_connector_account_by_id(&state.into(), connector_id, key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: connector_id.get_string_repr().to_owned(),
+ })
+ .attach_printable("error while fetching merchant_connector_account from connector_id")?;
+
+ let (connector, connector_name) =
+ get_connector_by_connector_name(state, &mca.connector_name, Some(mca.get_id()))?;
+
+ Ok((mca, connector, connector_name))
+}
diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs
index 64b52b7995..10e4b0eafb 100644
--- a/crates/router/src/core/webhooks/webhook_events.rs
+++ b/crates/router/src/core/webhooks/webhook_events.rs
@@ -152,6 +152,7 @@ pub async fn list_delivery_attempts(
}
#[instrument(skip(state))]
+#[cfg(feature = "v1")]
pub async fn retry_delivery_attempt(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 93181c6614..a9df1abbc0 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1485,6 +1485,26 @@ impl PaymentAttemptInterface for KafkaStore {
.await
}
+ #[cfg(feature = "v2")]
+ async fn find_payment_attempt_by_profile_id_connector_transaction_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ profile_id: &id_type::ProfileId,
+ connector_transaction_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> {
+ self.diesel_store
+ .find_payment_attempt_by_profile_id_connector_transaction_id(
+ key_manager_state,
+ merchant_key_store,
+ profile_id,
+ connector_transaction_id,
+ storage_scheme,
+ )
+ .await
+ }
+
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs
index db5a40fc6e..64126ec76d 100644
--- a/crates/router/src/events/outgoing_webhook_logs.rs
+++ b/crates/router/src/events/outgoing_webhook_logs.rs
@@ -26,10 +26,16 @@ pub struct OutgoingWebhookEvent {
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "outgoing_webhook_event_type", rename_all = "snake_case")]
pub enum OutgoingWebhookEventContent {
+ #[cfg(feature = "v1")]
Payment {
payment_id: common_utils::id_type::PaymentId,
content: Value,
},
+ #[cfg(feature = "v2")]
+ Payment {
+ payment_id: common_utils::id_type::GlobalPaymentId,
+ content: Value,
+ },
Payout {
payout_id: String,
content: Value,
@@ -61,6 +67,8 @@ pub enum OutgoingWebhookEventContent {
pub trait OutgoingWebhookEventMetric {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>;
}
+
+#[cfg(feature = "v1")]
impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> {
match self {
@@ -98,6 +106,44 @@ impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
}
}
+#[cfg(feature = "v2")]
+impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
+ fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> {
+ match self {
+ Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment {
+ payment_id: payment_payload.id.clone(),
+ content: masking::masked_serialize(&payment_payload)
+ .unwrap_or(serde_json::json!({"error":"failed to serialize"})),
+ }),
+ Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund {
+ payment_id: refund_payload.payment_id.clone(),
+ refund_id: refund_payload.get_refund_id_as_string(),
+ content: masking::masked_serialize(&refund_payload)
+ .unwrap_or(serde_json::json!({"error":"failed to serialize"})),
+ }),
+ Self::DisputeDetails(dispute_payload) => Some(OutgoingWebhookEventContent::Dispute {
+ payment_id: dispute_payload.payment_id.clone(),
+ attempt_id: dispute_payload.attempt_id.clone(),
+ dispute_id: dispute_payload.dispute_id.clone(),
+ content: masking::masked_serialize(&dispute_payload)
+ .unwrap_or(serde_json::json!({"error":"failed to serialize"})),
+ }),
+ Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate {
+ payment_method_id: mandate_payload.payment_method_id.clone(),
+ mandate_id: mandate_payload.mandate_id.clone(),
+ content: masking::masked_serialize(&mandate_payload)
+ .unwrap_or(serde_json::json!({"error":"failed to serialize"})),
+ }),
+ #[cfg(feature = "payouts")]
+ Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout {
+ payout_id: payout_payload.payout_id.clone(),
+ content: masking::masked_serialize(&payout_payload)
+ .unwrap_or(serde_json::json!({"error":"failed to serialize"})),
+ }),
+ }
+ }
+}
+
impl OutgoingWebhookEvent {
#[allow(clippy::too_many_arguments)]
pub fn new(
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 7efaab21d5..829216db1d 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -138,7 +138,8 @@ pub fn mk_app(
.service(routes::Payments::server(state.clone()))
.service(routes::Customers::server(state.clone()))
.service(routes::Configs::server(state.clone()))
- .service(routes::MerchantConnectorAccount::server(state.clone()));
+ .service(routes::MerchantConnectorAccount::server(state.clone()))
+ .service(routes::Webhooks::server(state.clone()));
#[cfg(feature = "v1")]
{
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 0f1529a9bd..aaadcaa4eb 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -56,7 +56,6 @@ pub mod verification;
pub mod verify_connector;
#[cfg(all(feature = "olap", feature = "v1"))]
pub mod webhook_events;
-#[cfg(feature = "v1")]
pub mod webhooks;
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 892dfa62a3..5c81db35ea 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -48,7 +48,7 @@ use super::poll;
use super::routing;
#[cfg(all(feature = "olap", feature = "v1"))]
use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};
-#[cfg(all(feature = "oltp", feature = "v1"))]
+#[cfg(feature = "oltp")]
use super::webhooks::*;
use super::{
admin, api_keys, cache::*, connector_onboarding, disputes, files, gsm, health::*, profiles,
@@ -1437,6 +1437,29 @@ impl Webhooks {
}
}
+#[cfg(all(feature = "oltp", feature = "v2"))]
+impl Webhooks {
+ pub fn server(config: AppState) -> Scope {
+ use api_models::webhooks as webhook_type;
+
+ #[allow(unused_mut)]
+ let mut route = web::scope("/v2/webhooks")
+ .app_data(web::Data::new(config))
+ .service(
+ web::resource("/{merchant_id}/{profile_id}/{connector_id}")
+ .route(
+ web::post().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>),
+ )
+ .route(web::get().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>))
+ .route(
+ web::put().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>),
+ ),
+ );
+
+ route
+ }
+}
+
pub struct Configs;
#[cfg(any(feature = "olap", feature = "oltp"))]
diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rs
index 5039f72db3..08427012ce 100644
--- a/crates/router/src/routes/webhook_events.rs
+++ b/crates/router/src/routes/webhook_events.rs
@@ -92,6 +92,7 @@ pub async fn list_webhook_delivery_attempts(
}
#[instrument(skip_all, fields(flow = ?Flow::WebhookEventDeliveryRetry))]
+#[cfg(feature = "v1")]
pub async fn retry_webhook_delivery_attempt(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs
index 43b50b0460..5427ac34b4 100644
--- a/crates/router/src/routes/webhooks.rs
+++ b/crates/router/src/routes/webhooks.rs
@@ -11,6 +11,7 @@ use crate::{
};
#[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))]
+#[cfg(feature = "v1")]
pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
@@ -42,3 +43,45 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
))
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))]
+#[cfg(feature = "v2")]
+pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ body: web::Bytes,
+ path: web::Path<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantConnectorAccountId,
+ )>,
+) -> impl Responder {
+ let flow = Flow::IncomingWebhookReceive;
+ let (merchant_id, profile_id, connector_id) = path.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow.clone(),
+ state,
+ &req,
+ (),
+ |state, auth, _, req_state| {
+ webhooks::incoming_webhooks_wrapper::<W>(
+ &flow,
+ state.to_owned(),
+ req_state,
+ &req,
+ auth.merchant_account,
+ auth.profile,
+ auth.key_store,
+ &connector_id,
+ body.clone(),
+ )
+ },
+ &auth::MerchantIdAndProfileIdAuth {
+ merchant_id,
+ profile_id,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index d4ac3bc846..2541a5dc7d 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1403,6 +1403,65 @@ where
}
}
+#[derive(Debug)]
+#[cfg(feature = "v2")]
+pub struct MerchantIdAndProfileIdAuth {
+ pub merchant_id: id_type::MerchantId,
+ pub profile_id: id_type::ProfileId,
+}
+
+#[cfg(feature = "v2")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAndProfileIdAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ let key_manager_state = &(&state.session_state()).into();
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &self.merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+
+ let profile = state
+ .store()
+ .find_business_profile_by_merchant_id_profile_id(
+ key_manager_state,
+ &key_store,
+ &self.merchant_id,
+ &self.profile_id,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(key_manager_state, &self.merchant_id, &key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+
+ let auth = AuthenticationData {
+ merchant_account: merchant,
+ key_store,
+ profile,
+ };
+ Ok((
+ auth.clone(),
+ AuthenticationType::MerchantId {
+ merchant_id: auth.merchant_account.get_id().clone(),
+ },
+ ))
+ }
+}
+
#[derive(Debug)]
#[cfg(feature = "v2")]
pub struct PublishableKeyAndProfileIdAuth {
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 57ef1d3336..524712f1ca 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -45,12 +45,19 @@ pub use super::payments_v2::{
use crate::core::errors;
pub trait PaymentIdTypeExt {
+ #[cfg(feature = "v1")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::PaymentId, errors::ValidationError>;
+
+ #[cfg(feature = "v2")]
+ fn get_payment_intent_id(
+ &self,
+ ) -> errors::CustomResult<common_utils::id_type::GlobalPaymentId, errors::ValidationError>;
}
impl PaymentIdTypeExt for PaymentIdType {
+ #[cfg(feature = "v1")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::PaymentId, errors::ValidationError> {
@@ -64,6 +71,21 @@ impl PaymentIdTypeExt for PaymentIdType {
.attach_printable("Expected payment intent ID but got connector transaction ID"),
}
}
+
+ #[cfg(feature = "v2")]
+ fn get_payment_intent_id(
+ &self,
+ ) -> errors::CustomResult<common_utils::id_type::GlobalPaymentId, errors::ValidationError> {
+ match self {
+ Self::PaymentIntentId(id) => Ok(id.clone()),
+ Self::ConnectorTransactionId(_)
+ | Self::PaymentAttemptId(_)
+ | Self::PreprocessingId(_) => Err(errors::ValidationError::IncorrectValueProvided {
+ field_name: "payment_id",
+ })
+ .attach_printable("Expected payment intent ID but got connector transaction ID"),
+ }
+ }
}
pub(crate) trait MandateValidationFieldsExt {
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index ae4a9e659a..83691f4612 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -103,6 +103,19 @@ impl PaymentAttemptInterface for MockDb {
Err(StorageError::MockDbError)?
}
+ #[cfg(feature = "v2")]
+ async fn find_payment_attempt_by_profile_id_connector_transaction_id(
+ &self,
+ _key_manager_state: &KeyManagerState,
+ _merchant_key_store: &MerchantKeyStore,
+ _profile_id: &id_type::ProfileId,
+ _connector_transaction_id: &str,
+ _storage_scheme: storage_enums::MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
#[cfg(feature = "v1")]
async fn find_attempts_by_merchant_id_payment_id(
&self,
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 7bc9bcc8a9..9b9121952b 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -215,8 +215,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
.map(PaymentAttempt::from_storage_model)
}
- #[cfg(feature = "v1")]
#[instrument(skip_all)]
+ #[cfg(feature = "v1")]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -237,6 +237,36 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
.map(PaymentAttempt::from_storage_model)
}
+ #[instrument(skip_all)]
+ #[cfg(feature = "v2")]
+ async fn find_payment_attempt_by_profile_id_connector_transaction_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_txn_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+ DieselPaymentAttempt::find_by_profile_id_connector_transaction_id(
+ &conn,
+ profile_id,
+ connector_txn_id,
+ )
+ .await
+ .map_err(|er| {
+ let new_err = diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })?
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
@@ -933,8 +963,29 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
}
}
- #[cfg(feature = "v1")]
+ #[cfg(feature = "v2")]
+ async fn find_payment_attempt_by_profile_id_connector_transaction_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_transaction_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ // Ignoring storage scheme for v2 implementation
+ self.router_store
+ .find_payment_attempt_by_profile_id_connector_transaction_id(
+ key_manager_state,
+ merchant_key_store,
+ profile_id,
+ connector_transaction_id,
+ storage_scheme,
+ )
+ .await
+ }
+
#[instrument(skip_all)]
+ #[cfg(feature = "v1")]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,