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(coingate): Add Payment webhooks (#7489)
awasthi21fb8cba07012b
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.tomlindex 5cb4c952b6..9fadf1c298 100644--- a/crates/connector_configs/toml/development.toml+++ b/crates/connector_configs/toml/development.toml@@ -1205,8 +1205,9 @@ merchant_secret="Source verification key"[coingate][[coingate.crypto]]payment_method_type = "crypto_currency"-[coingate.connector_auth.HeaderKey]+[coingate.connector_auth.BodyKey]api_key="API Key"+key1 ="Merchant Token"[cryptopay][[cryptopay.crypto]]diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.tomlindex bd8d41a0eb..c1f5116bca 100644--- a/crates/connector_configs/toml/production.toml+++ b/crates/connector_configs/toml/production.toml@@ -1035,8 +1035,9 @@ merchant_secret="Source verification key"[coingate][[coingate.crypto]]payment_method_type = "crypto_currency"-[coingate.connector_auth.HeaderKey]+[coingate.connector_auth.BodyKey]api_key="API Key"+key1 ="Merchant Token"[cybersource]diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.tomlindex 5626defa4b..b5016ce42e 100644--- a/crates/connector_configs/toml/sandbox.toml+++ b/crates/connector_configs/toml/sandbox.toml@@ -1202,8 +1202,9 @@ merchant_secret="Source verification key"[coingate][[coingate.crypto]]payment_method_type = "crypto_currency"-[coingate.connector_auth.HeaderKey]+[coingate.connector_auth.BodyKey]api_key="API Key"+key1 ="Merchant Token"[cryptopay][[cryptopay.crypto]]diff --git a/crates/hyperswitch_connectors/src/connectors/coingate.rs b/crates/hyperswitch_connectors/src/connectors/coingate.rsindex e426dcb238..0423fe3bc7 100644--- a/crates/hyperswitch_connectors/src/connectors/coingate.rs+++ b/crates/hyperswitch_connectors/src/connectors/coingate.rs@@ -2,12 +2,13 @@ pub mod transformers;use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType};use common_utils::{+ crypto,errors::CustomResult,- ext_traits::BytesExt,+ ext_traits::{ByteSliceExt, BytesExt, ValueExt},request::{Method, Request, RequestBuilder, RequestContent},types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},};-use error_stack::{report, ResultExt};+use error_stack::ResultExt;use hyperswitch_domain_models::{router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},router_flow_types::{@@ -38,8 +39,8 @@ use hyperswitch_interfaces::{types::{self, Response},webhooks,};-use masking::{Mask, PeekInterface};-use transformers as coingate;+use masking::{ExposeInterface, Mask, PeekInterface};+use transformers::{self as coingate, CoingateWebhookBody};use crate::{constants::headers, types::ResponseRouterData, utils};@@ -298,7 +299,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coievent_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {- let response: coingate::CoingatePaymentsResponse = res+ let response: coingate::CoingateSyncResponse = res.response.parse_struct("coingate PaymentsSyncResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;@@ -398,25 +399,94 @@ impl ConnectorValidation for Coingate {#[async_trait::async_trait]impl webhooks::IncomingWebhook for Coingate {- fn get_webhook_object_reference_id(+ fn get_webhook_source_verification_algorithm(&self,_request: &webhooks::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {+ Ok(Box::new(crypto::HmacSha256))+ }++ fn get_webhook_source_verification_message(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ _merchant_id: &common_utils::id_type::MerchantId,+ _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {+ let message = std::str::from_utf8(request.body)+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;+ Ok(message.to_string().into_bytes())+ }++ fn get_webhook_object_reference_id(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))+ let notif: CoingateWebhookBody = request+ .body+ .parse_struct("CoingateWebhookBody")+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;+ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(+ api_models::payments::PaymentIdType::ConnectorTransactionId(notif.id.to_string()),+ ))}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 notif: CoingateWebhookBody = request+ .body+ .parse_struct("CoingateWebhookBody")+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;+ match notif.status {+ transformers::CoingatePaymentStatus::Pending => {+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)+ }+ transformers::CoingatePaymentStatus::Confirming+ | transformers::CoingatePaymentStatus::New => {+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)+ }+ transformers::CoingatePaymentStatus::Paid => {+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)+ }+ transformers::CoingatePaymentStatus::Invalid+ | transformers::CoingatePaymentStatus::Expired+ | transformers::CoingatePaymentStatus::Canceled => {+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)+ }+ }+ }+ 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: crypto::Encryptable<masking::Secret<serde_json::Value>>,+ _connector_label: &str,+ ) -> CustomResult<bool, errors::ConnectorError> {+ let connector_account_details: ConnectorAuthType = connector_account_details+ .parse_value::<ConnectorAuthType>("ConnectorAuthType")+ .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)?;+ let auth_type = coingate::CoingateAuthType::try_from(&connector_account_details)?;+ let secret_key = auth_type.merchant_token.expose();+ let request_body: CoingateWebhookBody = request+ .body+ .parse_struct("CoingateWebhookBody")+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;++ let token = request_body.token.expose();+ Ok(secret_key == token)}-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 notif: CoingateWebhookBody = request+ .body+ .parse_struct("CoingateWebhookBody")+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;++ Ok(Box::new(notif))}}diff --git a/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rsindex 77128580c2..348cf7478c 100644--- a/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs@@ -7,13 +7,16 @@ use hyperswitch_domain_models::{router_data::{ConnectorAuthType, RouterData},router_request_types::ResponseId,router_response_types::{PaymentsResponseData, RedirectForm},- types::PaymentsAuthorizeRouterData,+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},};use hyperswitch_interfaces::errors;use masking::Secret;use serde::{Deserialize, Serialize};-use crate::{types::ResponseRouterData, utils};+use crate::{+ types::{PaymentsSyncResponseRouterData, ResponseRouterData},+ utils::{self, PaymentsAuthorizeRequestData},+};pub struct CoingateRouterData<T> {pub amount: StringMajorUnit,@@ -34,10 +37,11 @@ pub struct CoingatePaymentsRequest {price_amount: StringMajorUnit,price_currency: Currency,receive_currency: String,- callback_url: Option<String>,+ callback_url: String,success_url: Option<String>,cancel_url: Option<String>,title: String,+ token: Secret<String>,}impl TryFrom<&CoingateRouterData<&PaymentsAuthorizeRouterData>> for CoingatePaymentsRequest {@@ -45,15 +49,17 @@ impl TryFrom<&CoingateRouterData<&PaymentsAuthorizeRouterData>> for CoingatePaymfn try_from(item: &CoingateRouterData<&PaymentsAuthorizeRouterData>,) -> Result<Self, Self::Error> {+ let auth = CoingateAuthType::try_from(&item.router_data.connector_auth_type)?;Ok(match item.router_data.request.payment_method_data {PaymentMethodData::Crypto(_) => Ok(Self {price_amount: item.amount.clone(),price_currency: item.router_data.request.currency,receive_currency: "DO_NOT_CONVERT".to_string(),- callback_url: item.router_data.request.router_return_url.clone(),+ callback_url: item.router_data.request.get_webhook_url()?,success_url: item.router_data.request.router_return_url.clone(),cancel_url: item.router_data.request.router_return_url.clone(),title: item.router_data.connector_request_reference_id.clone(),+ token: auth.merchant_token,}),_ => Err(errors::ConnectorError::NotImplemented(utils::get_unimplemented_payment_method_error_message("Coingate"),@@ -61,17 +67,44 @@ impl TryFrom<&CoingateRouterData<&PaymentsAuthorizeRouterData>> for CoingatePaym}?)}}-+#[derive(Debug, Serialize, Deserialize)]+pub struct CoingateSyncResponse {+ status: CoingatePaymentStatus,+ id: i64,+}+impl TryFrom<PaymentsSyncResponseRouterData<CoingateSyncResponse>> for PaymentsSyncRouterData {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(+ item: PaymentsSyncResponseRouterData<CoingateSyncResponse>,+ ) -> Result<Self, Self::Error> {+ Ok(Self {+ status: enums::AttemptStatus::from(item.response.status.clone()),+ response: Ok(PaymentsResponseData::TransactionResponse {+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),+ redirection_data: Box::new(None),+ mandate_reference: Box::new(None),+ connector_metadata: None,+ network_txn_id: None,+ connector_response_reference_id: None,+ incremental_authorization_allowed: None,+ charges: None,+ }),+ ..item.data+ })+ }+}pub struct CoingateAuthType {pub(super) api_key: Secret<String>,+ pub(super) merchant_token: Secret<String>,}impl TryFrom<&ConnectorAuthType> for CoingateAuthType {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {match auth_type {- ConnectorAuthType::HeaderKey { api_key } => Ok(Self {+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {api_key: api_key.to_owned(),+ merchant_token: key1.to_owned(),}),_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),}@@ -109,8 +142,8 @@ impl From<CoingatePaymentStatus> for common_enums::AttemptStatus {pub struct CoingatePaymentsResponse {status: CoingatePaymentStatus,id: i64,- payment_url: String,- order_id: String,+ payment_url: Option<String>,+ order_id: Option<String>,}impl<F, T> TryFrom<ResponseRouterData<F, CoingatePaymentsResponse, T, PaymentsResponseData>>@@ -125,14 +158,18 @@ impl<F, T> TryFrom<ResponseRouterData<F, CoingatePaymentsResponse, T, PaymentsReresponse: Ok(PaymentsResponseData::TransactionResponse {resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),redirection_data: Box::new(Some(RedirectForm::Form {- endpoint: item.response.payment_url.clone(),+ endpoint: item.response.payment_url.clone().ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "payment_url",+ },+ )?,method: Method::Get,form_fields: HashMap::new(),})),mandate_reference: Box::new(None),connector_metadata: None,network_txn_id: None,- connector_response_reference_id: Some(item.response.order_id.clone()),+ connector_response_reference_id: item.response.order_id.clone(),incremental_authorization_allowed: None,charges: None,}),@@ -146,3 +183,9 @@ pub struct CoingateErrorResponse {pub message: String,pub reason: String,}+#[derive(Debug, Serialize, Deserialize)]+pub struct CoingateWebhookBody {+ pub token: Secret<String>,+ pub status: CoingatePaymentStatus,+ pub id: i64,+}