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
refactor(connector): [Worldpayxml] webhooks body refactor and dispute webhooks implementation (#14109)
Swangi Kumari44d0045a3d59
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs b/crates/hyperswitch_connectors/src/connectors/worldpayxml.rsindex 7ea4c3a6f3..ba15f74e0e 100644--- a/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs+++ b/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs@@ -1396,24 +1396,23 @@ impl webhooks::IncomingWebhook for Worldpayxml {&self,request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {- let body_str = std::str::from_utf8(request.body)- .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;-- let body: worldpayxml::WorldpayFormWebhookBody = serde_urlencoded::from_str(body_str)- .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;- let order_code = body.order_code.clone();- if worldpayxml::is_refund_event(body.payment_status) {+ let body: worldpayxml::WorldpayXmlWebhookBody =+ utils::deserialize_xml_to_struct(request.body)?;+ let order_code = body.notify.order_status_event.order_code.clone();+ if worldpayxml::is_refund_event(body.notify.order_status_event.payment.last_event) {return Ok(api_models::webhooks::ObjectReferenceId::RefundId(api_models::webhooks::RefundIdType::ConnectorRefundId(order_code),));}- if worldpayxml::is_transaction_event(body.payment_status) {+ if worldpayxml::is_transaction_event(body.notify.order_status_event.payment.last_event)+ || worldpayxml::is_dispute_event(body.notify.order_status_event.payment.last_event)+ {return Ok(api_models::webhooks::ObjectReferenceId::PaymentId(api_models::payments::PaymentIdType::ConnectorTransactionId(order_code),));}#[cfg(feature = "payouts")]- if worldpayxml::is_payout_event(body.payment_status) {+ if worldpayxml::is_payout_event(body.notify.order_status_event.payment.last_event) {return Ok(api_models::webhooks::ObjectReferenceId::PayoutId(api_models::webhooks::PayoutIdType::ConnectorPayoutId(order_code),));@@ -1430,24 +1429,26 @@ impl webhooks::IncomingWebhook for Worldpayxml {return Ok(api_models::webhooks::IncomingWebhookEvent::EndpointVerification);}- let body_str = std::str::from_utf8(request.body)- .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;-- let webhook_body: worldpayxml::WorldpayFormWebhookBody =- serde_urlencoded::from_str(body_str)- .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;+ let body: worldpayxml::WorldpayXmlWebhookBody =+ utils::deserialize_xml_to_struct(request.body)?;#[cfg(feature = "payouts")]{- if worldpayxml::is_payout_event(webhook_body.payment_status) {+ if worldpayxml::is_payout_event(body.notify.order_status_event.payment.last_event) {return Ok(worldpayxml::get_payout_webhook_event(- webhook_body.payment_status,+ body.notify.order_status_event.payment.last_event,));}}+ if worldpayxml::is_dispute_event(body.notify.order_status_event.payment.last_event) {+ return Ok(worldpayxml::get_dispute_webhook_event(+ body.notify.order_status_event.payment.last_event,+ ));+ }+Ok(worldpayxml::get_payment_webhook_event(- webhook_body.payment_status,+ body.notify.order_status_event.payment.last_event,))}@@ -1456,14 +1457,23 @@ impl webhooks::IncomingWebhook for Worldpayxml {request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<Box<dyn hyperswitch_masking::ErasedMaskSerialize>, errors::ConnectorError>{- let body_str = std::str::from_utf8(request.body)- .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;-- let body: worldpayxml::WorldpayFormWebhookBody = serde_urlencoded::from_str(body_str)- .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;+ let body: worldpayxml::WorldpayXmlWebhookBody =+ utils::deserialize_xml_to_struct(request.body)?;Ok(Box::new(body))}++ fn get_dispute_details(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ _context: Option<&webhooks::WebhookContext>,+ ) -> CustomResult<hyperswitch_interfaces::disputes::DisputePayload, errors::ConnectorError>+ {+ let body: worldpayxml::WorldpayXmlWebhookBody =+ utils::deserialize_xml_to_struct(request.body)?;++ hyperswitch_interfaces::disputes::DisputePayload::try_from(&body)+ }}static WORLDPAYXML_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rsindex 5be991e78e..0113c04d98 100644--- a/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs@@ -38,7 +38,7 @@ use hyperswitch_domain_models::{PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,},};-use hyperswitch_interfaces::{consts, errors};+use hyperswitch_interfaces::{consts, disputes::DisputePayload, errors};use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use josekit;use serde::{Deserialize, Serialize};@@ -348,8 +348,9 @@ struct AuthorisationId {id: Option<Secret<String>>,}-#[derive(Debug, Clone, Copy, Deserialize, Serialize)]+#[derive(Debug, Clone, Copy, Deserialize, Serialize, strum::IntoStaticStr)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]pub enum LastEvent {Authorised,Refused,@@ -372,10 +373,20 @@ pub enum LastEvent {PushRequested,PushRefused,SettledByMerchant,+ ChargedBack,+ ChargebackReversed,#[serde(other)]Unknown,}+impl LastEvent {+ /// Renders the event as the raw Worldpay status string (SCREAMING_SNAKE_CASE),+ /// mirroring how it arrives on the wire, for use as a connector status.+ fn as_str(self) -> &'static str {+ self.into()+ }+}+#[derive(Debug, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]struct SchemeResponse {@@ -907,7 +918,7 @@ enum Action {#[derive(Debug, Serialize, Deserialize)]#[serde(untagged)]pub enum WorldpayxmlSyncResponse {- Webhook(Box<WorldpayFormWebhookBody>),+ Webhook(Box<WorldpayXmlWebhookBody>),Payment(Box<PaymentService>),}@@ -2351,28 +2362,25 @@ impl<F>}WorldpayxmlSyncResponse::Webhook(data) => {let is_auto_capture = item.data.request.is_auto_capture()?;+ let order_status_event = data.notify.order_status_event;let status = get_attempt_status(is_auto_capture,- data.payment_status,+ order_status_event.payment.last_event,Some(&item.data.status),)?;+ let response = process_payment_response(+ status,+ &order_status_event.payment,+ item.http_code,+ order_status_event.order_code.clone(),+ None,+ )+ .map_err(|err| *err);Ok(Self {status,- response: Ok(PaymentsResponseData::TransactionResponse {- resource_id: ResponseId::ConnectorTransactionId(data.order_code.clone()),- redirection_data: Box::new(None),- mandate_reference: Box::new(None),- connector_metadata: None,- network_txn_id: None,- network_txn_link_id: None,- connector_response_reference_id: Some(data.order_code.clone()),- incremental_authorization_allowed: None,- charges: None,- authentication_data: None,- payment_account_reference: None,- }),+ response,..item.data})}@@ -3481,11 +3489,19 @@ impl TryFrom<RefundsResponseRouterData<RSync, WorldpayxmlSyncResponse>>}}WorldpayxmlSyncResponse::Webhook(data) => {+ let payment_data = data.notify.order_status_event.payment;+let status =- get_refund_status(data.payment_status, item.data.request.refund_status)?;+ get_refund_status(payment_data.last_event, item.data.request.refund_status)?;let response = if connector_utils::is_refund_failure(status) {- let error_code = data.return_code;- let error_message = data.return_message;+ let error_code = payment_data+ .return_code+ .as_ref()+ .map(|code| code.code.clone());+ let error_message = payment_data+ .return_code+ .as_ref()+ .map(|code| code.description.clone());Err(ErrorResponse {code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()),@@ -3504,7 +3520,7 @@ impl TryFrom<RefundsResponseRouterData<RSync, WorldpayxmlSyncResponse>>})} else {Ok(RefundsResponseData {- connector_refund_id: data.order_code,+ connector_refund_id: data.notify.order_status_event.order_code,refund_status: status,})};@@ -4279,24 +4295,19 @@ pub fn map_purpose_code(value: Option<String>) -> Option<String> {}#[derive(Debug, Serialize, Deserialize)]-pub struct WorldpayFormWebhookBody {- #[serde(rename = "PaymentAmount")]- pub payment_amount: Option<StringMinorUnit>,-- #[serde(rename = "PaymentId")]- pub payment_id: Option<String>,-- #[serde(rename = "OrderCode")]- pub order_code: String,-- #[serde(rename = "PaymentStatus")]- pub payment_status: LastEvent,-- #[serde(rename = "ReturnCode")]- pub return_code: Option<String>,+#[serde(rename = "paymentService")]+pub struct WorldpayXmlWebhookBody {+ #[serde(rename = "@version")]+ pub version: String,+ #[serde(rename = "@merchantCode")]+ pub merchant_code: Secret<String>,+ pub notify: Notify,+}- #[serde(rename = "ReturnMessage")]- pub return_message: Option<String>,+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Notify {+ pub order_status_event: OrderStatusEvent,}#[derive(Debug, Serialize, Deserialize)]@@ -4375,6 +4386,50 @@ pub fn is_transaction_event(event_code: LastEvent) -> bool {)}+pub fn is_dispute_event(event_code: LastEvent) -> bool {+ matches!(+ event_code,+ LastEvent::ChargedBack | LastEvent::ChargebackReversed+ )+}++pub fn get_dispute_webhook_event(status: LastEvent) -> api_models::webhooks::IncomingWebhookEvent {+ match status {+ // A chargeback has been raised against the payment.+ LastEvent::ChargedBack => api_models::webhooks::IncomingWebhookEvent::DisputeOpened,+ // The chargeback was reversed in the merchant's favour.+ LastEvent::ChargebackReversed => api_models::webhooks::IncomingWebhookEvent::DisputeWon,+ _ => api_models::webhooks::IncomingWebhookEvent::EventNotSupported,+ }+}++impl TryFrom<&WorldpayXmlWebhookBody> for DisputePayload {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(body: &WorldpayXmlWebhookBody) -> Result<Self, Self::Error> {+ let order_status_event = &body.notify.order_status_event;+ let payment = &order_status_event.payment;+ let amount =+ payment+ .amount+ .as_ref()+ .ok_or(errors::ConnectorError::MissingRequiredField {+ field_name: "notify.orderStatusEvent.payment.amount".into(),+ })?;+ Ok(Self {+ amount: amount.value.clone(),+ currency: amount.currency_code,+ dispute_stage: enums::DisputeStage::Dispute,+ connector_dispute_id: order_status_event.order_code.clone(),+ connector_status: payment.last_event.as_str().to_string(),+ connector_reason: None,+ connector_reason_code: None,+ challenge_required_by: None,+ created_at: None,+ updated_at: None,+ })+ }+}+fn get_mandate_type(mit_category: Option<common_enums::MitCategory>) -> MandateType {match mit_category {Some(common_enums::MitCategory::Installment) => MandateType::Instalment,