Skip to content

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

refactor(connector): [Paypal] gracefully handle unknown response enum variants and missing optional fields (#13240)

Swangi Kumarie0f0081e5f04
diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs
index f9de4d8aab..bc9b09524a 100644
--- a/crates/hyperswitch_connectors/src/connectors/paypal.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs
@@ -143,61 +143,91 @@ impl Paypal {
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
//Handled error response separately for Orders as the end point is different for Orders - (Authorize) and Payments - (Capture, void, refund, rsync).
//Error response have different fields for Orders and Payments.
- let response: paypal::PaypalOrderErrorResponse = res
- .response
- .parse_struct("Paypal ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ if res.response.is_empty() {
+ return Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: NO_ERROR_CODE.to_string(),
+ message: 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,
+ });
+ }
- event_builder.map(|i| i.set_error_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ let response: Result<
+ paypal::PaypalOrderErrorResponse,
+ error_stack::Report<common_utils::errors::ParsingError>,
+ > = res.response.parse_struct("Paypal ErrorResponse");
- let error_reason = response.details.clone().map(|order_errors| {
- order_errors
- .iter()
- .map(|error| {
- let mut reason = format!("description - {}", error.description);
- if let Some(value) = &error.value {
- reason.push_str(&format!(", value - {value}"));
- }
- if let Some(field) = error
- .field
- .as_ref()
- .and_then(|field| field.split('/').next_back())
- {
- reason.push_str(&format!(", field - {field}"));
- }
- reason.push(';');
- reason
+ match response {
+ Ok(response) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ let error_reason = response.details.clone().map(|order_errors| {
+ order_errors
+ .iter()
+ .map(|error| {
+ let mut reason = format!("description - {}", error.description);
+ if let Some(value) = &error.value {
+ reason.push_str(&format!(", value - {value}"));
+ }
+ if let Some(field) = error
+ .field
+ .as_ref()
+ .and_then(|field| field.split('/').next_back())
+ {
+ reason.push_str(&format!(", field - {field}"));
+ }
+ reason.push(';');
+ reason
+ })
+ .collect::<String>()
+ });
+ let errors_list = response.details.unwrap_or_default();
+ let option_error_code_message =
+ connector_utils::get_error_code_error_message_based_on_priority(
+ self.clone(),
+ errors_list
+ .into_iter()
+ .map(|errors| errors.into())
+ .collect(),
+ );
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: option_error_code_message
+ .clone()
+ .map(|error_code_message| error_code_message.error_code)
+ .unwrap_or(NO_ERROR_CODE.to_string()),
+ message: option_error_code_message
+ .map(|error_code_message| error_code_message.error_message)
+ .unwrap_or(NO_ERROR_MESSAGE.to_string()),
+ reason: error_reason.or(Some(response.message)),
+ attempt_status: None,
+ connector_transaction_id: response.debug_id,
+ connector_response_reference_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
})
- .collect::<String>()
- });
- let errors_list = response.details.unwrap_or_default();
- let option_error_code_message =
- connector_utils::get_error_code_error_message_based_on_priority(
- self.clone(),
- errors_list
- .into_iter()
- .map(|errors| errors.into())
- .collect(),
- );
- Ok(ErrorResponse {
- status_code: res.status_code,
- code: option_error_code_message
- .clone()
- .map(|error_code_message| error_code_message.error_code)
- .unwrap_or(NO_ERROR_CODE.to_string()),
- message: option_error_code_message
- .map(|error_code_message| error_code_message.error_message)
- .unwrap_or(NO_ERROR_MESSAGE.to_string()),
- reason: error_reason.or(Some(response.message)),
- attempt_status: None,
- connector_transaction_id: response.debug_id,
- 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);
+ connector_utils::handle_json_response_deserialization_failure(res, "paypal")
+ }
+ }
}
}
@@ -312,69 +342,99 @@ impl ConnectorCommon for Paypal {
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: paypal::PaypalPaymentErrorResponse = res
- .response
- .parse_struct("Paypal ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ if res.response.is_empty() {
+ return Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: NO_ERROR_CODE.to_string(),
+ message: 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,
+ });
+ }
- event_builder.map(|i| i.set_error_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ let response: Result<
+ paypal::PaypalPaymentErrorResponse,
+ error_stack::Report<common_utils::errors::ParsingError>,
+ > = res.response.parse_struct("Paypal ErrorResponse");
- let error_reason = response
- .details
- .clone()
- .map(|error_details| {
- error_details
- .iter()
- .try_fold(String::new(), |mut acc, error| {
- if let Some(description) = &error.description {
- write!(acc, "description - {description} ;")
- .change_context(
- errors::ConnectorError::ResponseDeserializationFailed,
- )
- .attach_printable("Failed to concatenate error details")
- .map(|_| acc)
- } else {
- Ok(acc)
- }
+ match response {
+ Ok(response) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ let error_reason = response
+ .details
+ .clone()
+ .map(|error_details| {
+ error_details
+ .iter()
+ .try_fold(String::new(), |mut acc, error| {
+ if let Some(description) = &error.description {
+ write!(acc, "description - {description} ;")
+ .change_context(
+ errors::ConnectorError::ResponseDeserializationFailed,
+ )
+ .attach_printable("Failed to concatenate error details")
+ .map(|_| acc)
+ } else {
+ Ok(acc)
+ }
+ })
})
- })
- .transpose()?;
- let reason = match error_reason {
- Some(err_reason) => err_reason
- .is_empty()
- .then(|| response.message.to_owned())
- .or(Some(err_reason)),
- None => Some(response.message.to_owned()),
- };
- let errors_list = response.details.unwrap_or_default();
- let option_error_code_message =
- connector_utils::get_error_code_error_message_based_on_priority(
- self.clone(),
- errors_list
- .into_iter()
- .map(|errors| errors.into())
- .collect(),
- );
-
- Ok(ErrorResponse {
- status_code: res.status_code,
- code: option_error_code_message
- .clone()
- .map(|error_code_message| error_code_message.error_code)
- .unwrap_or(NO_ERROR_CODE.to_string()),
- message: option_error_code_message
- .map(|error_code_message| error_code_message.error_message)
- .unwrap_or(NO_ERROR_MESSAGE.to_string()),
- reason,
- attempt_status: None,
- connector_transaction_id: response.debug_id,
- connector_response_reference_id: None,
- network_advice_code: None,
- network_decline_code: None,
- network_error_message: None,
- connector_metadata: None,
- })
+ .transpose()?;
+ let reason = match error_reason {
+ Some(err_reason) => err_reason
+ .is_empty()
+ .then(|| response.message.to_owned())
+ .or(Some(err_reason)),
+ None => Some(response.message.to_owned()),
+ };
+ let errors_list = response.details.unwrap_or_default();
+ let option_error_code_message =
+ connector_utils::get_error_code_error_message_based_on_priority(
+ self.clone(),
+ errors_list
+ .into_iter()
+ .map(|errors| errors.into())
+ .collect(),
+ );
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: option_error_code_message
+ .clone()
+ .map(|error_code_message| error_code_message.error_code)
+ .unwrap_or(NO_ERROR_CODE.to_string()),
+ message: option_error_code_message
+ .map(|error_code_message| error_code_message.error_message)
+ .unwrap_or(NO_ERROR_MESSAGE.to_string()),
+ reason,
+ attempt_status: None,
+ connector_transaction_id: response.debug_id,
+ 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);
+ connector_utils::handle_json_response_deserialization_failure(res, "paypal")
+ }
+ }
}
}
@@ -478,27 +538,57 @@ impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> fo
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: paypal::PaypalAccessTokenErrorResponse = res
- .response
- .parse_struct("Paypal AccessTokenErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ if res.response.is_empty() {
+ return Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: NO_ERROR_CODE.to_string(),
+ message: 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,
+ });
+ }
- event_builder.map(|i| i.set_error_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ let response: Result<
+ paypal::PaypalAccessTokenErrorResponse,
+ error_stack::Report<common_utils::errors::ParsingError>,
+ > = res.response.parse_struct("Paypal AccessTokenErrorResponse");
- Ok(ErrorResponse {
- status_code: res.status_code,
- code: response.error.clone(),
- message: response.error.clone(),
- reason: Some(response.error_description),
- 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) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.error.clone(),
+ message: response.error.clone(),
+ reason: Some(response.error_description),
+ 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);
+ connector_utils::handle_json_response_deserialization_failure(res, "paypal")
+ }
+ }
}
}
@@ -583,27 +673,57 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: paypal::PaypalAccessTokenErrorResponse = res
- .response
- .parse_struct("Paypal AccessTokenErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ if res.response.is_empty() {
+ return Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: NO_ERROR_CODE.to_string(),
+ message: 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,
+ });
+ }
- event_builder.map(|i| i.set_error_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ let response: Result<
+ paypal::PaypalAccessTokenErrorResponse,
+ error_stack::Report<common_utils::errors::ParsingError>,
+ > = res.response.parse_struct("Paypal AccessTokenErrorResponse");
- Ok(ErrorResponse {
- status_code: res.status_code,
- code: response.error.clone(),
- message: response.error.clone(),
- reason: Some(response.error_description),
- 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) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.error.clone(),
+ message: response.error.clone(),
+ reason: Some(response.error_description),
+ 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);
+ connector_utils::handle_json_response_deserialization_failure(res, "paypal")
+ }
+ }
}
}
@@ -1727,7 +1847,8 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pay
}
// only set when payment is done through card 3DS
//because no authorize or capture id is generated during payment authorize call for card 3DS
- transformers::PaypalPaymentIntent::Authenticate => {
+ transformers::PaypalPaymentIntent::Authenticate
+ | transformers::PaypalPaymentIntent::Unknown => {
format!(
"v2/checkout/orders/{}",
req.request
@@ -2284,6 +2405,10 @@ impl IncomingWebhook for Paypal {
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ if request.body.is_empty() {
+ return Ok(api_models::webhooks::IncomingWebhookEvent::EndpointVerification);
+ }
+
let payload: paypal::PaypalWebooksEventType = request
.body
.parse_struct("PaypalWebooksEventType")
@@ -2385,6 +2510,20 @@ impl IncomingWebhook for Paypal {
.attach_printable("Expected Dispute webhooks,but found other webhooks")?
}
transformers::PaypalResource::PaypalDisputeWebhooks(payload) => {
+ let connector_status = match payload.status {
+ transformers::DisputeStatus::Unknown => {
+ return Err(error_stack::Report::new(
+ errors::ConnectorError::WebhookBodyDecodingFailed,
+ ))
+ .attach_printable(
+ "Received unknown paypal dispute status; cannot determine outcome without explicit mapping",
+ );
+ }
+ ref known => known.to_string(),
+ };
+ let dispute_stage = api_models::enums::DisputeStage::try_from(
+ payload.dispute_life_cycle_stage.clone(),
+ )?;
let amt = connector_utils::convert_back_amount_to_minor_units(
self.amount_converter,
payload.dispute_amount.value,
@@ -2397,10 +2536,8 @@ impl IncomingWebhook for Paypal {
payload.dispute_amount.currency_code,
)?,
currency: payload.dispute_amount.currency_code,
- dispute_stage: api_models::enums::DisputeStage::from(
- payload.dispute_life_cycle_stage.clone(),
- ),
- connector_status: payload.status.to_string(),
+ dispute_stage,
+ connector_status,
connector_dispute_id: payload.dispute_id,
connector_reason: payload.reason.clone(),
connector_reason_code: payload.reason,
diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
index 4f0ab23e55..88178ee1c7 100644
--- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
@@ -157,6 +157,8 @@ pub enum PaypalPaymentIntent {
Capture,
Authorize,
Authenticate,
+ #[serde(other)]
+ Unknown,
}
#[derive(Default, Debug, Clone, Serialize, Eq, PartialEq, Deserialize)]
@@ -502,6 +504,8 @@ pub struct ContextStruct {
pub enum UserAction {
#[serde(rename = "PAY_NOW")]
PayNow,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -510,6 +514,8 @@ pub enum ShippingPreference {
SetProvidedAddress,
#[serde(rename = "GET_FROM_FILE")]
GetFromFile,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Serialize)]
@@ -575,11 +581,15 @@ pub struct CustomerId {
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum StoreInVault {
OnSuccess,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UsageType {
Merchant,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Serialize)]
@@ -1592,6 +1602,8 @@ pub struct PaypalAuthUpdateResponse {
#[serde(rename_all = "snake_case")]
pub enum PaypalAuthResponseType {
IdToken,
+ #[serde(other)]
+ Unknown,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaypalAuthUpdateResponse, T, AccessToken>>
@@ -1651,18 +1663,18 @@ pub struct PaypalExtendedAuthResponse {
#[derive(Debug, Deserialize, Serialize)]
pub struct PaypalIncrementalAuthResponse {
status: PaypalIncrementalStatus,
- status_details: PaypalIncrementalAuthStatusDetails,
+ status_details: Option<PaypalIncrementalAuthStatusDetails>,
id: String,
- invoice_id: String,
- custom_id: String,
- links: Vec<PaypalLinks>,
- amount: OrderAmount,
- network_transaction_reference: PaypalNetworkTransactionReference,
- expiration_time: String,
- create_time: String,
- update_time: String,
- supplementary_data: PaypalSupplementaryData,
- payee: Payee,
+ invoice_id: Option<String>,
+ custom_id: Option<String>,
+ links: Option<Vec<PaypalLinks>>,
+ amount: Option<OrderAmount>,
+ network_transaction_reference: Option<PaypalNetworkTransactionReference>,
+ expiration_time: Option<String>,
+ create_time: Option<String>,
+ update_time: Option<String>,
+ supplementary_data: Option<PaypalSupplementaryData>,
+ payee: Option<Payee>,
name: Option<String>,
message: Option<String>,
}
@@ -1676,6 +1688,8 @@ pub enum PaypalIncrementalStatus {
PARTIALLYCAPTURED,
VOIDED,
PENDING,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -1687,6 +1701,8 @@ pub enum PaypalExtendedAuthorizationStatus {
PartiallyCaptured,
Voided,
Pending,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Deserialize, Serialize)]
@@ -1704,40 +1720,52 @@ pub struct PaypalIncrementalAuthStatusDetails {
pub enum PaypalStatusPendingReason {
PENDINGREVIEW,
DECLINEDBYRISKFRAUDFILTERS,
+ #[serde(other)]
+ Unknown,
}
-impl From<PaypalIncrementalStatus> for common_enums::AuthorizationStatus {
- fn from(item: PaypalIncrementalStatus) -> Self {
- match item {
- PaypalIncrementalStatus::CREATED
- | PaypalIncrementalStatus::CAPTURED
- | PaypalIncrementalStatus::PARTIALLYCAPTURED => Self::Success,
- PaypalIncrementalStatus::PENDING => Self::Processing,
- PaypalIncrementalStatus::DENIED | PaypalIncrementalStatus::VOIDED => Self::Failure,
+fn get_incremental_authorization_status(
+ item: PaypalIncrementalStatus,
+ prev_status: common_enums::AuthorizationStatus,
+) -> common_enums::AuthorizationStatus {
+ match item {
+ PaypalIncrementalStatus::CREATED
+ | PaypalIncrementalStatus::CAPTURED
+ | PaypalIncrementalStatus::PARTIALLYCAPTURED => common_enums::AuthorizationStatus::Success,
+ PaypalIncrementalStatus::PENDING => common_enums::AuthorizationStatus::Processing,
+ PaypalIncrementalStatus::DENIED | PaypalIncrementalStatus::VOIDED => {
+ common_enums::AuthorizationStatus::Failure
+ }
+ PaypalIncrementalStatus::Unknown => {
+ router_env::logger::warn!(
+ "Unknown paypal incremental authorization status received; retaining previous status {:?}",
+ prev_status
+ );
+ prev_status
}
}
}
-impl From<PaypalIncrementalStatus> for common_enums::AttemptStatus {
- fn from(item: PaypalIncrementalStatus) -> Self {
- match item {
- PaypalIncrementalStatus::CREATED
- | PaypalIncrementalStatus::CAPTURED
- | PaypalIncrementalStatus::PARTIALLYCAPTURED => Self::Authorized,
- PaypalIncrementalStatus::PENDING => Self::Pending,
- PaypalIncrementalStatus::DENIED | PaypalIncrementalStatus::VOIDED => Self::Failure,
+fn get_extended_auth_attempt_status(
+ item: PaypalExtendedAuthorizationStatus,
+ prev_status: common_enums::AttemptStatus,
+) -> common_enums::AttemptStatus {
+ match item {
+ PaypalExtendedAuthorizationStatus::Created
+ | PaypalExtendedAuthorizationStatus::Captured
+ | PaypalExtendedAuthorizationStatus::PartiallyCaptured => {
+ common_enums::AttemptStatus::Authorized
}
- }
-}
-impl From<PaypalExtendedAuthorizationStatus> for common_enums::AttemptStatus {
- fn from(item: PaypalExtendedAuthorizationStatus) -> Self {
- match item {
- PaypalExtendedAuthorizationStatus::Created
- | PaypalExtendedAuthorizationStatus::Captured
- | PaypalExtendedAuthorizationStatus::PartiallyCaptured => Self::Authorized,
- PaypalExtendedAuthorizationStatus::Pending => Self::Pending,
- PaypalExtendedAuthorizationStatus::Denied
- | PaypalExtendedAuthorizationStatus::Voided => Self::Failure,
+ PaypalExtendedAuthorizationStatus::Pending => common_enums::AttemptStatus::Pending,
+ PaypalExtendedAuthorizationStatus::Denied | PaypalExtendedAuthorizationStatus::Voided => {
+ common_enums::AttemptStatus::Failure
+ }
+ PaypalExtendedAuthorizationStatus::Unknown => {
+ router_env::logger::warn!(
+ "Unknown paypal extended authorization status received; retaining previous status {:?}",
+ prev_status
+ );
+ prev_status
}
}
}
@@ -1751,7 +1779,9 @@ fn is_extend_authorization_applied(
| PaypalExtendedAuthorizationStatus::PartiallyCaptured => {
Some(common_types::primitive_wrappers::ExtendedAuthorizationAppliedBool::from(true))
}
- PaypalExtendedAuthorizationStatus::Pending => None,
+ PaypalExtendedAuthorizationStatus::Pending | PaypalExtendedAuthorizationStatus::Unknown => {
+ None
+ }
PaypalExtendedAuthorizationStatus::Denied | PaypalExtendedAuthorizationStatus::Voided => {
Some(common_types::primitive_wrappers::ExtendedAuthorizationAppliedBool::from(false))
}
@@ -1777,7 +1807,10 @@ impl<F>
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = common_enums::AuthorizationStatus::from(item.response.status);
+ let status = get_incremental_authorization_status(
+ item.response.status,
+ common_enums::AuthorizationStatus::Unresolved,
+ );
Ok(Self {
response: Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
status,
@@ -1812,7 +1845,8 @@ impl TryFrom<PaymentsExtendAuthorizationResponseRouterData<PaypalExtendedAuthRes
None,
));
- let status = common_enums::AttemptStatus::from(item.response.status.clone());
+ let status =
+ get_extended_auth_attempt_status(item.response.status.clone(), item.data.status);
let response = if is_payment_failure(status) {
let reason = item
.response
@@ -1964,11 +1998,14 @@ pub enum PaypalOrderStatus {
Saved,
PayerActionRequired,
Approved,
+ #[serde(other)]
+ Unknown,
}
pub(crate) fn get_order_status(
item: PaypalOrderStatus,
intent: PaypalPaymentIntent,
+ prev_status: storage_enums::AttemptStatus,
) -> storage_enums::AttemptStatus {
match item {
PaypalOrderStatus::Completed => {
@@ -1986,6 +2023,13 @@ pub(crate) fn get_order_status(
PaypalOrderStatus::PayerActionRequired => {
storage_enums::AttemptStatus::AuthenticationPending
}
+ PaypalOrderStatus::Unknown => {
+ router_env::logger::warn!(
+ "Unknown paypal order status received; retaining previous status {:?}",
+ prev_status
+ );
+ prev_status
+ }
}
}
@@ -2187,6 +2231,7 @@ pub struct ThreeDsCheck {
pub enum LiabilityShift {
Possible,
No,
+ #[serde(other)]
Unknown,
}
@@ -2201,6 +2246,8 @@ pub enum EnrollmentStatus {
Unavailable,
#[serde(rename = "B")]
Bypassed,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -2222,6 +2269,8 @@ pub enum AuthenticationStatus {
InfoOnly,
#[serde(rename = "D")]
Decoupled,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -2342,7 +2391,7 @@ fn get_id_based_on_intent(
.next()?
.id,
),
- PaypalPaymentIntent::Authenticate => None,
+ PaypalPaymentIntent::Authenticate | PaypalPaymentIntent::Unknown => None,
}
}()
.ok_or_else(|| errors::ConnectorError::MissingConnectorTransactionID.into())
@@ -2402,7 +2451,7 @@ where
ResponseId::ConnectorTransactionId(item.response.id.clone()),
),
- PaypalPaymentIntent::Authenticate => {
+ PaypalPaymentIntent::Authenticate | PaypalPaymentIntent::Unknown => {
Err(errors::ConnectorError::ResponseDeserializationFailed)?
}
};
@@ -2428,7 +2477,7 @@ where
// top-level order `status`, which PayPal may omit (e.g. a declined capture). For example a
// `DECLINED` capture maps to `AttemptStatus::Failure` and is handled by the branch below.
let status = payment_collection_item.status.clone();
- let status = storage_enums::AttemptStatus::from(status);
+ let status = get_payment_attempt_status(status, item.data.status);
if is_payment_failure(status) {
let error_code = payment_collection_item
@@ -2595,7 +2644,11 @@ impl<F, T>
Option<common_enums::PaymentExperience>,
),
) -> Result<Self, Self::Error> {
- let status = get_order_status(item.response.clone().status, item.response.intent.clone());
+ let status = get_order_status(
+ item.response.clone().status,
+ item.response.intent.clone(),
+ item.data.status,
+ );
let link = get_redirect_url(item.response.links.clone())?;
// For Paypal SDK flow, we need to trigger SDK client and then complete authorize
@@ -2661,7 +2714,11 @@ impl
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = get_order_status(item.response.clone().status, item.response.intent.clone());
+ let status = get_order_status(
+ item.response.clone().status,
+ item.response.intent.clone(),
+ item.data.status,
+ );
let link = get_redirect_url(item.response.links.clone())?;
let connector_meta = serde_json::json!(PaypalMeta {
@@ -2717,7 +2774,11 @@ impl
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = get_order_status(item.response.clone().status, item.response.intent.clone());
+ let status = get_order_status(
+ item.response.clone().status,
+ item.response.intent.clone(),
+ item.data.status,
+ );
// For Paypal SDK flow, we need to trigger SDK client and then Confirm
let next_action = Some(NextActionCall::Confirm);
@@ -2793,6 +2854,7 @@ impl TryFrom<PaymentsResponseRouterData<PaypalThreeDsResponse>> for PaymentsAuth
let status = get_order_status(
item.response.clone().status,
PaypalPaymentIntent::Authenticate,
+ item.data.status,
);
let link = get_redirect_url(item.response.links.clone())?;
@@ -2853,8 +2915,9 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaypalPaymentsSyncResponse, T, Payments
fn try_from(
item: ResponseRouterData<F, PaypalPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
+ let prev_status = item.data.status;
Ok(Self {
- status: storage_enums::AttemptStatus::from(item.response.status),
+ status: get_payment_attempt_status(item.response.status, prev_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response
@@ -3079,21 +3142,31 @@ pub enum PaypalFulfillStatus {
Failed,
Refunded,
Returned,
+ #[serde(other)]
+ Unknown,
}
#[cfg(feature = "payouts")]
-pub(crate) fn get_payout_status(status: PaypalFulfillStatus) -> storage_enums::PayoutStatus {
+pub(crate) fn get_payout_status(
+ status: PaypalFulfillStatus,
+) -> Option<storage_enums::PayoutStatus> {
match status {
- PaypalFulfillStatus::Success => storage_enums::PayoutStatus::Success,
+ PaypalFulfillStatus::Success => Some(storage_enums::PayoutStatus::Success),
PaypalFulfillStatus::Denied | PaypalFulfillStatus::Failed => {
- storage_enums::PayoutStatus::Failed
+ Some(storage_enums::PayoutStatus::Failed)
}
- PaypalFulfillStatus::Cancelled => storage_enums::PayoutStatus::Cancelled,
+ PaypalFulfillStatus::Cancelled => Some(storage_enums::PayoutStatus::Cancelled),
PaypalFulfillStatus::Pending | PaypalFulfillStatus::Processing => {
- storage_enums::PayoutStatus::Pending
+ Some(storage_enums::PayoutStatus::Pending)
}
PaypalFulfillStatus::Refunded | PaypalFulfillStatus::Returned => {
- storage_enums::PayoutStatus::Reversed
+ Some(storage_enums::PayoutStatus::Reversed)
+ }
+ PaypalFulfillStatus::Unknown => {
+ router_env::logger::warn!(
+ "Unknown paypal payout status received; retaining previous payout status"
+ );
+ None
}
}
}
@@ -3106,7 +3179,7 @@ impl<F> TryFrom<PayoutsResponseRouterData<F, PaypalFulfillResponse>> for Payouts
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
- status: Some(get_payout_status(item.response.batch_header.batch_status)),
+ status: get_payout_status(item.response.batch_header.batch_status),
connector_payout_id: Some(item.response.batch_header.payout_batch_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
@@ -3127,7 +3200,7 @@ impl<F> TryFrom<PayoutsResponseRouterData<F, PaypalPayoutSyncResponse>> for Payo
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
- status: Some(get_payout_status(item.response.batch_header.batch_status)),
+ status: get_payout_status(item.response.batch_header.batch_status),
connector_payout_id: item.response.batch_header.payout_batch_id,
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
@@ -3205,6 +3278,8 @@ pub enum PaypalPaymentStatus {
Expired,
PartiallyCaptured,
Refunded,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -3213,7 +3288,7 @@ pub struct PaypalCaptureResponse {
status: PaypalPaymentStatus,
amount: Option<OrderAmount>,
invoice_id: Option<String>,
- final_capture: bool,
+ final_capture: Option<bool>,
payment_source: Option<PaymentSourceItemResponse>,
payer: Option<Payer>,
}
@@ -3223,19 +3298,29 @@ pub struct Payer {
payer_id: Option<Secret<String>>,
}
-impl From<PaypalPaymentStatus> for storage_enums::AttemptStatus {
- fn from(item: PaypalPaymentStatus) -> Self {
- match item {
- PaypalPaymentStatus::Created => Self::Authorized,
- PaypalPaymentStatus::Completed
- | PaypalPaymentStatus::Captured
- | PaypalPaymentStatus::Refunded => Self::Charged,
- PaypalPaymentStatus::Declined => Self::Failure,
- PaypalPaymentStatus::Failed => Self::CaptureFailed,
- PaypalPaymentStatus::Pending => Self::Pending,
- PaypalPaymentStatus::Denied | PaypalPaymentStatus::Expired => Self::Failure,
- PaypalPaymentStatus::PartiallyCaptured => Self::PartialCharged,
- PaypalPaymentStatus::Voided => Self::Voided,
+fn get_payment_attempt_status(
+ item: PaypalPaymentStatus,
+ prev_status: storage_enums::AttemptStatus,
+) -> storage_enums::AttemptStatus {
+ match item {
+ PaypalPaymentStatus::Created => storage_enums::AttemptStatus::Authorized,
+ PaypalPaymentStatus::Completed
+ | PaypalPaymentStatus::Captured
+ | PaypalPaymentStatus::Refunded => storage_enums::AttemptStatus::Charged,
+ PaypalPaymentStatus::Declined => storage_enums::AttemptStatus::Failure,
+ PaypalPaymentStatus::Failed => storage_enums::AttemptStatus::CaptureFailed,
+ PaypalPaymentStatus::Pending => storage_enums::AttemptStatus::Pending,
+ PaypalPaymentStatus::Denied | PaypalPaymentStatus::Expired => {
+ storage_enums::AttemptStatus::Failure
+ }
+ PaypalPaymentStatus::PartiallyCaptured => storage_enums::AttemptStatus::PartialCharged,
+ PaypalPaymentStatus::Voided => storage_enums::AttemptStatus::Voided,
+ PaypalPaymentStatus::Unknown => {
+ router_env::logger::warn!(
+ "Unknown paypal payment status received; retaining previous status {:?}",
+ prev_status
+ );
+ prev_status
}
}
}
@@ -3247,7 +3332,7 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaypalCaptureResponse>>
fn try_from(
item: PaymentsCaptureResponseRouterData<PaypalCaptureResponse>,
) -> Result<Self, Self::Error> {
- let status = storage_enums::AttemptStatus::from(item.response.status);
+ let status = get_payment_attempt_status(item.response.status, item.data.status);
let amount_captured = match status {
storage_enums::AttemptStatus::Pending
| storage_enums::AttemptStatus::Authorized
@@ -3317,6 +3402,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaypalCaptureResponse>>
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalCancelStatus {
Voided,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
@@ -3334,8 +3421,16 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaypalPaymentsCancelResponse, T, Paymen
fn try_from(
item: ResponseRouterData<F, PaypalPaymentsCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
+ let prev_status = item.data.status;
let status = match item.response.status {
PaypalCancelStatus::Voided => storage_enums::AttemptStatus::Voided,
+ PaypalCancelStatus::Unknown => {
+ router_env::logger::warn!(
+ "Unknown paypal cancel status received; retaining previous status {:?}",
+ prev_status
+ );
+ prev_status
+ }
};
Ok(Self {
status,
@@ -3384,14 +3479,24 @@ pub enum RefundStatus {
Failed,
Cancelled,
Pending,
+ #[serde(other)]
+ Unknown,
}
-impl From<RefundStatus> for storage_enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
- match item {
- RefundStatus::Completed => Self::Success,
- RefundStatus::Failed | RefundStatus::Cancelled => Self::Failure,
- RefundStatus::Pending => Self::Pending,
+fn get_refund_status(
+ item: RefundStatus,
+ prev_status: storage_enums::RefundStatus,
+) -> storage_enums::RefundStatus {
+ match item {
+ RefundStatus::Completed => storage_enums::RefundStatus::Success,
+ RefundStatus::Failed | RefundStatus::Cancelled => storage_enums::RefundStatus::Failure,
+ RefundStatus::Pending => storage_enums::RefundStatus::Pending,
+ RefundStatus::Unknown => {
+ router_env::logger::warn!(
+ "Unknown paypal refund status received; retaining previous status {:?}",
+ prev_status
+ );
+ prev_status
}
}
}
@@ -3408,10 +3513,11 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRout
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
+ let prev_refund_status = item.data.request.refund_status;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
- refund_status: storage_enums::RefundStatus::from(item.response.status),
+ refund_status: get_refund_status(item.response.status, prev_refund_status),
}),
..item.data
})
@@ -3429,10 +3535,11 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for RefundsRo
fn try_from(
item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
+ let prev_refund_status = item.data.request.refund_status;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
- refund_status: storage_enums::RefundStatus::from(item.response.status),
+ refund_status: get_refund_status(item.response.status, prev_refund_status),
}),
..item.data
})
@@ -3605,6 +3712,8 @@ pub enum DisputeLifeCycleStage {
Chargeback,
PreArbitration,
Arbitration,
+ #[serde(other)]
+ Unknown,
}
#[derive(Deserialize, Debug, strum::Display, Serialize)]
@@ -3616,6 +3725,8 @@ pub enum DisputeStatus {
UnderReview,
Resolved,
Other,
+ #[serde(other)]
+ Unknown,
}
#[derive(Deserialize, Debug, Serialize)]
@@ -3633,6 +3744,8 @@ pub enum OutcomeCode {
ACCEPTED,
DENIED,
NONE,
+ #[serde(other)]
+ Unknown,
}
#[derive(Deserialize, Debug, Serialize)]
@@ -3744,18 +3857,25 @@ impl From<OutcomeCode> for IncomingWebhookEvent {
OutcomeCode::ACCEPTED => Self::DisputeAccepted,
OutcomeCode::DENIED => Self::DisputeCancelled,
OutcomeCode::NONE => Self::DisputeCancelled,
- OutcomeCode::ResolvedWithPayout => Self::EventNotSupported,
+ OutcomeCode::ResolvedWithPayout | OutcomeCode::Unknown => Self::EventNotSupported,
}
}
}
-impl From<DisputeLifeCycleStage> for enums::DisputeStage {
- fn from(dispute_life_cycle_stage: DisputeLifeCycleStage) -> Self {
+impl TryFrom<DisputeLifeCycleStage> for enums::DisputeStage {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(dispute_life_cycle_stage: DisputeLifeCycleStage) -> Result<Self, Self::Error> {
match dispute_life_cycle_stage {
- DisputeLifeCycleStage::Inquiry => Self::PreDispute,
- DisputeLifeCycleStage::Chargeback => Self::Dispute,
- DisputeLifeCycleStage::PreArbitration => Self::PreArbitration,
- DisputeLifeCycleStage::Arbitration => Self::PreArbitration,
+ DisputeLifeCycleStage::Inquiry => Ok(Self::PreDispute),
+ DisputeLifeCycleStage::Chargeback => Ok(Self::Dispute),
+ DisputeLifeCycleStage::PreArbitration => Ok(Self::PreArbitration),
+ DisputeLifeCycleStage::Arbitration => Ok(Self::PreArbitration),
+ DisputeLifeCycleStage::Unknown => Err(error_stack::Report::new(
+ errors::ConnectorError::WebhookBodyDecodingFailed,
+ ))
+ .attach_printable(
+ "Received unknown paypal dispute life cycle stage; cannot determine outcome without explicit mapping",
+ ),
}
}
}
@@ -3781,6 +3901,8 @@ pub struct PaypalSourceVerificationResponse {
pub enum PaypalSourceVerificationStatus {
Success,
Failure,
+ #[serde(other)]
+ Unknown,
}
impl
@@ -3815,7 +3937,9 @@ impl From<PaypalSourceVerificationStatus> for VerifyWebhookStatus {
fn from(item: PaypalSourceVerificationStatus) -> Self {
match item {
PaypalSourceVerificationStatus::Success => Self::SourceVerified,
- PaypalSourceVerificationStatus::Failure => Self::SourceNotVerified,
+ PaypalSourceVerificationStatus::Failure | PaypalSourceVerificationStatus::Unknown => {
+ Self::SourceNotVerified
+ }
}
}
}