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

feat: Added Paypal Post Auth Flow for HS<>UCS tunnel (#10640)

Amitsingh Tanwara0c835891df7
diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs
index 944208f940..09eb6358d5 100644
--- a/crates/hyperswitch_connectors/src/connectors/paypal.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs
@@ -25,14 +25,15 @@ use hyperswitch_domain_models::{
SetupMandate, Void,
},
refunds::{Execute, RSync},
+ unified_authentication_service::PostAuthenticate,
CompleteAuthorize, VerifyWebhookSource,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData,
- PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsSessionData,
- PaymentsSyncData, RefundsData, ResponseId, SdkPaymentsSessionUpdateData,
+ PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
+ PaymentsSessionData, PaymentsSyncData, RefundsData, SdkPaymentsSessionUpdateData,
SetupMandateRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
@@ -42,10 +43,10 @@ use hyperswitch_domain_models::{
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsExtendAuthorizationRouterData,
- PaymentsIncrementalAuthorizationRouterData, PaymentsPostSessionTokensRouterData,
- PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData,
- RefundSyncRouterData, RefundsRouterData, SdkSessionUpdateRouterData,
- SetupMandateRouterData, VerifyWebhookSourceRouterData,
+ PaymentsIncrementalAuthorizationRouterData, PaymentsPostAuthenticateRouterData,
+ PaymentsPostSessionTokensRouterData, PaymentsPreProcessingRouterData,
+ PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
+ SdkSessionUpdateRouterData, SetupMandateRouterData, VerifyWebhookSourceRouterData,
},
};
#[cfg(feature = "payouts")]
@@ -67,10 +68,10 @@ use hyperswitch_interfaces::{
events::connector_api_logs::ConnectorEvent,
types::{
ExtendedAuthorizationType, IncrementalAuthorizationType, PaymentsAuthorizeType,
- PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsPostSessionTokensType,
- PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefreshTokenType,
- RefundExecuteType, RefundSyncType, Response, SdkSessionUpdateType, SetupMandateType,
- VerifyWebhookSourceType,
+ PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsPostAuthenticateType,
+ PaymentsPostSessionTokensType, PaymentsPreProcessingType, PaymentsSyncType,
+ PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response,
+ SdkSessionUpdateType, SetupMandateType, VerifyWebhookSourceType,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
@@ -83,7 +84,7 @@ use transformers::{
};
use crate::{
- constants::{self, headers},
+ constants::headers,
types::ResponseRouterData,
utils::{
self as connector_utils, to_connector_meta, ConnectorErrorType, ConnectorErrorTypeMapping,
@@ -1378,116 +1379,108 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- match response {
- // if card supports 3DS check for liability
- paypal::PaypalPreProcessingResponse::PaypalLiabilityResponse(liability_response) => {
- // permutation for status to continue payment
- match (
- liability_response
- .payment_source
- .card
- .authentication_result
- .three_d_secure
- .enrollment_status
- .as_ref(),
- liability_response
- .payment_source
- .card
- .authentication_result
- .three_d_secure
- .authentication_status
- .as_ref(),
- liability_response
- .payment_source
- .card
- .authentication_result
- .liability_shift
- .clone(),
- ) {
- (
- Some(paypal::EnrollmentStatus::Ready),
- Some(paypal::AuthenticationStatus::Success),
- paypal::LiabilityShift::Possible,
- )
- | (
- Some(paypal::EnrollmentStatus::Ready),
- Some(paypal::AuthenticationStatus::Attempted),
- paypal::LiabilityShift::Possible,
- )
- | (Some(paypal::EnrollmentStatus::NotReady), None, paypal::LiabilityShift::No)
- | (Some(paypal::EnrollmentStatus::Unavailable), None, paypal::LiabilityShift::No)
- | (Some(paypal::EnrollmentStatus::Bypassed), None, paypal::LiabilityShift::No) => {
- Ok(PaymentsPreProcessingRouterData {
- status: enums::AttemptStatus::AuthenticationSuccessful,
- response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: ResponseId::NoResponseId,
- redirection_data: Box::new(None),
- mandate_reference: Box::new(None),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charges: None,
- }),
- ..data.clone()
- })
- }
- _ => Ok(PaymentsPreProcessingRouterData {
- response: Err(ErrorResponse {
- attempt_status: Some(enums::AttemptStatus::Failure),
- code: NO_ERROR_CODE.to_string(),
- message: NO_ERROR_MESSAGE.to_string(),
- connector_transaction_id: None,
- reason: Some(format!("{} Connector Responsded with LiabilityShift: {:?}, EnrollmentStatus: {:?}, and AuthenticationStatus: {:?}",
- constants::CANNOT_CONTINUE_AUTH,
- liability_response
- .payment_source
- .card
- .authentication_result
- .liability_shift,
- liability_response
- .payment_source
- .card
- .authentication_result
- .three_d_secure
- .enrollment_status
- .unwrap_or(paypal::EnrollmentStatus::Null),
- liability_response
- .payment_source
- .card
- .authentication_result
- .three_d_secure
- .authentication_status
- .unwrap_or(paypal::AuthenticationStatus::Null),
- )),
- status_code: res.status_code,
- network_advice_code: None,
- network_decline_code: None,
- network_error_message: None,
- connector_metadata: None,
- }),
- ..data.clone()
- }),
- }
+ let (status, response) = match PaymentsResponseData::try_from(response) {
+ Ok(data) => (enums::AttemptStatus::AuthenticationSuccessful, Ok(data)),
+ Err(error) => {
+ let mut error: ErrorResponse = error;
+ error.status_code = res.status_code;
+ (enums::AttemptStatus::Failure, Err(error))
}
- // if card does not supports 3DS check for liability
- paypal::PaypalPreProcessingResponse::PaypalNonLiabilityResponse(_) => {
- Ok(PaymentsPreProcessingRouterData {
- status: enums::AttemptStatus::AuthenticationSuccessful,
- response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: ResponseId::NoResponseId,
- redirection_data: Box::new(None),
- mandate_reference: Box::new(None),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charges: None,
- }),
- ..data.clone()
- })
+ };
+
+ Ok(PaymentsPreProcessingRouterData {
+ status,
+ response,
+ ..data.clone()
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl api::PaymentsPostAuthenticate for Paypal {}
+
+impl ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>
+ for Paypal
+{
+ fn get_headers(
+ &self,
+ req: &PaymentsPostAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_url(
+ &self,
+ req: &PaymentsPostAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let order_id = req
+ .request
+ .connector_transaction_id
+ .to_owned()
+ .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}v2/checkout/orders/{}?fields=payment_source",
+ self.base_url(connectors),
+ order_id,
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsPostAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsPostAuthenticateType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(PaymentsPostAuthenticateType::get_headers(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsPostAuthenticateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsPostAuthenticateRouterData, errors::ConnectorError> {
+ let response: paypal::PaypalPostAuthenticateResponse = res
+ .response
+ .parse_struct("paypal PaypalPostAuthenticateResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ let (status, response) = match PaymentsResponseData::try_from(response) {
+ Ok(data) => (enums::AttemptStatus::AuthenticationSuccessful, Ok(data)),
+ Err(error) => {
+ let mut error: ErrorResponse = error;
+ error.status_code = res.status_code;
+ (enums::AttemptStatus::Failure, Err(error))
}
- }
+ };
+
+ Ok(PaymentsPostAuthenticateRouterData {
+ status,
+ response,
+ ..data.clone()
+ })
}
fn get_error_response(
diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
index c8a9933029..349d9a37de 100644
--- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
@@ -43,7 +43,10 @@ use hyperswitch_domain_models::{
router_flow_types::PoFulfill, router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
-use hyperswitch_interfaces::errors;
+use hyperswitch_interfaces::{
+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
+ errors,
+};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -1709,12 +1712,8 @@ impl TryFrom<PaymentsExtendAuthorizationResponseRouterData<PaypalExtendedAuthRes
.and_then(|status_details| status_details.reason.map(|reason| reason.to_string()));
Err(ErrorResponse {
- code: reason
- .clone()
- .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
- message: reason
- .clone()
- .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
+ code: reason.clone().unwrap_or(NO_ERROR_CODE.to_string()),
+ message: reason.clone().unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
@@ -1915,6 +1914,114 @@ pub enum PaypalPreProcessingResponse {
PaypalNonLiabilityResponse(PaypalNonLiabilityResponse),
}
+impl TryFrom<PaypalPreProcessingResponse> for PaymentsResponseData {
+ type Error = ErrorResponse;
+
+ fn try_from(response: PaypalPreProcessingResponse) -> Result<Self, Self::Error> {
+ match response {
+ PaypalPreProcessingResponse::PaypalNonLiabilityResponse(_) => {
+ Ok(auth_success_response())
+ }
+ PaypalPreProcessingResponse::PaypalLiabilityResponse(liability_response) => {
+ validate_liability_response(liability_response).map_err(|e| *e)
+ }
+ }
+ }
+}
+
+fn auth_success_response() -> PaymentsResponseData {
+ PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charges: None,
+ }
+}
+
+fn validate_liability_response(
+ liability_response: PaypalLiabilityResponse,
+) -> Result<PaymentsResponseData, Box<ErrorResponse>> {
+ let three_ds = &liability_response
+ .payment_source
+ .card
+ .authentication_result
+ .three_d_secure;
+ let auth_result = &liability_response.payment_source.card.authentication_result;
+
+ let allowed = matches!(
+ (
+ three_ds.enrollment_status.as_ref(),
+ three_ds.authentication_status.as_ref(),
+ auth_result.liability_shift.clone(),
+ ),
+ (
+ Some(EnrollmentStatus::Ready),
+ Some(AuthenticationStatus::Success),
+ LiabilityShift::Possible,
+ ) | (
+ Some(EnrollmentStatus::Ready),
+ Some(AuthenticationStatus::Attempted),
+ LiabilityShift::Possible,
+ ) | (Some(EnrollmentStatus::NotReady), None, LiabilityShift::No)
+ | (
+ Some(EnrollmentStatus::Unavailable),
+ None,
+ LiabilityShift::No
+ )
+ | (Some(EnrollmentStatus::Bypassed), None, LiabilityShift::No)
+ );
+
+ if allowed {
+ Ok(auth_success_response())
+ } else {
+ let reason = format!(
+ "{} Connector Responded with LiabilityShift: {:?}, EnrollmentStatus: {:?}, and AuthenticationStatus: {:?}",
+ constants::CANNOT_CONTINUE_AUTH,
+ auth_result.liability_shift,
+ three_ds
+ .enrollment_status
+ .clone()
+ .unwrap_or(EnrollmentStatus::Null),
+ three_ds
+ .authentication_status
+ .clone()
+ .unwrap_or(AuthenticationStatus::Null),
+ );
+
+ Err(Box::new(ErrorResponse {
+ attempt_status: Some(enums::AttemptStatus::Failure),
+ code: NO_ERROR_CODE.to_string(),
+ message: NO_ERROR_MESSAGE.to_string(),
+ connector_transaction_id: None,
+ reason: Some(reason),
+ status_code: 400, // Will be overridden by caller
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ }))
+ }
+}
+
+impl TryFrom<PaypalPostAuthenticateResponse> for PaymentsResponseData {
+ type Error = ErrorResponse;
+
+ fn try_from(response: PaypalPostAuthenticateResponse) -> Result<Self, Self::Error> {
+ match response {
+ PaypalPostAuthenticateResponse::PaypalNonLiabilityResponse(_) => {
+ Ok(auth_success_response())
+ }
+ PaypalPostAuthenticateResponse::PaypalLiabilityResponse(liability_response) => {
+ validate_liability_response(liability_response).map_err(|e| *e)
+ }
+ }
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalLiabilityResponse {
pub payment_source: CardParams,
@@ -1925,6 +2032,13 @@ pub struct PaypalNonLiabilityResponse {
payment_source: CardsData,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum PaypalPostAuthenticateResponse {
+ PaypalLiabilityResponse(PaypalLiabilityResponse),
+ PaypalNonLiabilityResponse(PaypalNonLiabilityResponse),
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CardParams {
pub card: AuthResult,
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 795c6dd140..af11e75663 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -2318,7 +2318,6 @@ default_imp_for_post_authenticate_steps!(
connectors::Paysafe,
connectors::Payme,
connectors::Payone,
- connectors::Paypal,
connectors::Paystack,
connectors::Paytm,
connectors::Payu,