Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat(connector): [Adyenplatform] add webhooks for payout #5749

Merged
merged 4 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 139 additions & 10 deletions crates/router/src/connector/adyenplatform.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
pub mod transformers;

use api_models::{self, webhooks::IncomingWebhookEvent};
#[cfg(feature = "payouts")]
use base64::Engine;
#[cfg(feature = "payouts")]
use common_utils::request::RequestContent;
#[cfg(feature = "payouts")]
use common_utils::types::MinorUnitForConnector;
#[cfg(feature = "payouts")]
use common_utils::types::{AmountConvertor, MinorUnit};
use error_stack::{report, ResultExt};
#[cfg(not(feature = "payouts"))]
use error_stack::report;
use error_stack::ResultExt;
#[cfg(feature = "payouts")]
use http::HeaderName;
#[cfg(feature = "payouts")]
use masking::Secret;
#[cfg(feature = "payouts")]
use ring::hmac;
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};

Expand All @@ -28,7 +38,12 @@ use crate::{
},
};
#[cfg(feature = "payouts")]
use crate::{events::connector_api_logs::ConnectorEvent, utils::BytesExt};
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
types::transformers::ForeignFrom,
utils::{crypto, ByteSliceExt, BytesExt},
};

#[derive(Clone)]
pub struct Adyenplatform {
Expand Down Expand Up @@ -294,24 +309,138 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun

#[async_trait::async_trait]
impl api::IncomingWebhook for Adyenplatform {
fn get_webhook_object_reference_id(
#[cfg(feature = "payouts")]
fn get_webhook_source_verification_algorithm(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}

#[cfg(feature = "payouts")]
fn get_webhook_source_verification_signature(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature = request
.headers
.get(HeaderName::from_static("hmacsignature"))
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(base64_signature.as_bytes().to_vec())
}

#[cfg(feature = "payouts")]
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
}

#[cfg(feature = "payouts")]
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

let raw_key = hex::decode(connector_webhook_secrets.secret)
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)?;

let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key);
let signed_messaged = hmac::sign(&signing_key, &message);
let payload_sign = consts::BASE64_ENGINE.encode(signed_messaged.as_ref());
Ok(payload_sign.as_bytes().eq(&signature))
}

fn get_webhook_object_reference_id(
&self,
#[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

Ok(api_models::webhooks::ObjectReferenceId::PayoutId(
api_models::webhooks::PayoutIdType::PayoutAttemptId(webhook_body.data.reference),
))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}

fn get_webhook_event_type(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
#[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

Ok(IncomingWebhookEvent::foreign_from((
webhook_body.webhook_type,
webhook_body.data.status,
webhook_body.data.tracking,
)))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}

fn get_webhook_resource_object(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
#[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(Box::new(webhook_body))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
}
106 changes: 103 additions & 3 deletions crates/router/src/connector/adyenplatform/transformers/payouts.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#[cfg(feature = "payouts")]
use api_models::webhooks;
use common_utils::pii;
use error_stack::{report, ResultExt};
use masking::Secret;
Expand All @@ -10,7 +12,7 @@ use crate::{
utils::{self, PayoutsData, RouterData},
},
core::errors,
types::{self, api::payouts, storage::enums},
types::{self, api::payouts, storage::enums, transformers::ForeignFrom},
};

#[derive(Debug, Default, Serialize, Deserialize)]
Expand Down Expand Up @@ -251,7 +253,7 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for Adye
category: AdyenPayoutMethod::try_from(payout_type)?,
counterparty,
priority: AdyenPayoutPriority::from(priority),
reference: request.payout_id.clone(),
reference: item.router_data.connector_request_reference_id.clone(),
reference_for_beneficiary: request.payout_id,
description: item.router_data.description.clone(),
})
Expand Down Expand Up @@ -286,7 +288,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenTransferResponse>>
impl From<AdyenTransferStatus> for enums::PayoutStatus {
fn from(adyen_status: AdyenTransferStatus) -> Self {
match adyen_status {
AdyenTransferStatus::Authorised => Self::Success,
AdyenTransferStatus::Authorised => Self::Initiated,
AdyenTransferStatus::Refused => Self::Ineligible,
AdyenTransferStatus::Error => Self::Failed,
}
Expand Down Expand Up @@ -336,6 +338,104 @@ impl TryFrom<enums::PayoutType> for AdyenPayoutMethod {
}
}

#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformIncomingWebhook {
pub data: AdyenplatformIncomingWebhookData,
#[serde(rename = "type")]
pub webhook_type: AdyenplatformWebhookEventType,
}

#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformIncomingWebhookData {
pub status: AdyenplatformWebhookStatus,
pub reference: String,
pub priority: AdyenPayoutPriority,
pub tracking: Option<AdyenplatformInstantStatus>,
}

#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformInstantStatus {
status: InstantPriorityStatus,
}

#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum InstantPriorityStatus {
Pending,
Credited,
}

#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
pub enum AdyenplatformWebhookEventType {
#[serde(rename = "balancePlatform.transfer.created")]
PayoutCreated,
#[serde(rename = "balancePlatform.transfer.updated")]
PayoutUpdated,
}

#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenplatformWebhookStatus {
Authorised,
Booked,
Pending,
Failed,
Returned,
Received,
}

#[cfg(feature = "payouts")]
impl
ForeignFrom<(
AdyenplatformWebhookEventType,
AdyenplatformWebhookStatus,
Option<AdyenplatformInstantStatus>,
)> for webhooks::IncomingWebhookEvent
{
fn foreign_from(
(event_type, status, instant_status): (
AdyenplatformWebhookEventType,
AdyenplatformWebhookStatus,
Option<AdyenplatformInstantStatus>,
),
) -> Self {
match (event_type, status, instant_status) {
(AdyenplatformWebhookEventType::PayoutCreated, _, _) => Self::PayoutCreated,
(
AdyenplatformWebhookEventType::PayoutUpdated,
_,
Some(AdyenplatformInstantStatus {
status: InstantPriorityStatus::Credited,
}),
) => Self::PayoutSuccess,
(
AdyenplatformWebhookEventType::PayoutUpdated,
_,
Some(AdyenplatformInstantStatus {
status: InstantPriorityStatus::Pending,
}),
) => Self::PayoutProcessing,
(AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status {
AdyenplatformWebhookStatus::Authorised
| AdyenplatformWebhookStatus::Booked
| AdyenplatformWebhookStatus::Received => Self::PayoutCreated,
AdyenplatformWebhookStatus::Pending => Self::PayoutProcessing,
AdyenplatformWebhookStatus::Failed => Self::PayoutFailure,
AdyenplatformWebhookStatus::Returned => Self::PayoutReversed,
},
}
}
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferErrorResponse {
Expand Down
Loading