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): [Trustpay] gracefully handle unknown response enum variants and missing optional fields (#13248)
Swangi Kumari41d28f2838e3
diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rsindex 0a0f37ec06..1fea4787dc 100644--- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs@@ -156,6 +156,22 @@ impl ConnectorCommon for Trustpay {res: Response,event_builder: Option<&mut ConnectorEvent>,) -> CustomResult<ErrorResponse, errors::ConnectorError> {+ if res.response.is_empty() {+ return Ok(ErrorResponse {+ status_code: res.status_code,+ code: consts::NO_ERROR_CODE.to_string(),+ message: consts::NO_ERROR_MESSAGE.to_string(),+ reason: None,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ });+ }+let response: Result<trustpay::TrustpayErrorResponse,Report<common_utils::errors::ParsingError>,@@ -338,28 +354,60 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>res: Response,event_builder: Option<&mut ConnectorEvent>,) -> CustomResult<ErrorResponse, errors::ConnectorError> {- let response: trustpay::TrustpayAccessTokenErrorResponse = res+ if res.response.is_empty() {+ return Ok(ErrorResponse {+ status_code: res.status_code,+ code: consts::NO_ERROR_CODE.to_string(),+ message: consts::NO_ERROR_MESSAGE.to_string(),+ reason: None,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ });+ }++ let response: Result<+ trustpay::TrustpayAccessTokenErrorResponse,+ Report<common_utils::errors::ParsingError>,+ > = res.response- .parse_struct("Trustpay AccessTokenErrorResponse")- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ .parse_struct("Trustpay AccessTokenErrorResponse");- event_builder.map(|i| i.set_response_body(&response));- router_env::logger::info!(connector_response=?response);+ match response {+ Ok(response) => {+ event_builder.map(|i| i.set_response_body(&response));+ router_env::logger::info!(connector_response=?response);- Ok(ErrorResponse {- status_code: res.status_code,- code: response.result_info.result_code.to_string(),- // message vary for the same code, so relying on code alone as it is unique- message: response.result_info.result_code.to_string(),- reason: response.result_info.additional_info,- attempt_status: None,- connector_transaction_id: None,- connector_response_reference_id: None,- network_advice_code: None,- network_decline_code: None,- network_error_message: None,- connector_metadata: None,- })+ Ok(ErrorResponse {+ status_code: res.status_code,+ code: response.result_info.result_code.to_string(),+ // message vary for the same code, so relying on code alone as it is unique+ message: response.result_info.result_code.to_string(),+ reason: response.result_info.additional_info,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ })+ }+ Err(error_msg) => {+ event_builder.map(|event| {+ event.set_error(serde_json::json!({+ "error": res.response.escape_ascii().to_string(),+ "status_code": res.status_code,+ }))+ });+ router_env::logger::error!(deserialization_error =? error_msg);+ utils::handle_json_response_deserialization_failure(res, "trustpay")+ }+ }}}@@ -1051,6 +1099,12 @@ impl webhooks::IncomingWebhook for Trustpay {))}}+ trustpay::CreditDebitIndicator::Unknown => Err(Report::new(+ errors::ConnectorError::WebhookReferenceIdNotFound,+ ))+ .attach_printable(+ "Unknown trustpay credit_debit_indicator received; cannot resolve object reference id",+ ),}}@@ -1059,6 +1113,10 @@ impl webhooks::IncomingWebhook for Trustpay {request: &webhooks::IncomingWebhookRequestDetails<'_>,_context: Option<&webhooks::WebhookContext>,) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {+ if request.body.is_empty() {+ return Ok(api_models::webhooks::IncomingWebhookEvent::EndpointVerification);+ }+let response: trustpay::TrustpayWebhookResponse = request.body.parse_struct("TrustpayWebhookResponse")@@ -1087,7 +1145,9 @@ impl webhooks::IncomingWebhook for Trustpay {}(- trustpay::CreditDebitIndicator::Dbit | trustpay::CreditDebitIndicator::Crdt,+ trustpay::CreditDebitIndicator::Dbit+ | trustpay::CreditDebitIndicator::Crdt+ | trustpay::CreditDebitIndicator::Unknown,trustpay::WebhookStatus::Unknown,) => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),(trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Refunded) => {@@ -1096,6 +1156,13 @@ impl webhooks::IncomingWebhook for Trustpay {(trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Chargebacked) => {Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)}+ (+ trustpay::CreditDebitIndicator::Unknown,+ trustpay::WebhookStatus::Paid+ | trustpay::WebhookStatus::Rejected+ | trustpay::WebhookStatus::Refunded+ | trustpay::WebhookStatus::Chargebacked,+ ) => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),}}@@ -1160,6 +1227,12 @@ impl webhooks::IncomingWebhook for Trustpay {.parse_struct("TrustpayWebhookResponse").switch()?;let payment_info = trustpay_response.payment_information;+ if matches!(payment_info.status, trustpay::WebhookStatus::Unknown) {+ return Err(Report::new(errors::ConnectorError::WebhookBodyDecodingFailed))+ .attach_printable(+ "Received unknown trustpay dispute status; cannot determine outcome without explicit mapping",+ );+ }let reason = payment_info.status_reason_information.unwrap_or_default();let connector_dispute_id = payment_info.referencesdiff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rsindex 0d9d2d15d0..eebd640bcc 100644--- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs@@ -95,6 +95,8 @@ pub enum TrustpayPaymentMethod {IDeal,Sofort,Blik,+ #[serde(other)]+ Unknown,}#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]@@ -420,7 +422,8 @@ fn get_debtor_info(TrustpayPaymentMethod::Eps| TrustpayPaymentMethod::Giropay| TrustpayPaymentMethod::IDeal- | TrustpayPaymentMethod::Sofort => None,+ | TrustpayPaymentMethod::Sofort+ | TrustpayPaymentMethod::Unknown => None,})}@@ -764,26 +767,46 @@ pub enum TrustpayBankRedirectPaymentStatus {Rejected,Authorizing,Pending,+ #[serde(other)]+ Unknown,}-impl From<TrustpayBankRedirectPaymentStatus> for enums::AttemptStatus {- fn from(item: TrustpayBankRedirectPaymentStatus) -> Self {- match item {- TrustpayBankRedirectPaymentStatus::Paid => Self::Charged,- TrustpayBankRedirectPaymentStatus::Rejected => Self::AuthorizationFailed,- TrustpayBankRedirectPaymentStatus::Authorized => Self::Authorized,- TrustpayBankRedirectPaymentStatus::Authorizing => Self::Authorizing,- TrustpayBankRedirectPaymentStatus::Pending => Self::Authorizing,+fn get_bank_redirect_attempt_status(+ item: TrustpayBankRedirectPaymentStatus,+ prev_status: enums::AttemptStatus,+) -> enums::AttemptStatus {+ match item {+ TrustpayBankRedirectPaymentStatus::Paid => enums::AttemptStatus::Charged,+ TrustpayBankRedirectPaymentStatus::Rejected => enums::AttemptStatus::AuthorizationFailed,+ TrustpayBankRedirectPaymentStatus::Authorized => enums::AttemptStatus::Authorized,+ TrustpayBankRedirectPaymentStatus::Authorizing => enums::AttemptStatus::Authorizing,+ TrustpayBankRedirectPaymentStatus::Pending => enums::AttemptStatus::Authorizing,+ TrustpayBankRedirectPaymentStatus::Unknown => {+ router_env::logger::warn!(+ "Unknown trustpay bank redirect payment status received; retaining previous status {:?}",+ prev_status+ );+ prev_status}}}-impl From<TrustpayBankRedirectPaymentStatus> for enums::RefundStatus {- fn from(item: TrustpayBankRedirectPaymentStatus) -> Self {- match item {- TrustpayBankRedirectPaymentStatus::Paid => Self::Success,- TrustpayBankRedirectPaymentStatus::Rejected => Self::Failure,- _ => Self::Pending,+fn get_bank_redirect_refund_status(+ item: TrustpayBankRedirectPaymentStatus,+ prev_status: enums::RefundStatus,+) -> enums::RefundStatus {+ match item {+ TrustpayBankRedirectPaymentStatus::Paid => enums::RefundStatus::Success,+ TrustpayBankRedirectPaymentStatus::Rejected => enums::RefundStatus::Failure,+ TrustpayBankRedirectPaymentStatus::Authorized+ | TrustpayBankRedirectPaymentStatus::Authorizing+ | TrustpayBankRedirectPaymentStatus::Pending => enums::RefundStatus::Pending,+ TrustpayBankRedirectPaymentStatus::Unknown => {+ router_env::logger::warn!(+ "Unknown trustpay bank redirect refund status received; retaining previous status {:?}",+ prev_status+ );+ prev_status}}}@@ -1003,6 +1026,7 @@ fn handle_bank_redirects_error_response(fn handle_bank_redirects_sync_response(response: SyncResponseBankRedirect,status_code: u16,+ previous_attempt_status: enums::AttemptStatus,) -> CustomResult<(enums::AttemptStatus,@@ -1012,7 +1036,10 @@ fn handle_bank_redirects_sync_response(),errors::ConnectorError,> {- let status = enums::AttemptStatus::from(response.payment_information.status);+ let status = get_bank_redirect_attempt_status(+ response.payment_information.status,+ previous_attempt_status,+ );let error = if utils::is_payment_failure(status) {let reason_info = response.payment_information@@ -1072,6 +1099,7 @@ fn handle_bank_redirects_sync_response(pub fn handle_webhook_response(payment_information: WebhookPaymentInformation,status_code: u16,+ previous_attempt_status: enums::AttemptStatus,) -> CustomResult<(enums::AttemptStatus,@@ -1081,7 +1109,8 @@ pub fn handle_webhook_response(),errors::ConnectorError,> {- let status = enums::AttemptStatus::try_from(payment_information.status.clone())?;+ let status =+ get_webhook_attempt_status(payment_information.status.clone(), previous_attempt_status)?;let error = if utils::is_payment_failure(status) {let reason_info = payment_information.status_reason_information@@ -1149,13 +1178,13 @@ pub fn get_trustpay_response(handle_bank_redirects_response(*response)}TrustpayPaymentsResponse::BankRedirectSync(response) => {- handle_bank_redirects_sync_response(*response, status_code)+ handle_bank_redirects_sync_response(*response, status_code, previous_attempt_status)}TrustpayPaymentsResponse::BankRedirectError(response) => {handle_bank_redirects_error_response(*response, status_code, previous_attempt_status)}TrustpayPaymentsResponse::WebhookResponse(response) => {- handle_webhook_response(*response, status_code)+ handle_webhook_response(*response, status_code, previous_attempt_status)}}}@@ -1770,8 +1799,9 @@ fn handle_cards_refund_response(fn handle_webhooks_refund_response(response: WebhookPaymentInformation,status_code: u16,+ previous_refund_status: enums::RefundStatus,) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> {- let refund_status = enums::RefundStatus::try_from(response.status)?;+ let refund_status = get_webhook_refund_status(response.status, previous_refund_status)?;let error = if utils::is_refund_failure(refund_status) {let reason_info = response.status_reason_information.unwrap_or_default();Some(ErrorResponse {@@ -1841,8 +1871,12 @@ fn handle_bank_redirects_refund_response(fn handle_bank_redirects_refund_sync_response(response: SyncResponseBankRedirect,status_code: u16,+ previous_refund_status: enums::RefundStatus,) -> (Option<ErrorResponse>, RefundsResponseData) {- let refund_status = enums::RefundStatus::from(response.payment_information.status);+ let refund_status = get_bank_redirect_refund_status(+ response.payment_information.status,+ previous_refund_status,+ );let error = if utils::is_refund_failure(refund_status) {let reason_info = response.payment_information@@ -1911,18 +1945,23 @@ fn handle_bank_redirects_refund_sync_error_response(impl<F> TryFrom<RefundsResponseRouterData<F, RefundResponse>> for RefundsRouterData<F> {type Error = Error;fn try_from(item: RefundsResponseRouterData<F, RefundResponse>) -> Result<Self, Self::Error> {+ let previous_refund_status = item.data.request.refund_status;let (error, response) = match item.response {RefundResponse::CardsRefund(response) => {handle_cards_refund_response(*response, item.http_code)?}RefundResponse::WebhookRefund(response) => {- handle_webhooks_refund_response(*response, item.http_code)?+ handle_webhooks_refund_response(*response, item.http_code, previous_refund_status)?}RefundResponse::BankRedirectRefund(response) => {handle_bank_redirects_refund_response(*response, item.http_code)}RefundResponse::BankRedirectRefundSyncResponse(response) => {- handle_bank_redirects_refund_sync_response(*response, item.http_code)+ handle_bank_redirects_refund_sync_response(+ *response,+ item.http_code,+ previous_refund_status,+ )}RefundResponse::BankRedirectError(response) => {handle_bank_redirects_refund_sync_error_response(*response, item.http_code)@@ -2030,6 +2069,8 @@ pub struct TrustpayErrorResponse {pub enum CreditDebitIndicator {Crdt,Dbit,+ #[serde(other)]+ Unknown,}#[derive(strum::Display, Debug, Clone, Serialize, Deserialize, PartialEq)]@@ -2042,26 +2083,42 @@ pub enum WebhookStatus {Unknown,}-impl TryFrom<WebhookStatus> for enums::AttemptStatus {- type Error = errors::ConnectorError;- fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> {- match item {- WebhookStatus::Paid => Ok(Self::Charged),- WebhookStatus::Rejected => Ok(Self::AuthorizationFailed),- _ => Err(errors::ConnectorError::WebhookEventTypeNotFound),+fn get_webhook_attempt_status(+ item: WebhookStatus,+ prev_status: enums::AttemptStatus,+) -> Result<enums::AttemptStatus, errors::ConnectorError> {+ match item {+ WebhookStatus::Paid => Ok(enums::AttemptStatus::Charged),+ WebhookStatus::Rejected => Ok(enums::AttemptStatus::AuthorizationFailed),+ WebhookStatus::Unknown => {+ router_env::logger::warn!(+ "Unknown trustpay webhook status received; retaining previous status {:?}",+ prev_status+ );+ Ok(prev_status)+ }+ WebhookStatus::Refunded | WebhookStatus::Chargebacked => {+ Err(errors::ConnectorError::WebhookEventTypeNotFound)}}}-impl TryFrom<WebhookStatus> for enums::RefundStatus {- type Error = errors::ConnectorError;- fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> {- match item {- WebhookStatus::Paid => Ok(Self::Success),- WebhookStatus::Refunded => Ok(Self::Success),- WebhookStatus::Rejected => Ok(Self::Failure),- _ => Err(errors::ConnectorError::WebhookEventTypeNotFound),+fn get_webhook_refund_status(+ item: WebhookStatus,+ prev_status: enums::RefundStatus,+) -> Result<enums::RefundStatus, errors::ConnectorError> {+ match item {+ WebhookStatus::Paid => Ok(enums::RefundStatus::Success),+ WebhookStatus::Refunded => Ok(enums::RefundStatus::Success),+ WebhookStatus::Rejected => Ok(enums::RefundStatus::Failure),+ WebhookStatus::Unknown => {+ router_env::logger::warn!(+ "Unknown trustpay webhook status received; retaining previous refund status {:?}",+ prev_status+ );+ Ok(prev_status)}+ WebhookStatus::Chargebacked => Err(errors::ConnectorError::WebhookEventTypeNotFound),}}