Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(connector): [Envoy] Implement Incoming Webhooks (#14953)
Anurag6cc34d48d971
diff --git a/crates/hyperswitch_connectors/src/connectors/envoy.rs b/crates/hyperswitch_connectors/src/connectors/envoy.rsindex 33e324743d..3a846efdf5 100644--- a/crates/hyperswitch_connectors/src/connectors/envoy.rs+++ b/crates/hyperswitch_connectors/src/connectors/envoy.rs@@ -9,8 +9,9 @@ use common_utils::{request::{Method, Request, RequestBuilder, RequestContent},types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},};-use error_stack::{report, ResultExt};+use error_stack::ResultExt;use hyperswitch_domain_models::{+ api::WebhookResponse,router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},router_flow_types::{access_token_auth::AccessTokenAuth,@@ -673,27 +674,118 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Envoy {#[async_trait::async_trait]impl webhooks::IncomingWebhook for Envoy {- fn get_webhook_object_reference_id(+ async fn verify_webhook_source(&self,_request: &webhooks::IncomingWebhookRequestDetails<'_>,+ _merchant_id: &common_utils::id_type::MerchantId,+ _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,+ _connector_account_details: common_utils::crypto::Encryptable<+ hyperswitch_masking::Secret<serde_json::Value>,+ >,+ _connector_label: &str,+ ) -> CustomResult<bool, errors::ConnectorError> {+ Ok(false)+ }++ fn get_webhook_object_reference_id(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))+ let body: envoy::EnvoyNotification = utils::deserialize_xml_to_struct(request.body)?;++ let connector_payout_id = match body {+ envoy::EnvoyNotification::PaymentOutNotification(payload) => {+ payload+ .payment_details+ .original_payment_info+ .merchant_reference+ }+ envoy::EnvoyNotification::PaymentOutReversalNotification(payload) => {+ payload+ .reversal_info+ .original_payment_info+ .merchant_reference+ }+ };++ Ok(api_models::webhooks::ObjectReferenceId::PayoutId(+ api_models::webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id),+ ))}fn get_webhook_event_type(&self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,_context: Option<&webhooks::WebhookContext>,) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))+ let body: envoy::EnvoyNotification = utils::deserialize_xml_to_struct(request.body)?;++ match body {+ envoy::EnvoyNotification::PaymentOutNotification(_) => {+ Ok(api_models::webhooks::IncomingWebhookEvent::PayoutSuccess)+ }+ envoy::EnvoyNotification::PaymentOutReversalNotification(_) => {+ Ok(api_models::webhooks::IncomingWebhookEvent::PayoutFailure)+ }+ }}fn get_webhook_resource_object(&self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<Box<dyn hyperswitch_masking::ErasedMaskSerialize>, errors::ConnectorError>{- Err(report!(errors::ConnectorError::WebhooksNotImplemented))+ let body: envoy::EnvoyNotification = utils::deserialize_xml_to_struct(request.body)?;++ Ok(Box::new(body))+ }++ fn get_webhook_api_response(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ error_kind: Option<webhooks::IncomingWebhookFlowError>,+ _connector_authentication_type: Option<+ common_utils::crypto::Encryptable<hyperswitch_masking::Secret<serde_json::Value>>,+ >,+ ) -> CustomResult<WebhookResponse<serde_json::Value>, errors::ConnectorError> {+ let body: envoy::EnvoyNotification = utils::deserialize_xml_to_struct(request.body)?;++ let result = match error_kind {+ Some(_) => envoy::EnvoyNotificationResult::Error,+ None => envoy::EnvoyNotificationResult::Success,+ };++ let response = match body {+ envoy::EnvoyNotification::PaymentOutNotification(_) => {+ let notification_response = envoy::EnvoyNotificationResponse::new(+ envoy::PaymentOutNotificationResponse::new(result),+ );+ utils::XmlSerializer::serialize_to_xml_bytes(+ ¬ification_response,+ "1.0",+ Some("UTF-8"),+ None,+ None,+ )?+ }+ envoy::EnvoyNotification::PaymentOutReversalNotification(_) => {+ let notification_response = envoy::EnvoyNotificationResponse::new(+ envoy::PaymentOutReversalNotificationResponse::new(result),+ );+ utils::XmlSerializer::serialize_to_xml_bytes(+ ¬ification_response,+ "1.0",+ Some("UTF-8"),+ None,+ None,+ )?+ }+ };++ Ok(WebhookResponse::Xml(+ String::from_utf8(response)+ .change_context(errors::ConnectorError::WebhookResponseEncodingFailed)?,+ ))}}@@ -707,7 +799,7 @@ static ENVOY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {integration_status: enums::ConnectorIntegrationStatus::Live,};-static ENVOY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];+static ENVOY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payouts];impl ConnectorSpecifications for Envoy {fn is_webhook_ip_verification_required(&self) -> bool {diff --git a/crates/hyperswitch_connectors/src/connectors/envoy/transformers.rs b/crates/hyperswitch_connectors/src/connectors/envoy/transformers.rsindex ac76a00bef..74e79bcba5 100644--- a/crates/hyperswitch_connectors/src/connectors/envoy/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/envoy/transformers.rs@@ -296,8 +296,7 @@ pub struct PaymentDetails {pub target_currency: Currency,pub target_amount: FloatMajorUnit,pub source_or_target: SourceOrTarget,- #[serde(skip_serializing_if = "Option::is_none")]- pub merchant_reference: Option<String>,+ pub merchant_reference: PayoutId,pub payment_reference: PayoutId,#[serde(skip_serializing_if = "Option::is_none")]pub email: Option<Email>,@@ -515,7 +514,7 @@ impl<F> TryFrom<&EnvoyRouterData<&PayoutsRouterData<F>>> for PayToBankAccountV3target_currency: payout_data.destination_currency,target_amount: item.amount.to_owned(),source_or_target: SourceOrTarget::Target,- merchant_reference: None,+ merchant_reference: payout_data.payout_id.clone(),payment_reference: payout_data.payout_id.clone(),email: customer_details.as_ref().and_then(|c| c.email.clone()),mobile: customer_details.as_ref().and_then(|c| c.phone.clone()),@@ -615,9 +614,9 @@ impl From<i32> for ResponseStatus {impl From<ResponseStatus> for enums::PayoutStatus {fn from(status: ResponseStatus) -> Self {match status {- ResponseStatus::Success => Self::Success,- ResponseStatus::SuccessNoResults => Self::Pending,- ResponseStatus::Processing => Self::Pending,+ ResponseStatus::Success+ | ResponseStatus::SuccessNoResults+ | ResponseStatus::Processing => Self::Pending,ResponseStatus::Failed(_) => Self::Failed,}}@@ -688,3 +687,172 @@ impl TryFrom<PayoutsResponseRouterData<PoFulfill, EnvoyPayoutSoapResponse>>}}}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename = "Envelope")]+pub struct EnvoyNotificationEnvelope {+ #[serde(rename = "Body")]+ pub body: EnvoyNotificationBody,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct EnvoyNotificationBody {+ #[serde(rename = "$value")]+ pub notification: EnvoyNotification,+}++#[derive(Debug, Serialize, Deserialize)]+pub enum EnvoyNotification {+ PaymentOutNotification(PaymentOutNotification),+ PaymentOutReversalNotification(PaymentOutReversalNotification),+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PaymentOutNotification {+ pub payment_details: EnvoyPaymentDetails,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct EnvoyPaymentDetails {+ pub original_payment_info: OriginalPaymentInfo,+ payment_result: PaymentResult,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OriginalPaymentInfo {+ country_code: CountryAlpha2,+ payee: Option<Secret<String>>,+ pub merchant_reference: String,+ merchant_payment_reference: Option<String>,+ source_currency: Currency,+ source_amount: FloatMajorUnit,+ target_currency: Currency,+ target_amount: FloatMajorUnit,+ source_or_target: SourceOrTarget,+ fast_payment: YesNo,+ additional_info1: Option<String>,+ additional_info2: Option<String>,+ additional_info3: Option<String>,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PaymentResult {+ envoy_merchant_account_number: Secret<String>,+ item_number: Option<Secret<i64>>,+ statement_id: Secret<String>,+ epacs_reference: String,+ execution_date: String,+ applied_currency: Currency,+ applied_amount: FloatMajorUnit,+ estimated_settlement_date: Option<String>,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PaymentOutReversalNotification {+ pub reversal_info: ReversalInfo,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ReversalInfo {+ pub original_payment_info: OriginalPaymentInfo,+ credit: Option<Credit>,+ debit: Option<Debit>,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Credit {+ envoy_merchant_account_number: Secret<String>,+ item_number: Option<Secret<i64>>,+ statement_id: Secret<String>,+ epacs_reference: String,+ posting_date: String,+ credit_currency: Option<Currency>,+ credit_amount: FloatMajorUnit,+ reversal_reason: Option<String>,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Debit {+ envoy_merchant_account_number: Secret<String>,+ item_number: Option<Secret<i64>>,+ statement_id: Secret<String>,+ epacs_reference: String,+ posting_date: String,+ debit_currency: Currency,+ debit_amount: FloatMajorUnit,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum EnvoyNotificationResult {+ Success,+ Error,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename = "soap:Envelope")]+pub struct EnvoyNotificationResponse<T> {+ #[serde(rename = "@xmlns:soap")]+ pub soap: String,+ #[serde(rename = "@xmlns:xsd")]+ pub xsd: String,+ #[serde(rename = "@xmlns:xsi")]+ pub xsi: String,+ #[serde(rename = "soap:Body")]+ pub body: T,+}++impl<T> EnvoyNotificationResponse<T> {+ pub fn new(body: T) -> Self {+ Self {+ soap: "http://schemas.xmlsoap.org/soap/envelope/".to_string(),+ xsd: "http://www.w3.org/2001/XMLSchema".to_string(),+ xsi: "http://www.w3.org/2001/XMLSchema-instance".to_string(),+ body,+ }+ }+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename = "PaymentOutNotificationResponse")]+pub struct PaymentOutNotificationResponse {+ #[serde(rename = "@xmlns")]+ pub xmlns: String,+ #[serde(rename = "PaymentOutNotificationResult")]+ pub result: EnvoyNotificationResult,+}++impl PaymentOutNotificationResponse {+ pub fn new(result: EnvoyNotificationResult) -> Self {+ Self {+ xmlns: "http://apilistener.envoyservices.com".to_string(),+ result,+ }+ }+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename = "PaymentOutReversalNotificationResponse")]+pub struct PaymentOutReversalNotificationResponse {+ #[serde(rename = "@xmlns")]+ pub xmlns: String,+ #[serde(rename = "PaymentOutReversalNotificationResult")]+ pub result: EnvoyNotificationResult,+}++impl PaymentOutReversalNotificationResponse {+ pub fn new(result: EnvoyNotificationResult) -> Self {+ Self {+ xmlns: "http://apilistener.envoyservices.com".to_string(),+ result,+ }+ }+}diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rsindex 21f504e507..b0a14534ee 100644--- a/crates/hyperswitch_domain_models/src/api.rs+++ b/crates/hyperswitch_domain_models/src/api.rs@@ -18,6 +18,7 @@ pub enum ApplicationResponse<R> {PaymentLinkForm(Box<PaymentLinkAction>),FileData((Vec<u8>, mime::Mime)),JsonWithHeaders((R, Vec<(String, hyperswitch_masking::Maskable<String>)>)),+ Xml(String),GenericLinkForm(Box<GenericLinks>),/// `response` contains the HTTP response sent back to the connector; `metadata` is consumed/// by `server_wrap_util` for the ApiEvent log.@@ -36,6 +37,7 @@ pub enum WebhookResponse<R> {TextPlain(String),FileData((Vec<u8>, mime::Mime)),JsonWithHeaders((R, Vec<(String, hyperswitch_masking::Maskable<String>)>)),+ Xml(String),}impl<R> From<WebhookResponse<R>> for ApplicationResponse<R> {@@ -46,6 +48,7 @@ impl<R> From<WebhookResponse<R>> for ApplicationResponse<R> {WebhookResponse::TextPlain(s) => Self::TextPlain(s),WebhookResponse::FileData((v, m)) => Self::FileData((v, m)),WebhookResponse::JsonWithHeaders((r, h)) => Self::JsonWithHeaders((r, h)),+ WebhookResponse::Xml(x) => Self::Xml(x),}}}@@ -71,6 +74,7 @@ impl<R> ApplicationResponse<R> {| Self::Form(_)| Self::PaymentLinkForm(_)| Self::FileData(_)+ | Self::Xml(_)| Self::GenericLinkForm(_)| Self::StatusOk => Err(common_utils::errors::ValidationError::InvalidValue {message: "expected either Json or JsonWithHeaders Response".to_string(),diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rsindex 637367d96a..33055cabfe 100644--- a/crates/router/src/compatibility/wrap.rs+++ b/crates/router/src/compatibility/wrap.rs@@ -115,6 +115,7 @@ where}Ok(api::ApplicationResponse::StatusOk) => api::http_response_ok(),Ok(api::ApplicationResponse::TextPlain(text)) => api::http_response_plaintext(text),+ Ok(api::ApplicationResponse::Xml(xml)) => api::http_response_xml(xml),Ok(api::ApplicationResponse::FileData((file_data, content_type))) => {api::http_response_file_data(file_data, content_type)}diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rsindex b3404812da..45122c4f55 100644--- a/crates/router/src/routes/metrics/request.rs+++ b/crates/router/src/routes/metrics/request.rs@@ -10,6 +10,7 @@ pub fn track_response_status_code<Q>(response: &ApplicationResponse<Q>) -> i64 {| ApplicationResponse::PaymentLinkForm(_)| ApplicationResponse::FileData(_)| ApplicationResponse::JsonWithHeaders(_)+ | ApplicationResponse::Xml(_)| ApplicationResponse::IncomingWebhookEvent { .. } => 200,ApplicationResponse::JsonForRedirection(_) => 302,}diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rsindex 114663d1b1..7ce5a11cf1 100644--- a/crates/router/src/services/api.rs+++ b/crates/router/src/services/api.rs@@ -498,6 +498,7 @@ where},Ok(ApplicationResponse::StatusOk) => http_response_ok(),Ok(ApplicationResponse::TextPlain(text)) => http_response_plaintext(text),+ Ok(ApplicationResponse::Xml(xml)) => http_response_xml(xml),Ok(ApplicationResponse::FileData((file_data, content_type))) => {http_response_file_data(file_data, content_type)}@@ -702,6 +703,10 @@ pub fn http_response_plaintext<T: body::MessageBody + 'static>(res: T) -> HttpReHttpResponse::Ok().content_type(mime::TEXT_PLAIN).body(res)}+pub fn http_response_xml<T: body::MessageBody + 'static>(res: T) -> HttpResponse {+ HttpResponse::Ok().content_type(mime::TEXT_XML).body(res)+}+pub fn http_response_file_data<T: body::MessageBody + 'static>(res: T,content_type: mime::Mime,diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rsindex 853baab8cb..d0ae8947fc 100644--- a/crates/router/src/workflows/outgoing_webhook_retry.rs+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs@@ -674,6 +674,7 @@ async fn get_outgoing_webhook_content_and_event_type(| ApplicationResponse::GenericLinkForm(_)| ApplicationResponse::PaymentLinkForm(_)| ApplicationResponse::FileData(_)+ | ApplicationResponse::Xml(_)| ApplicationResponse::IncomingWebhookEvent { .. } => {Err(errors::ProcessTrackerError::ResourceFetchingFailed {resource_name: tracking_data.primary_object_id.clone(),@@ -735,6 +736,7 @@ async fn get_outgoing_webhook_content_and_event_type(| ApplicationResponse::GenericLinkForm(_)| ApplicationResponse::PaymentLinkForm(_)| ApplicationResponse::FileData(_)+ | ApplicationResponse::Xml(_)| ApplicationResponse::IncomingWebhookEvent { .. } => {Err(errors::ProcessTrackerError::ResourceFetchingFailed {resource_name: tracking_data.primary_object_id.clone(),@@ -767,6 +769,7 @@ async fn get_outgoing_webhook_content_and_event_type(| ApplicationResponse::GenericLinkForm(_)| ApplicationResponse::PaymentLinkForm(_)| ApplicationResponse::FileData(_)+ | ApplicationResponse::Xml(_)| ApplicationResponse::IncomingWebhookEvent { .. } => {Err(errors::ProcessTrackerError::ResourceFetchingFailed {resource_name: tracking_data.primary_object_id.clone(),