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): [Gigadat] Add Payments Webhook (#9775)
awasthi210bc0c004ffab
diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat.rs b/crates/hyperswitch_connectors/src/connectors/gigadat.rsindex 33910dce4b..7ca6b9639a 100644--- a/crates/hyperswitch_connectors/src/connectors/gigadat.rs+++ b/crates/hyperswitch_connectors/src/connectors/gigadat.rs@@ -4,12 +4,13 @@ use base64::Engine;use common_enums::enums;use common_utils::{consts,+ crypto::Encryptable,errors::CustomResult,ext_traits::BytesExt,request::{Method, Request, RequestBuilder, RequestContent},types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},};-use error_stack::{report, ResultExt};+use error_stack::ResultExt;use hyperswitch_domain_models::{payment_method_data::PaymentMethodData,router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},@@ -55,6 +56,7 @@ use masking::{Mask, PeekInterface};#[cfg(feature = "payouts")]use router_env::{instrument, tracing};use transformers as gigadat;+use url::form_urlencoded;use uuid::Uuid;use crate::{constants::headers, types::ResponseRouterData, utils};@@ -832,27 +834,116 @@ impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Gigad}}+fn get_webhook_query_params(+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+) -> CustomResult<transformers::GigadatWebhookQueryParameters, errors::ConnectorError> {+ let query_string = &request.query_params;++ let (transaction, status) = query_string+ .split('&')+ .filter_map(|pair| pair.split_once('='))+ .fold((None, None), |(mut txn, mut sts), (key, value)| {+ match key {+ "transaction" => txn = Some(value.to_string()),+ "status" => {+ if let Ok(status) =+ transformers::GigadatPaymentStatus::try_from(value.to_string())+ {+ sts = Some(status);+ }+ }+ _ => {}+ }+ (txn, sts)+ });++ Ok(transformers::GigadatWebhookQueryParameters {+ transaction: transaction.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,+ status: status.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,+ })+}+#[async_trait::async_trait]impl webhooks::IncomingWebhook for Gigadat {fn get_webhook_object_reference_id(&self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))+ let query_params = get_webhook_query_params(request)?;+ let body_str = std::str::from_utf8(request.body)+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;++ let details: Vec<transformers::GigadatWebhookKeyValue> =+ form_urlencoded::parse(body_str.as_bytes())+ .map(|(key, value)| transformers::GigadatWebhookKeyValue {+ key: key.to_string(),+ value: value.to_string(),+ })+ .collect();++ let cpi_type_entry = details+ .iter()+ .find(|&entry| entry.key == "cpiType")+ .ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?;++ let reference_id = match cpi_type_entry.value.as_str() {+ #[cfg(feature = "payouts")]+ "ETO" | "RTO" | "RTX" | "ANR" | "ANX" => {+ api_models::webhooks::ObjectReferenceId::PayoutId(+ api_models::webhooks::PayoutIdType::ConnectorPayoutId(query_params.transaction),+ )+ }+ "ETI" | "RFM" => api_models::webhooks::ObjectReferenceId::PaymentId(+ api_models::payments::PaymentIdType::ConnectorTransactionId(+ query_params.transaction,+ ),+ ),+ _ => {+ return Err(errors::ConnectorError::NotImplemented(+ "Invalid transaction type ".to_string(),+ )+ .into())+ }+ };+ Ok(reference_id)}fn get_webhook_event_type(&self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))+ let query_params = get_webhook_query_params(request)?;+ let event_type = api_models::webhooks::IncomingWebhookEvent::from(query_params.status);+ Ok(event_type)}fn get_webhook_resource_object(&self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))+ let body_str = std::str::from_utf8(request.body)+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;++ let details: Vec<transformers::GigadatWebhookKeyValue> =+ form_urlencoded::parse(body_str.as_bytes())+ .map(|(key, value)| transformers::GigadatWebhookKeyValue {+ key: key.to_string(),+ value: value.to_string(),+ })+ .collect();+ let resource_object = serde_json::to_string(&details)+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;+ Ok(Box::new(resource_object))+ }+ 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: Encryptable<masking::Secret<serde_json::Value>>,+ _connector_label: &str,+ ) -> CustomResult<bool, errors::ConnectorError> {+ Ok(false)}}@@ -880,7 +971,18 @@ lazy_static! {connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,integration_status: enums::ConnectorIntegrationStatus::Sandbox,};- static ref GIGADAT_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();+ static ref GIGADAT_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = {+ #[cfg(feature = "payouts")]+ {+ let mut flows = vec![enums::EventClass::Payments];+ flows.push(enums::EventClass::Payouts);+ flows+ }+ #[cfg(not(feature = "payouts"))]+ {+ vec![enums::EventClass::Payments]+ }+ };}impl ConnectorSpecifications for Gigadat {diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rsindex a4bfc9c01a..2ef10458a3 100644--- a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs@@ -1,3 +1,4 @@+use api_models;use common_enums::{enums, Currency};use common_utils::{id_type,@@ -202,6 +203,39 @@ impl From<GigadatPaymentStatus> for enums::AttemptStatus {}}+impl From<GigadatPaymentStatus> for api_models::webhooks::IncomingWebhookEvent {+ fn from(item: GigadatPaymentStatus) -> Self {+ match item {+ GigadatPaymentStatus::StatusSuccess => Self::PaymentIntentSuccess,+ GigadatPaymentStatus::StatusFailed+ | GigadatPaymentStatus::StatusRejected+ | GigadatPaymentStatus::StatusRejected1+ | GigadatPaymentStatus::StatusExpired+ | GigadatPaymentStatus::StatusAborted1 => Self::PaymentIntentFailure,+ GigadatPaymentStatus::StatusInited | GigadatPaymentStatus::StatusPending => {+ Self::PaymentIntentProcessing+ }+ }+ }+}++impl TryFrom<String> for GigadatPaymentStatus {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(value: String) -> Result<Self, Self::Error> {+ match value.as_str() {+ "STATUS_INITED" => Ok(Self::StatusInited),+ "STATUS_SUCCESS" => Ok(Self::StatusSuccess),+ "STATUS_REJECTED" => Ok(Self::StatusRejected),+ "STATUS_REJECTED1" => Ok(Self::StatusRejected1),+ "STATUS_EXPIRED" => Ok(Self::StatusExpired),+ "STATUS_ABORTED1" => Ok(Self::StatusAborted1),+ "STATUS_PENDING" => Ok(Self::StatusPending),+ "STATUS_FAILED" => Ok(Self::StatusFailed),+ _ => Err(errors::ConnectorError::WebhookBodyDecodingFailed.into()),+ }+ }+}+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct GigadatTransactionStatusResponse {pub status: GigadatPaymentStatus,@@ -423,3 +457,15 @@ pub struct Error {pub code: Option<String>,pub detail: String,}++#[derive(Debug, Deserialize)]+pub struct GigadatWebhookQueryParameters {+ pub transaction: String,+ pub status: GigadatPaymentStatus,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct GigadatWebhookKeyValue {+ pub key: String,+ pub value: String,+}