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): [Nexixpay] gracefully handle unknown response enum variants and missing optional fields (#13266)
Swangi Kumari2772f74052df
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rsindex 1833dbc2f0..ac491b084f 100644--- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs@@ -169,64 +169,96 @@ impl ConnectorCommon for Nexixpay {res: Response,event_builder: Option<&mut ConnectorEvent>,) -> CustomResult<ErrorResponse, errors::ConnectorError> {- let response: nexixpay::NexixpayErrorResponse = match res.status_code {- 401 => nexixpay::NexixpayErrorResponse {+ let response: Result<+ nexixpay::NexixpayErrorResponse,+ error_stack::Report<common_utils::errors::ParsingError>,+ > = match res.status_code {+ // 401 / 404 have no useful body from Nexixpay — fabricate a canonical error.+ 401 => Ok(nexixpay::NexixpayErrorResponse {errors: vec![nexixpay::NexixpayErrorBody {code: Some(consts::NO_ERROR_CODE.to_string()),description: Some("UNAUTHORIZED".to_string()),}],- },- 404 => nexixpay::NexixpayErrorResponse {+ }),+ 404 => Ok(nexixpay::NexixpayErrorResponse {errors: vec![nexixpay::NexixpayErrorBody {code: Some(consts::NO_ERROR_CODE.to_string()),description: Some("NOT FOUND".to_string()),}],- },- _ => res- .response- .parse_struct("NexixpayErrorResponse")- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?,- };-- let concatenated_descriptions: Option<String> = {- let descriptions: Vec<String> = response- .errors- .iter()- .filter_map(|error| error.description.as_ref())- .cloned()- .collect();-- if descriptions.is_empty() {- None- } else {- Some(descriptions.join(", "))+ }),+ _ => {+ 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,+ });+ }+ res.response.parse_struct("NexixpayErrorResponse")}};- 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- .errors- .first()- .and_then(|error| error.code.clone())- .unwrap_or(consts::NO_ERROR_CODE.to_string()),- message: response- .errors- .first()- .and_then(|error| error.description.clone())- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),- reason: concatenated_descriptions,- 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,- })+ match response {+ Ok(response) => {+ let concatenated_descriptions: Option<String> = {+ let descriptions: Vec<String> = response+ .errors+ .iter()+ .filter_map(|error| error.description.as_ref())+ .cloned()+ .collect();++ if descriptions.is_empty() {+ None+ } else {+ Some(descriptions.join(", "))+ }+ };++ 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+ .errors+ .first()+ .and_then(|error| error.code.clone())+ .unwrap_or(consts::NO_ERROR_CODE.to_string()),+ message: response+ .errors+ .first()+ .and_then(|error| error.description.clone())+ .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),+ reason: concatenated_descriptions,+ 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, "nexixpay")+ }+ }}}@@ -860,6 +892,7 @@ fn get_payment_id(nexixpay::NexixpayPaymentIntent::Cancel => nexixpay_meta_data.cancel_operation_id,nexixpay::NexixpayPaymentIntent::Capture => nexixpay_meta_data.capture_operation_id,nexixpay::NexixpayPaymentIntent::Authorize => nexixpay_meta_data.authorization_operation_id,+ nexixpay::NexixpayPaymentIntent::Unknown => None,};payment_id.ok_or_else(|| {errors::ConnectorError::MissingRequiredField {diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rsindex f07dc0a35e..66dd6fe03c 100644--- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs@@ -368,9 +368,9 @@ pub struct NexixpayCompleteAuthorizeRequest {#[serde(rename_all = "camelCase")]pub struct OperationData {operation_id: String,- operation_currency: Currency,+ operation_currency: Option<Currency>,operation_result: NexixpayPaymentStatus,- operation_type: NexixpayOperationType,+ operation_type: Option<NexixpayOperationType>,order_id: String,}@@ -498,6 +498,8 @@ pub enum NexixpayPaymentIntent {Capture,Cancel,Authorize,+ #[serde(other)]+ Unknown,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -629,17 +631,17 @@ pub struct NexixpayRedirectionResponse {#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Operation {- additional_data: AdditionalData,+ additional_data: Option<AdditionalData>,channel: Option<Channel>,- customer_info: CustomerInfo,- operation_amount: StringMinorUnit,- operation_currency: Currency,+ customer_info: Option<CustomerInfo>,+ operation_amount: Option<StringMinorUnit>,+ operation_currency: Option<Currency>,operation_id: String,operation_result: NexixpayPaymentStatus,- operation_time: String,- operation_type: NexixpayOperationType,+ operation_time: Option<String>,+ operation_type: Option<NexixpayOperationType>,order_id: String,- payment_method: String,+ payment_method: Option<String>,warnings: Option<Vec<DetailedWarnings>>,}@@ -649,6 +651,8 @@ pub enum Channel {Ecommerce,Pos,Backoffice,+ #[serde(other)]+ Unknown,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -737,6 +741,7 @@ fn process_nexixpay_preprocessing_response(metadata: Option<Secret<serde_json::Value>>,is_auto_capture: bool,http_code: u16,+ prev_status: AttemptStatus,) -> Result<(AttemptStatus, Result<PaymentsResponseData, ErrorResponse>),error_stack::Report<errors::ConnectorError>,@@ -763,7 +768,8 @@ fn process_nexixpay_preprocessing_response(is_auto_capture,})?);- let status = AttemptStatus::from(response.operation.operation_result.clone());+ let status =+ get_payment_attempt_status(response.operation.operation_result.clone(), prev_status);let authentication_data = UcsAuthenticationData::foreign_try_from((&three_ds_data,response.operation.operation_id.clone(),@@ -800,12 +806,14 @@ impl TryFrom<PaymentsPreprocessingResponseRouterData<NexixpayRedirectionResponseitem: PaymentsPreprocessingResponseRouterData<NexixpayRedirectionResponse>,) -> Result<Self, Self::Error> {let is_auto_capture = item.data.request.is_auto_capture()?;+ let prev_status = item.data.status;let (status, response) = process_nexixpay_preprocessing_response(item.response,item.data.request.redirect_response.as_ref(),item.data.request.metadata.clone(),is_auto_capture,item.http_code,+ prev_status,)?;Ok(Self {@@ -824,12 +832,14 @@ impl TryFrom<PaymentsPostAuthenticateResponseRouterData<NexixpayRedirectionRespoitem: PaymentsPostAuthenticateResponseRouterData<NexixpayRedirectionResponse>,) -> Result<Self, Self::Error> {let is_auto_capture = item.data.request.is_auto_capture()?;+ let prev_status = item.data.status;let (status, response) = process_nexixpay_preprocessing_response(item.response,item.data.request.redirect_response.as_ref(),item.data.request.metadata.clone(),is_auto_capture,item.http_code,+ prev_status,)?;Ok(Self {@@ -1161,6 +1171,8 @@ pub enum NexixpayPaymentStatus {Voided,Refunded,Failed,+ #[serde(other)]+ Unknown,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -1174,12 +1186,16 @@ pub enum NexixpayOperationType {Noshow,Incremental,DelayCharge,+ #[serde(other)]+ Unknown,}#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]pub enum NexixpayRefundOperationType {Refund,+ #[serde(other)]+ Unknown,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -1190,6 +1206,8 @@ pub enum NexixpayRefundResultStatus {Refunded,Failed,Executed,+ #[serde(other)]+ Unknown,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -1198,16 +1216,16 @@ pub struct NexixpayTransactionResponse {order_id: String,operation_id: String,operation_result: NexixpayPaymentStatus,- operation_type: NexixpayOperationType,+ operation_type: Option<NexixpayOperationType>,}#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct NexixpayRSyncResponse {- order_id: String,+ order_id: Option<String>,operation_id: String,operation_result: NexixpayRefundResultStatus,- operation_type: NexixpayRefundOperationType,+ operation_type: Option<NexixpayRefundOperationType>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -1255,19 +1273,27 @@ pub struct NexixpayErrorResponse {pub errors: Vec<NexixpayErrorBody>,}-impl From<NexixpayPaymentStatus> for AttemptStatus {- fn from(item: NexixpayPaymentStatus) -> Self {- match item {- NexixpayPaymentStatus::Declined- | NexixpayPaymentStatus::DeniedByRisk- | NexixpayPaymentStatus::ThreedsFailed- | NexixpayPaymentStatus::Failed => Self::Failure,- NexixpayPaymentStatus::Authorized => Self::Authorized,- NexixpayPaymentStatus::ThreedsValidated => Self::AuthenticationSuccessful,- NexixpayPaymentStatus::Executed => Self::Charged,- NexixpayPaymentStatus::Pending => Self::AuthenticationPending, // this is being used in authorization calls only.- NexixpayPaymentStatus::Canceled | NexixpayPaymentStatus::Voided => Self::Voided,- NexixpayPaymentStatus::Refunded => Self::AutoRefunded,+fn get_payment_attempt_status(+ item: NexixpayPaymentStatus,+ prev_status: AttemptStatus,+) -> AttemptStatus {+ match item {+ NexixpayPaymentStatus::Declined+ | NexixpayPaymentStatus::DeniedByRisk+ | NexixpayPaymentStatus::ThreedsFailed+ | NexixpayPaymentStatus::Failed => AttemptStatus::Failure,+ NexixpayPaymentStatus::Authorized => AttemptStatus::Authorized,+ NexixpayPaymentStatus::ThreedsValidated => AttemptStatus::AuthenticationSuccessful,+ NexixpayPaymentStatus::Executed => AttemptStatus::Charged,+ NexixpayPaymentStatus::Pending => AttemptStatus::AuthenticationPending, // this is being used in authorization calls only.+ NexixpayPaymentStatus::Canceled | NexixpayPaymentStatus::Voided => AttemptStatus::Voided,+ NexixpayPaymentStatus::Refunded => AttemptStatus::AutoRefunded,+ NexixpayPaymentStatus::Unknown => {+ router_env::logger::warn!(+ "Unknown nexixpay payment status received; retaining previous status {:?}",+ prev_status+ );+ prev_status}}}@@ -1293,6 +1319,7 @@ impl TryFrom<PaymentsResponseRouterData<NexixpayPaymentsResponse>> for PaymentsAfn try_from(item: PaymentsResponseRouterData<NexixpayPaymentsResponse>,) -> Result<Self, Self::Error> {+ let prev_status = item.data.status;match item.response {NexixpayPaymentsResponse::PaymentResponse(ref response_body) => {let complete_authorize_url = item.data.request.get_complete_authorize_url()?;@@ -1335,7 +1362,10 @@ impl TryFrom<PaymentsResponseRouterData<NexixpayPaymentsResponse>> for PaymentsA} else {Box::new(None)};- let status = AttemptStatus::from(response_body.operation.operation_result.clone());+ let status = get_payment_attempt_status(+ response_body.operation.operation_result.clone(),+ prev_status,+ );match status {AttemptStatus::Failure => {let response = Err(get_error_response(@@ -1370,8 +1400,10 @@ impl TryFrom<PaymentsResponseRouterData<NexixpayPaymentsResponse>> for PaymentsA}}NexixpayPaymentsResponse::MandateResponse(ref mandate_response) => {- let status =- AttemptStatus::from(mandate_response.operation.operation_result.clone());+ let status = get_payment_attempt_status(+ mandate_response.operation.operation_result.clone(),+ prev_status,+ );let is_auto_capture = item.data.request.is_auto_capture()?;let operation_id = mandate_response.operation.operation_id.clone();let connector_metadata = Some(serde_json::json!(NexixpayConnectorMetaData {@@ -1432,6 +1464,7 @@ impl TryFrom<PaymentsPreAuthenticateResponseRouterData<NexixpayPaymentsResponse>fn try_from(item: PaymentsPreAuthenticateResponseRouterData<NexixpayPaymentsResponse>,) -> Result<Self, Self::Error> {+ let prev_status = item.data.status;match item.response {NexixpayPaymentsResponse::PaymentResponse(ref response_body) => {let complete_authorize_url =@@ -1461,7 +1494,10 @@ impl TryFrom<PaymentsPreAuthenticateResponseRouterData<NexixpayPaymentsResponse>}));// PreAuthenticate doesn't support mandateslet mandate_reference = Box::new(None);- let status = AttemptStatus::from(response_body.operation.operation_result.clone());+ let status = get_payment_attempt_status(+ response_body.operation.operation_result.clone(),+ prev_status,+ );match status {AttemptStatus::Failure => {let response = Err(get_error_response(@@ -1496,8 +1532,10 @@ impl TryFrom<PaymentsPreAuthenticateResponseRouterData<NexixpayPaymentsResponse>}}NexixpayPaymentsResponse::MandateResponse(ref mandate_response) => {- let status =- AttemptStatus::from(mandate_response.operation.operation_result.clone());+ let status = get_payment_attempt_status(+ mandate_response.operation.operation_result.clone(),+ prev_status,+ );let operation_id = mandate_response.operation.operation_id.clone();let connector_metadata = Some(serde_json::json!(NexixpayConnectorMetaData {three_d_s_auth_result: None,@@ -1569,14 +1607,19 @@ impl<F> TryFrom<&NexixpayRouterData<&RefundsRouterData<F>>> for NexixpayRefundRe}}-impl From<NexixpayRefundResultStatus> for RefundStatus {- fn from(item: NexixpayRefundResultStatus) -> Self {- match item {- NexixpayRefundResultStatus::Voided- | NexixpayRefundResultStatus::Refunded- | NexixpayRefundResultStatus::Executed => Self::Success,- NexixpayRefundResultStatus::Pending => Self::Pending,- NexixpayRefundResultStatus::Failed => Self::Failure,+fn get_refund_status(item: NexixpayRefundResultStatus, prev_status: RefundStatus) -> RefundStatus {+ match item {+ NexixpayRefundResultStatus::Voided+ | NexixpayRefundResultStatus::Refunded+ | NexixpayRefundResultStatus::Executed => RefundStatus::Success,+ NexixpayRefundResultStatus::Pending => RefundStatus::Pending,+ NexixpayRefundResultStatus::Failed => RefundStatus::Failure,+ NexixpayRefundResultStatus::Unknown => {+ router_env::logger::warn!(+ "Unknown nexixpay refund status received; retaining previous status {:?}",+ prev_status+ );+ prev_status}}}@@ -1601,10 +1644,14 @@ impl TryFrom<RefundsResponseRouterData<RSync, NexixpayRSyncResponse>> for Refundfn try_from(item: RefundsResponseRouterData<RSync, NexixpayRSyncResponse>,) -> Result<Self, Self::Error> {+ let prev_refund_status = item.data.request.refund_status;Ok(Self {response: Ok(RefundsResponseData {connector_refund_id: item.response.operation_id,- refund_status: RefundStatus::from(item.response.operation_result),+ refund_status: get_refund_status(+ item.response.operation_result,+ prev_refund_status,+ ),}),..item.data})@@ -1652,12 +1699,16 @@ impl<F>} else {Box::new(None)};+ let prev_status = item.data.status;let status = if item.data.request.amount == 0&& item.response.operation.operation_result == NexixpayPaymentStatus::Authorized{AttemptStatus::Charged} else {- AttemptStatus::from(item.response.operation.operation_result.clone())+ get_payment_attempt_status(+ item.response.operation.operation_result.clone(),+ prev_status,+ )};match status {AttemptStatus::Failure => {@@ -1842,7 +1893,9 @@ impl TryFrom<PaymentsSyncResponseRouterData<NexixpayTransactionResponse>>fn try_from(item: PaymentsSyncResponseRouterData<NexixpayTransactionResponse>,) -> Result<Self, Self::Error> {- let status = AttemptStatus::from(item.response.operation_result.clone());+ let prev_status = item.data.status;+ let status =+ get_payment_attempt_status(item.response.operation_result.clone(), prev_status);let mandate_reference = if item.data.request.is_mandate_payment() {Box::new(Some(MandateReference {connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(),@@ -2043,7 +2096,11 @@ implpsync_flow: NexixpayPaymentIntent::Authorize}));- let status = AttemptStatus::from(item.response.operation.operation_result.clone());+ let prev_status = item.data.status;+ let status = get_payment_attempt_status(+ item.response.operation.operation_result.clone(),+ prev_status,+ );match status {AttemptStatus::Failure => {let response = Err(get_error_response(