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(connector): [SQUARE] Implement webhooks (#1980)

DEEPANSHU BANSAL5a49802f56cd
diff --git a/crates/router/src/connector/square.rs b/crates/router/src/connector/square.rs
index 6a35a4b551..842c82b7b8 100644
--- a/crates/router/src/connector/square.rs
+++ b/crates/router/src/connector/square.rs
@@ -3,11 +3,13 @@ pub mod transformers;
use std::fmt::Debug;
use api_models::enums;
+use base64::Engine;
+use common_utils::ext_traits::ByteSliceExt;
use error_stack::{IntoReport, ResultExt};
use masking::PeekInterface;
use transformers as square;
-use super::utils::RefundsRequestData;
+use super::utils::{self as super_utils, RefundsRequestData};
use crate::{
configs::settings,
consts,
@@ -809,24 +811,93 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
#[async_trait::async_trait]
impl api::IncomingWebhook for Square {
- fn get_webhook_object_reference_id(
+ fn get_webhook_source_verification_algorithm(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn common_utils::crypto::VerifySignature + Send>, errors::ConnectorError>
+ {
+ Ok(Box::new(common_utils::crypto::HmacSha256))
+ }
+
+ fn get_webhook_source_verification_signature(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let encoded_signature =
+ super_utils::get_header_key_value("x-square-hmacsha256-signature", request.headers)?;
+ let signature = consts::BASE64_ENGINE
+ .decode(encoded_signature)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
+ Ok(signature)
+ }
+
+ fn get_webhook_source_verification_message(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ _merchant_id: &str,
+ _secret: &[u8],
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ Ok(format!("{}{}", request.uri, String::from_utf8_lossy(request.body)).into_bytes())
+ }
+
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
- Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ let webhook_body: square::SquareWebhookBody = request
+ .body
+ .parse_struct("SquareWebhookBody")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+
+ match webhook_body.data.object {
+ square::SquareWebhookObject::Payment(_) => {
+ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::ConnectorTransactionId(
+ webhook_body.data.id,
+ ),
+ ))
+ }
+ square::SquareWebhookObject::Refund(_) => {
+ Ok(api_models::webhooks::ObjectReferenceId::RefundId(
+ api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.data.id),
+ ))
+ }
+ }
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ let details: square::SquareWebhookBody = request
+ .body
+ .parse_struct("SquareWebhookEventType")
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
+ Ok(api::IncomingWebhookEvent::from(details.data.object))
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<serde_json::Value, errors::ConnectorError> {
- Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ let details: square::SquareWebhookBody =
+ request
+ .body
+ .parse_struct("SquareWebhookObject")
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
+ let reference_object = match details.data.object {
+ square::SquareWebhookObject::Payment(square_payments_response_details) => {
+ serde_json::to_value(square_payments_response_details)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?
+ }
+ square::SquareWebhookObject::Refund(square_refund_response_details) => {
+ serde_json::to_value(square_refund_response_details)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?
+ }
+ };
+ Ok(reference_object)
}
}
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 9340bd9fa4..76b8efb2d2 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -292,7 +292,7 @@ impl TryFrom<&types::ConnectorAuthType> for SquareAuthType {
}
}
// PaymentsResponse
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SquarePaymentStatus {
Completed,
@@ -314,7 +314,7 @@ impl From<SquarePaymentStatus> for enums::AttemptStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct SquarePaymentsResponseDetails {
status: SquarePaymentStatus,
id: String,
@@ -372,7 +372,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for SquareRefundRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Completed,
@@ -391,7 +391,7 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct SquareRefundResponseDetails {
status: RefundStatus,
id: String,
@@ -445,3 +445,43 @@ pub struct SquareErrorDetails {
pub struct SquareErrorResponse {
pub errors: Vec<SquareErrorDetails>,
}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SquareWebhookObject {
+ Payment(SquarePaymentsResponseDetails),
+ Refund(SquareRefundResponseDetails),
+}
+
+#[derive(Debug, Deserialize)]
+pub struct SquareWebhookData {
+ pub id: String,
+ pub object: SquareWebhookObject,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct SquareWebhookBody {
+ #[serde(rename = "type")]
+ pub webhook_type: String,
+ pub data: SquareWebhookData,
+}
+
+impl From<SquareWebhookObject> for api::IncomingWebhookEvent {
+ fn from(item: SquareWebhookObject) -> Self {
+ match item {
+ SquareWebhookObject::Payment(payment_data) => match payment_data.status {
+ SquarePaymentStatus::Completed => Self::PaymentIntentSuccess,
+ SquarePaymentStatus::Failed => Self::PaymentIntentFailure,
+ SquarePaymentStatus::Pending => Self::PaymentIntentProcessing,
+ SquarePaymentStatus::Approved | SquarePaymentStatus::Canceled => {
+ Self::EventNotSupported
+ }
+ },
+ SquareWebhookObject::Refund(refund_data) => match refund_data.status {
+ RefundStatus::Completed => Self::RefundSuccess,
+ RefundStatus::Failed | RefundStatus::Rejected => Self::RefundFailure,
+ RefundStatus::Pending => Self::EventNotSupported,
+ },
+ }
+ }
+}
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index b6baf10e91..1ca68b4094 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -728,6 +728,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>(
let connector = connector.connector;
let mut request_details = api::IncomingWebhookRequestDetails {
method: req.method().clone(),
+ uri: req.uri().clone(),
headers: req.headers(),
query_params: req.query_string().to_string(),
body: &body,
diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rs
index 1922852a1e..698353893f 100644
--- a/crates/router/src/types/api/webhooks.rs
+++ b/crates/router/src/types/api/webhooks.rs
@@ -18,6 +18,7 @@ use crate::{
pub struct IncomingWebhookRequestDetails<'a> {
pub method: actix_web::http::Method,
+ pub uri: actix_web::http::Uri,
pub headers: &'a actix_web::http::header::HeaderMap,
pub body: &'a [u8],
pub query_params: String,