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
fix(connector): [GOCARDLESS] parse webhook action and links by resource_type (#14239)
Denis Ermakov5993ffeda21c
diff --git a/crates/hyperswitch_connectors/src/connectors/gocardless.rs b/crates/hyperswitch_connectors/src/connectors/gocardless.rsindex 6f41cff723..61956781ca 100644--- a/crates/hyperswitch_connectors/src/connectors/gocardless.rs+++ b/crates/hyperswitch_connectors/src/connectors/gocardless.rs@@ -765,21 +765,22 @@ impl IncomingWebhook for Gocardless {.events.first().ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?;- let reference_id = match &first_event.links {- transformers::WebhooksLink::PaymentWebhooksLink(link) => {+ let reference_id = match first_event {+ transformers::WebhookEvent::Payments(event) => {let payment_id = api_models::payments::PaymentIdType::ConnectorTransactionId(- link.payment.to_owned(),+ event.links.payment.to_owned(),);ObjectReferenceId::PaymentId(payment_id)}- transformers::WebhooksLink::RefundWebhookLink(link) => {- let refund_id =- api_models::webhooks::RefundIdType::ConnectorRefundId(link.refund.to_owned());+ transformers::WebhookEvent::Refunds(event) => {+ let refund_id = api_models::webhooks::RefundIdType::ConnectorRefundId(+ event.links.refund.to_owned(),+ );ObjectReferenceId::RefundId(refund_id)}- transformers::WebhooksLink::MandateWebhookLink(link) => {+ transformers::WebhookEvent::Mandates(event) => {let mandate_id = api_models::webhooks::MandateIdType::ConnectorMandateId(- link.mandate.to_owned(),+ event.links.mandate.to_owned(),);ObjectReferenceId::MandateId(mandate_id)}@@ -800,8 +801,8 @@ impl IncomingWebhook for Gocardless {.events.first().ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?;- let event_type = match &first_event.action {- transformers::WebhookAction::PaymentsAction(action) => match action {+ let event_type = match first_event {+ transformers::WebhookEvent::Payments(event) => match event.action {transformers::PaymentsAction::Created| transformers::PaymentsAction::Submitted| transformers::PaymentsAction::CustomerApprovalGranted => {@@ -817,18 +818,18 @@ impl IncomingWebhook for Gocardless {IncomingWebhookEvent::PaymentIntentSuccess}transformers::PaymentsAction::SurchargeFeeDebited- | transformers::PaymentsAction::ResubmissionRequired => {+ | transformers::PaymentsAction::ResubmissionRequested => {IncomingWebhookEvent::EventNotSupported}},- transformers::WebhookAction::RefundsAction(action) => match action {+ transformers::WebhookEvent::Refunds(event) => match event.action {transformers::RefundsAction::Failed => IncomingWebhookEvent::RefundFailure,transformers::RefundsAction::Paid => IncomingWebhookEvent::RefundSuccess,transformers::RefundsAction::RefundSettled| transformers::RefundsAction::FundsReturned| transformers::RefundsAction::Created => IncomingWebhookEvent::EventNotSupported,},- transformers::WebhookAction::MandatesAction(action) => match action {+ transformers::WebhookEvent::Mandates(event) => match event.action {transformers::MandatesAction::Active | transformers::MandatesAction::Reinstated => {IncomingWebhookEvent::MandateActive}@@ -863,12 +864,13 @@ impl IncomingWebhook for Gocardless {.first().ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?.clone();- match first_event.resource_type {- transformers::WebhookResourceType::Payments => Ok(Box::new(- gocardless::GocardlessPaymentsResponse::try_from(&first_event)?,+ match &first_event {+ transformers::WebhookEvent::Payments(event) => Ok(Box::new(+ gocardless::GocardlessPaymentsResponse::try_from(event)?,)),- transformers::WebhookResourceType::Refunds- | transformers::WebhookResourceType::Mandates => Ok(Box::new(first_event)),+ transformers::WebhookEvent::Refunds(_) | transformers::WebhookEvent::Mandates(_) => {+ Ok(Box::new(first_event))+ }}}}@@ -952,3 +954,112 @@ impl ConnectorSpecifications for Gocardless {api::ConnectorCustomerAction::CallConnectorCustomer}}++#[cfg(test)]+mod tests {+ use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId, RefundIdType};+ use hyperswitch_interfaces::webhooks::{IncomingWebhook, IncomingWebhookRequestDetails};++ use super::Gocardless;++ fn webhook_body(resource_type: &str, action: &str, link_key: &str) -> Vec<u8> {+ serde_json::json!({+ "events": [{+ "id": "EV000",+ "resource_type": resource_type,+ "action": action,+ "links": { link_key: "ID000" }+ }]+ })+ .to_string()+ .into_bytes()+ }++ fn event_type_for(resource_type: &str, action: &str, link_key: &str) -> IncomingWebhookEvent {+ let body = webhook_body(resource_type, action, link_key);+ let headers = actix_web::http::header::HeaderMap::new();+ let request = IncomingWebhookRequestDetails {+ method: http::Method::POST,+ uri: http::Uri::from_static("/webhooks"),+ headers: &headers,+ body: &body,+ query_params: String::new(),+ };+ Gocardless::new()+ .get_webhook_event_type(&request, None)+ .expect("webhook event type should be derived")+ }++ #[test]+ fn refund_actions_shared_with_payments_map_to_refund_events() {+ assert_eq!(+ event_type_for("refunds", "failed", "refund"),+ IncomingWebhookEvent::RefundFailure+ );+ assert_eq!(+ event_type_for("refunds", "created", "refund"),+ IncomingWebhookEvent::EventNotSupported+ );+ assert_eq!(+ event_type_for("refunds", "paid", "refund"),+ IncomingWebhookEvent::RefundSuccess+ );+ }++ #[test]+ fn mandate_actions_shared_with_payments_map_to_mandate_events() {+ assert_eq!(+ event_type_for("mandates", "cancelled", "mandate"),+ IncomingWebhookEvent::MandateRevoked+ );+ assert_eq!(+ event_type_for("mandates", "failed", "mandate"),+ IncomingWebhookEvent::MandateRevoked+ );+ for action in ["created", "submitted", "customer_approval_granted"] {+ assert_eq!(+ event_type_for("mandates", action, "mandate"),+ IncomingWebhookEvent::EventNotSupported,+ "mandate action `{action}`"+ );+ }+ }++ #[test]+ fn payment_actions_map_to_payment_events() {+ assert_eq!(+ event_type_for("payments", "failed", "payment"),+ IncomingWebhookEvent::PaymentIntentFailure+ );+ assert_eq!(+ event_type_for("payments", "confirmed", "payment"),+ IncomingWebhookEvent::PaymentIntentSuccess+ );+ assert_eq!(+ event_type_for("payments", "resubmission_requested", "payment"),+ IncomingWebhookEvent::EventNotSupported+ );+ }++ #[test]+ fn refund_webhook_references_the_refund() {+ let body = webhook_body("refunds", "failed", "refund");+ let headers = actix_web::http::header::HeaderMap::new();+ let request = IncomingWebhookRequestDetails {+ method: http::Method::POST,+ uri: http::Uri::from_static("/webhooks"),+ headers: &headers,+ body: &body,+ query_params: String::new(),+ };++ let reference_id = Gocardless::new()+ .get_webhook_object_reference_id(&request)+ .expect("webhook reference id should be derived");++ assert!(matches!(+ reference_id,+ ObjectReferenceId::RefundId(RefundIdType::ConnectorRefundId(ref id)) if id == "ID000"+ ));+ }+}diff --git a/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rsindex a17e93513c..58cb5315fa 100644--- a/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs@@ -836,27 +836,33 @@ pub struct GocardlessWebhookEvent {pub events: Vec<WebhookEvent>,}+/// `resource_type` decides how `action` and `links` are parsed. Action names such as+/// `created`, `failed` and `cancelled` are shared between resource types, so they cannot be+/// told apart on their own.#[derive(Clone, Debug, Serialize, Deserialize)]-pub struct WebhookEvent {- pub resource_type: WebhookResourceType,- pub action: WebhookAction,- pub links: WebhooksLink,+#[serde(tag = "resource_type", rename_all = "snake_case")]+pub enum WebhookEvent {+ Payments(PaymentWebhookEvent),+ Refunds(RefundWebhookEvent),+ Mandates(MandateWebhookEvent),}#[derive(Clone, Debug, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum WebhookResourceType {- Payments,- Refunds,- Mandates,+pub struct PaymentWebhookEvent {+ pub action: PaymentsAction,+ pub links: PaymentWebhooksLink,}#[derive(Clone, Debug, Serialize, Deserialize)]-#[serde(untagged)]-pub enum WebhookAction {- PaymentsAction(PaymentsAction),- RefundsAction(RefundsAction),- MandatesAction(MandatesAction),+pub struct RefundWebhookEvent {+ pub action: RefundsAction,+ pub links: RefundWebhookLink,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct MandateWebhookEvent {+ pub action: MandatesAction,+ pub links: MandateWebhookLink,}#[derive(Clone, Debug, Serialize, Deserialize)]@@ -872,7 +878,7 @@ pub enum PaymentsAction {SurchargeFeeDebited,Failed,Cancelled,- ResubmissionRequired,+ ResubmissionRequested,}#[derive(Clone, Debug, Serialize, Deserialize)]@@ -905,14 +911,6 @@ pub enum MandatesAction {Blocked,}-#[derive(Clone, Debug, Serialize, Deserialize)]-#[serde(untagged)]-pub enum WebhooksLink {- PaymentWebhooksLink(PaymentWebhooksLink),- RefundWebhookLink(RefundWebhookLink),- MandateWebhookLink(MandateWebhookLink),-}-#[derive(Clone, Debug, Serialize, Deserialize)]pub struct RefundWebhookLink {pub refund: String,@@ -928,45 +926,34 @@ pub struct MandateWebhookLink {pub mandate: String,}-impl TryFrom<&WebhookEvent> for GocardlessPaymentsResponse {+impl TryFrom<&PaymentWebhookEvent> for GocardlessPaymentsResponse {type Error = error_stack::Report<errors::ConnectorError>;- fn try_from(item: &WebhookEvent) -> Result<Self, Self::Error> {- let id = match &item.links {- WebhooksLink::PaymentWebhooksLink(link) => link.payment.to_owned(),- WebhooksLink::RefundWebhookLink(_) | WebhooksLink::MandateWebhookLink(_) => {- Err(errors::ConnectorError::WebhookEventTypeNotFound)?- }- };+ fn try_from(item: &PaymentWebhookEvent) -> Result<Self, Self::Error> {Ok(Self {payments: PaymentResponse {status: GocardlessPaymentStatus::try_from(&item.action)?,- id,+ id: item.links.payment.to_owned(),},})}}-impl TryFrom<&WebhookAction> for GocardlessPaymentStatus {+impl TryFrom<&PaymentsAction> for GocardlessPaymentStatus {type Error = error_stack::Report<errors::ConnectorError>;- fn try_from(item: &WebhookAction) -> Result<Self, Self::Error> {+ fn try_from(item: &PaymentsAction) -> Result<Self, Self::Error> {match item {- WebhookAction::PaymentsAction(action) => match action {- PaymentsAction::CustomerApprovalGranted | PaymentsAction::Submitted => {- Ok(Self::Submitted)- }- PaymentsAction::CustomerApprovalDenied => Ok(Self::CustomerApprovalDenied),- PaymentsAction::LateFailureSettled => Ok(Self::Failed),- PaymentsAction::Failed => Ok(Self::Failed),- PaymentsAction::Cancelled => Ok(Self::Cancelled),- PaymentsAction::Confirmed => Ok(Self::Confirmed),- PaymentsAction::PaidOut => Ok(Self::PaidOut),- PaymentsAction::SurchargeFeeDebited- | PaymentsAction::ResubmissionRequired- | PaymentsAction::Created => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,- },- WebhookAction::RefundsAction(_) | WebhookAction::MandatesAction(_) => {- Err(errors::ConnectorError::WebhookEventTypeNotFound)?+ PaymentsAction::CustomerApprovalGranted | PaymentsAction::Submitted => {+ Ok(Self::Submitted)}+ PaymentsAction::CustomerApprovalDenied => Ok(Self::CustomerApprovalDenied),+ PaymentsAction::LateFailureSettled => Ok(Self::Failed),+ PaymentsAction::Failed => Ok(Self::Failed),+ PaymentsAction::Cancelled => Ok(Self::Cancelled),+ PaymentsAction::Confirmed => Ok(Self::Confirmed),+ PaymentsAction::PaidOut => Ok(Self::PaidOut),+ PaymentsAction::SurchargeFeeDebited+ | PaymentsAction::ResubmissionRequested+ | PaymentsAction::Created => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,}}}