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(connector): [TRUSTPAYMENTS] Integrate cards non 3ds payments (#8705)

Ayush Anand1987cb4ea197
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 34cd0c5147..29fb70620b 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -12131,6 +12131,7 @@
"threedsecureio",
"tokenio",
"trustpay",
+ "trustpayments",
"tsys",
"vgs",
"volt",
@@ -30238,6 +30239,7 @@
"stripe",
"stripebilling",
"trustpay",
+ "trustpayments",
"tokenio",
"tsys",
"volt",
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index f29e2a3005..2bf8e41235 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -8733,6 +8733,7 @@
"threedsecureio",
"tokenio",
"trustpay",
+ "trustpayments",
"tsys",
"vgs",
"volt",
@@ -23967,6 +23968,7 @@
"stripe",
"stripebilling",
"trustpay",
+ "trustpayments",
"tokenio",
"tsys",
"volt",
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs
index 26afb2f2b9..56735cb15d 100644
--- a/crates/common_enums/src/connector_enums.rs
+++ b/crates/common_enums/src/connector_enums.rs
@@ -156,6 +156,7 @@ pub enum RoutableConnectors {
Stripebilling,
// Taxjar,
Trustpay,
+ Trustpayments,
// Thunes
Tokenio,
// Tsys,
@@ -336,6 +337,7 @@ pub enum Connector {
//Thunes,
Tokenio,
Trustpay,
+ Trustpayments,
Tsys,
// UnifiedAuthenticationService,
Vgs,
@@ -519,6 +521,7 @@ impl Connector {
| Self::Taxjar
// | Self::Thunes
| Self::Trustpay
+ | Self::Trustpayments
// | Self::Tokenio
| Self::Tsys
// | Self::UnifiedAuthenticationService
@@ -702,6 +705,7 @@ impl From<RoutableConnectors> for Connector {
RoutableConnectors::Stripebilling => Self::Stripebilling,
RoutableConnectors::Tokenio => Self::Tokenio,
RoutableConnectors::Trustpay => Self::Trustpay,
+ RoutableConnectors::Trustpayments => Self::Trustpayments,
// RoutableConnectors::Tokenio => Self::Tokenio,
RoutableConnectors::Tsys => Self::Tsys,
RoutableConnectors::Volt => Self::Volt,
@@ -835,6 +839,7 @@ impl TryFrom<Connector> for RoutableConnectors {
Connector::Stripebilling => Ok(Self::Stripebilling),
Connector::Tokenio => Ok(Self::Tokenio),
Connector::Trustpay => Ok(Self::Trustpay),
+ Connector::Trustpayments => Ok(Self::Trustpayments),
Connector::Tsys => Ok(Self::Tsys),
Connector::Volt => Ok(Self::Volt),
Connector::Wellsfargo => Ok(Self::Wellsfargo),
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 0a521f7a86..2c89a48aed 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -518,6 +518,7 @@ impl ConnectorConfig {
Connector::Stripebilling => Ok(connector_data.stripebilling),
Connector::Tokenio => Ok(connector_data.tokenio),
Connector::Trustpay => Ok(connector_data.trustpay),
+ Connector::Trustpayments => Ok(connector_data.trustpayments),
Connector::Threedsecureio => Ok(connector_data.threedsecureio),
Connector::Taxjar => Ok(connector_data.taxjar),
Connector::Tsys => Ok(connector_data.tsys),
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index ed96969454..d70494ad06 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -6740,8 +6740,19 @@ api_key = "API Key"
key1 = "API Secret"
[trustpayments]
+[[trustpayments.credit]]
+ payment_method_type = "Mastercard"
+[[trustpayments.credit]]
+ payment_method_type = "Visa"
+[[trustpayments.debit]]
+ payment_method_type = "Mastercard"
+[[trustpayments.debit]]
+ payment_method_type = "Visa"
[trustpayments.connector_auth.HeaderKey]
api_key = "API Key"
+[trustpayments.connector_webhook_details]
+merchant_secret = "Source verification key"
+
[breadpay]
[breadpay.connector_auth.BodyKey]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 0bb0c2c3d1..d09b9f386d 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -5392,9 +5392,20 @@ merchant_secret="Source verification key"
api_key = "API Key"
key1 = "API Secret"
+
[trustpayments]
+[[trustpayments.credit]]
+payment_method_type = "Mastercard"
+[[trustpayments.credit]]
+payment_method_type = "Visa"
+[[trustpayments.debit]]
+payment_method_type = "Mastercard"
+[[trustpayments.debit]]
+payment_method_type = "Visa"
[trustpayments.connector_auth.HeaderKey]
api_key = "API Key"
+[trustpayments.connector_webhook_details]
+merchant_secret = "Source verification key"
[flexiti]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 7517db193b..cc159184e0 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -6721,11 +6721,19 @@ merchant_secret="Source verification key"
api_key = "API Key"
key1 = "API Secret"
+
[trustpayments]
+[[trustpayments.credit]]
+payment_method_type = "Mastercard"
+[[trustpayments.credit]]
+payment_method_type = "Visa"
+[[trustpayments.debit]]
+payment_method_type = "Mastercard"
+[[trustpayments.debit]]
+payment_method_type = "Visa"
[trustpayments.connector_auth.HeaderKey]
api_key = "API Key"
-
[breadpay]
[breadpay.connector_auth.BodyKey]
api_key = "API Key"
diff --git a/crates/hyperswitch_connectors/src/connectors/trustpayments.rs b/crates/hyperswitch_connectors/src/connectors/trustpayments.rs
index 4b92c5aef6..a5bbb802ea 100644
--- a/crates/hyperswitch_connectors/src/connectors/trustpayments.rs
+++ b/crates/hyperswitch_connectors/src/connectors/trustpayments.rs
@@ -24,11 +24,12 @@ use hyperswitch_domain_models::{
RefundsData, SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
+ SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
- PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
- RefundSyncRouterData, RefundsRouterData,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
@@ -42,7 +43,7 @@ use hyperswitch_interfaces::{
types::{self, Response},
webhooks,
};
-use masking::{ExposeInterface, Mask};
+use masking::Mask;
use transformers as trustpayments;
use crate::{constants::headers, types::ResponseRouterData, utils};
@@ -76,7 +77,82 @@ impl api::PaymentToken for Trustpayments {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Trustpayments
{
- // Not Implemented (R)
+ fn get_headers(
+ &self,
+ req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/json/", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = trustpayments::TrustpaymentsTokenizationRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::TokenizationType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::TokenizationType::get_headers(self, req, connectors)?)
+ .set_body(types::TokenizationType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<
+ RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
+ errors::ConnectorError,
+ > {
+ let response: trustpayments::TrustpaymentsTokenizationResponse = res
+ .response
+ .parse_struct("Trustpayments TokenizationResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Trustpayments
@@ -104,12 +180,7 @@ impl ConnectorCommon for Trustpayments {
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
- // todo!()
api::CurrencyUnit::Minor
-
- // TODO! Check connector documentation, on which unit they are processing the currency.
- // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
- // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
@@ -128,7 +199,7 @@ impl ConnectorCommon for Trustpayments {
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
+ auth.get_basic_auth_header().into_masked(),
)])
}
@@ -186,9 +257,7 @@ impl ConnectorValidation for Trustpayments {
}
}
-impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Trustpayments {
- //TODO: implement sessions flow
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Trustpayments {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Trustpayments {}
@@ -215,9 +284,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!("{}/json/", self.base_url(connectors)))
}
fn get_request_body(
@@ -303,9 +372,18 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tru
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!("{}/json/", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = trustpayments::TrustpaymentsSyncRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -315,10 +393,13 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tru
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
- .method(Method::Get)
+ .method(Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::PaymentsSyncType::get_request_body(
+ self, req, connectors,
+ )?)
.build(),
))
}
@@ -367,17 +448,26 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!("{}/json/", self.base_url(connectors)))
}
fn get_request_body(
&self,
- _req: &PaymentsCaptureRouterData,
+ req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = trustpayments::TrustpaymentsRouterData::from((amount, req));
+ let connector_req =
+ trustpayments::TrustpaymentsCaptureRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -428,7 +518,81 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
}
}
-impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Trustpayments {}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Trustpayments {
+ fn get_headers(
+ &self,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/json/", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = trustpayments::TrustpaymentsVoidRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(types::PaymentsVoidType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: trustpayments::TrustpaymentsPaymentsResponse = res
+ .response
+ .parse_struct("Trustpayments PaymentsVoidResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Trustpayments {
fn get_headers(
@@ -446,9 +610,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Trustpa
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!("{}/json/", self.base_url(connectors)))
}
fn get_request_body(
@@ -532,9 +696,18 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Trustpaym
fn get_url(
&self,
_req: &RefundSyncRouterData,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!("{}/json/", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RefundSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = trustpayments::TrustpaymentsRefundSyncRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -544,7 +717,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Trustpaym
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
- .method(Method::Get)
+ .method(Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -608,7 +781,61 @@ impl webhooks::IncomingWebhook for Trustpayments {
}
static TRUSTPAYMENTS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
- LazyLock::new(SupportedPaymentMethods::new);
+ LazyLock::new(|| {
+ let supported_capture_methods = vec![
+ enums::CaptureMethod::Automatic,
+ enums::CaptureMethod::Manual,
+ ];
+
+ let mut trustpayments_supported_payment_methods = SupportedPaymentMethods::new();
+
+ trustpayments_supported_payment_methods.add(
+ enums::PaymentMethod::Card,
+ enums::PaymentMethodType::Credit,
+ PaymentMethodDetails {
+ mandates: enums::FeatureStatus::NotSupported,
+ refunds: enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: Some(
+ api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
+ api_models::feature_matrix::CardSpecificFeatures {
+ three_ds: enums::FeatureStatus::NotSupported,
+ no_three_ds: enums::FeatureStatus::Supported,
+ supported_card_networks: vec![
+ enums::CardNetwork::Visa,
+ enums::CardNetwork::Mastercard,
+ enums::CardNetwork::AmericanExpress,
+ ],
+ }
+ }),
+ ),
+ },
+ );
+
+ trustpayments_supported_payment_methods.add(
+ enums::PaymentMethod::Card,
+ enums::PaymentMethodType::Debit,
+ PaymentMethodDetails {
+ mandates: enums::FeatureStatus::NotSupported,
+ refunds: enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: Some(
+ api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
+ api_models::feature_matrix::CardSpecificFeatures {
+ three_ds: enums::FeatureStatus::NotSupported,
+ no_three_ds: enums::FeatureStatus::Supported,
+ supported_card_networks: vec![
+ enums::CardNetwork::Visa,
+ enums::CardNetwork::Mastercard,
+ ],
+ }
+ }),
+ ),
+ },
+ );
+
+ trustpayments_supported_payment_methods
+ });
static TRUSTPAYMENTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Trustpayments",
diff --git a/crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
index debeca6b63..befb962553 100644
--- a/crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
@@ -1,28 +1,300 @@
+use cards;
use common_enums::enums;
use common_utils::types::StringMinorUnit;
+use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
- types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
+ },
};
use hyperswitch_interfaces::errors;
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
-use crate::types::{RefundsResponseRouterData, ResponseRouterData};
+use crate::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{self, CardData, RefundsRequestData, RouterData as RouterDataExt},
+};
+
+const TRUSTPAYMENTS_API_VERSION: &str = "1.00";
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub enum TrustpaymentsSettleStatus {
+ #[serde(rename = "0")]
+ PendingSettlement,
+ #[serde(rename = "1")]
+ Settled,
+ #[serde(rename = "2")]
+ ManualCapture,
+ #[serde(rename = "3")]
+ Voided,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub enum TrustpaymentsCredentialsOnFile {
+ #[serde(rename = "0")]
+ NoStoredCredentials,
+ #[serde(rename = "1")]
+ CardholderInitiatedTransaction,
+ #[serde(rename = "2")]
+ MerchantInitiatedTransaction,
+}
+
+impl TrustpaymentsCredentialsOnFile {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Self::NoStoredCredentials => "0",
+ Self::CardholderInitiatedTransaction => "1",
+ Self::MerchantInitiatedTransaction => "2",
+ }
+ }
+}
+
+impl std::fmt::Display for TrustpaymentsCredentialsOnFile {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.as_str())
+ }
+}
+
+impl TrustpaymentsSettleStatus {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Self::PendingSettlement => "0",
+ Self::Settled => "1",
+ Self::ManualCapture => "2",
+ Self::Voided => "3",
+ }
+ }
+}
+
+impl std::fmt::Display for TrustpaymentsSettleStatus {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.as_str())
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub enum TrustpaymentsErrorCode {
+ #[serde(rename = "0")]
+ Success,
+
+ #[serde(rename = "30000")]
+ InvalidCredentials,
+ #[serde(rename = "30001")]
+ AuthenticationFailed,
+ #[serde(rename = "30002")]
+ InvalidSiteReference,
+ #[serde(rename = "30003")]
+ AccessDenied,
+ #[serde(rename = "30004")]
+ InvalidUsernameOrPassword,
+ #[serde(rename = "30005")]
+ AccountSuspended,
+ #[serde(rename = "50000")]
+ MissingRequiredField,
+ #[serde(rename = "50001")]
+ InvalidFieldFormat,
+ #[serde(rename = "50002")]
+ InvalidFieldValue,
+ #[serde(rename = "50003")]
+ FieldTooLong,
+ #[serde(rename = "50004")]
+ FieldTooShort,
+ #[serde(rename = "50005")]
+ InvalidCurrency,
+ #[serde(rename = "50006")]
+ InvalidAmount,
+ #[serde(rename = "60000")]
+ GeneralProcessingError,
+ #[serde(rename = "60001")]
+ SystemError,
+ #[serde(rename = "60002")]
+ CommunicationError,
+ #[serde(rename = "60003")]
+ Timeout,
+ #[serde(rename = "60004")]
+ Processing,
+ #[serde(rename = "60005")]
+ InvalidRequest,
+ #[serde(rename = "60019")]
+ NoSearchableFilter,
+ #[serde(rename = "70000")]
+ InvalidCardNumber,
+ #[serde(rename = "70001")]
+ InvalidExpiryDate,
+ #[serde(rename = "70002")]
+ InvalidSecurityCode,
+ #[serde(rename = "70003")]
+ InvalidCardType,
+ #[serde(rename = "70004")]
+ CardExpired,
+ #[serde(rename = "70005")]
+ InsufficientFunds,
+ #[serde(rename = "70006")]
+ CardDeclined,
+ #[serde(rename = "70007")]
+ CardRestricted,
+ #[serde(rename = "70008")]
+ InvalidMerchant,
+ #[serde(rename = "70009")]
+ TransactionNotPermitted,
+ #[serde(rename = "70010")]
+ ExceedsWithdrawalLimit,
+ #[serde(rename = "70011")]
+ SecurityViolation,
+ #[serde(rename = "70012")]
+ LostOrStolenCard,
+ #[serde(rename = "70013")]
+ SuspectedFraud,
+ #[serde(rename = "70014")]
+ ContactCardIssuer,
+ #[serde(rename = "70015")]
+ InvalidAmountValue,
+ #[serde(untagged)]
+ Unknown(String),
+}
+
+impl TrustpaymentsErrorCode {
+ pub fn as_str(&self) -> &str {
+ match self {
+ Self::Success => "0",
+ Self::InvalidCredentials => "30000",
+ Self::AuthenticationFailed => "30001",
+ Self::InvalidSiteReference => "30002",
+ Self::AccessDenied => "30003",
+ Self::InvalidUsernameOrPassword => "30004",
+ Self::AccountSuspended => "30005",
+ Self::MissingRequiredField => "50000",
+ Self::InvalidFieldFormat => "50001",
+ Self::InvalidFieldValue => "50002",
+ Self::FieldTooLong => "50003",
+ Self::FieldTooShort => "50004",
+ Self::InvalidCurrency => "50005",
+ Self::InvalidAmount => "50006",
+ Self::GeneralProcessingError => "60000",
+ Self::SystemError => "60001",
+ Self::CommunicationError => "60002",
+ Self::Timeout => "60003",
+ Self::Processing => "60004",
+ Self::InvalidRequest => "60005",
+ Self::NoSearchableFilter => "60019",
+ Self::InvalidCardNumber => "70000",
+ Self::InvalidExpiryDate => "70001",
+ Self::InvalidSecurityCode => "70002",
+ Self::InvalidCardType => "70003",
+ Self::CardExpired => "70004",
+ Self::InsufficientFunds => "70005",
+ Self::CardDeclined => "70006",
+ Self::CardRestricted => "70007",
+ Self::InvalidMerchant => "70008",
+ Self::TransactionNotPermitted => "70009",
+ Self::ExceedsWithdrawalLimit => "70010",
+ Self::SecurityViolation => "70011",
+ Self::LostOrStolenCard => "70012",
+ Self::SuspectedFraud => "70013",
+ Self::ContactCardIssuer => "70014",
+ Self::InvalidAmountValue => "70015",
+ Self::Unknown(code) => code,
+ }
+ }
+
+ pub fn is_success(&self) -> bool {
+ matches!(self, Self::Success)
+ }
+
+ pub fn get_attempt_status(&self) -> common_enums::AttemptStatus {
+ match self {
+ // Success cases should be handled by get_payment_status() with settlestatus logic
+ Self::Success => common_enums::AttemptStatus::Authorized,
+ // Authentication and configuration errors
+ Self::InvalidCredentials
+ | Self::AuthenticationFailed
+ | Self::InvalidSiteReference
+ | Self::AccessDenied
+ | Self::InvalidUsernameOrPassword
+ | Self::AccountSuspended => common_enums::AttemptStatus::Failure,
+ // Card-related and payment errors that should be treated as failures
+ Self::InvalidCardNumber
+ | Self::InvalidExpiryDate
+ | Self::InvalidSecurityCode
+ | Self::InvalidCardType
+ | Self::CardExpired
+ | Self::InsufficientFunds
+ | Self::CardDeclined
+ | Self::CardRestricted
+ | Self::TransactionNotPermitted
+ | Self::ExceedsWithdrawalLimit
+ | Self::InvalidAmountValue => common_enums::AttemptStatus::Failure,
+ // Processing states that should remain pending
+ Self::Processing => common_enums::AttemptStatus::Pending,
+ // Default fallback for unknown errors
+ _ => common_enums::AttemptStatus::Pending,
+ }
+ }
+
+ pub fn get_description(&self) -> &'static str {
+ match self {
+ Self::Success => "Success",
+ Self::InvalidCredentials => "Invalid credentials",
+ Self::AuthenticationFailed => "Authentication failed",
+ Self::InvalidSiteReference => "Invalid site reference",
+ Self::AccessDenied => "Access denied",
+ Self::InvalidUsernameOrPassword => "Invalid username or password",
+ Self::AccountSuspended => "Account suspended",
+ Self::MissingRequiredField => "Missing required field",
+ Self::InvalidFieldFormat => "Invalid field format",
+ Self::InvalidFieldValue => "Invalid field value",
+ Self::FieldTooLong => "Field value too long",
+ Self::FieldTooShort => "Field value too short",
+ Self::InvalidCurrency => "Invalid currency code",
+ Self::InvalidAmount => "Invalid amount format",
+ Self::GeneralProcessingError => "General processing error",
+ Self::SystemError => "System error",
+ Self::CommunicationError => "Communication error",
+ Self::Timeout => "Request timeout",
+ Self::Processing => "Transaction processing",
+ Self::InvalidRequest => "Invalid request format",
+ Self::NoSearchableFilter => "No searchable filter specified",
+ Self::InvalidCardNumber => "Invalid card number",
+ Self::InvalidExpiryDate => "Invalid expiry date",
+ Self::InvalidSecurityCode => "Invalid security code",
+ Self::InvalidCardType => "Invalid card type",
+ Self::CardExpired => "Card expired",
+ Self::InsufficientFunds => "Insufficient funds",
+ Self::CardDeclined => "Card declined by issuer",
+ Self::CardRestricted => "Card restricted",
+ Self::InvalidMerchant => "Invalid merchant",
+ Self::TransactionNotPermitted => "Transaction not permitted",
+ Self::ExceedsWithdrawalLimit => "Exceeds withdrawal limit",
+ Self::SecurityViolation => "Security violation",
+ Self::LostOrStolenCard => "Lost or stolen card",
+ Self::SuspectedFraud => "Suspected fraud",
+ Self::ContactCardIssuer => "Contact card issuer",
+ Self::InvalidAmountValue => "Invalid amount",
+ Self::Unknown(_) => "Unknown error",
+ }
+ }
+}
+
+impl std::fmt::Display for TrustpaymentsErrorCode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.as_str())
+ }
+}
-//TODO: Fill the struct with respective fields
pub struct TrustpaymentsRouterData<T> {
- pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for TrustpaymentsRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
- //Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
@@ -30,20 +302,28 @@ impl<T> From<(StringMinorUnit, T)> for TrustpaymentsRouterData<T> {
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, PartialEq)]
+#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsPaymentsRequest {
- amount: StringMinorUnit,
- card: TrustpaymentsCard,
+ pub alias: String,
+ pub version: String,
+ pub request: Vec<TrustpaymentsPaymentRequestData>,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct TrustpaymentsCard {
- number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsPaymentRequestData {
+ pub accounttypedescription: String,
+ pub baseamount: StringMinorUnit,
+ pub billingfirstname: Option<String>,
+ pub billinglastname: Option<String>,
+ pub currencyiso3a: String,
+ pub expirydate: Secret<String>,
+ pub orderreference: String,
+ pub pan: cards::CardNumber,
+ pub requesttypedescriptions: Vec<String>,
+ pub securitycode: Secret<String>,
+ pub sitereference: String,
+ pub credentialsonfile: String,
+ pub settlestatus: String,
}
impl TryFrom<&TrustpaymentsRouterData<&PaymentsAuthorizeRouterData>>
@@ -53,77 +333,508 @@ impl TryFrom<&TrustpaymentsRouterData<&PaymentsAuthorizeRouterData>>
fn try_from(
item: &TrustpaymentsRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
+ let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?;
+
+ if matches!(
+ item.router_data.auth_type,
+ enums::AuthenticationType::ThreeDs
+ ) {
+ return Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("trustpayments"),
+ )
+ .into());
+ }
+
match item.router_data.request.payment_method_data.clone() {
- PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
- "Card payment method not implemented".to_string(),
+ PaymentMethodData::Card(req_card) => {
+ let card = req_card.clone();
+
+ let request_types = match item.router_data.request.capture_method {
+ Some(common_enums::CaptureMethod::Automatic) | None => vec!["AUTH".to_string()],
+ Some(common_enums::CaptureMethod::Manual) => vec!["AUTH".to_string()],
+ Some(common_enums::CaptureMethod::ManualMultiple)
+ | Some(common_enums::CaptureMethod::Scheduled)
+ | Some(common_enums::CaptureMethod::SequentialAutomatic) => {
+ return Err(errors::ConnectorError::NotSupported {
+ message: "Capture method not supported by TrustPayments".to_string(),
+ connector: "TrustPayments",
+ }
+ .into());
+ }
+ };
+
+ Ok(Self {
+ alias: auth.username.expose(),
+ version: TRUSTPAYMENTS_API_VERSION.to_string(),
+ request: vec![TrustpaymentsPaymentRequestData {
+ accounttypedescription: "ECOM".to_string(),
+ baseamount: item.amount.clone(),
+ billingfirstname: item
+ .router_data
+ .get_optional_billing_first_name()
+ .map(|name| name.expose()),
+ billinglastname: item
+ .router_data
+ .get_optional_billing_last_name()
+ .map(|name| name.expose()),
+ currencyiso3a: item.router_data.request.currency.to_string(),
+ expirydate: card
+ .get_card_expiry_month_year_2_digit_with_delimiter("/".to_string())?,
+ orderreference: item.router_data.connector_request_reference_id.clone(),
+ pan: card.card_number.clone(),
+ requesttypedescriptions: request_types,
+ securitycode: card.card_cvc.clone(),
+ sitereference: auth.site_reference.expose(),
+ credentialsonfile:
+ TrustpaymentsCredentialsOnFile::CardholderInitiatedTransaction
+ .to_string(),
+ settlestatus: match item.router_data.request.capture_method {
+ Some(common_enums::CaptureMethod::Manual) => {
+ TrustpaymentsSettleStatus::ManualCapture
+ .as_str()
+ .to_string()
+ }
+ Some(common_enums::CaptureMethod::Automatic) | None => {
+ TrustpaymentsSettleStatus::PendingSettlement
+ .as_str()
+ .to_string()
+ }
+ _ => TrustpaymentsSettleStatus::PendingSettlement
+ .as_str()
+ .to_string(),
+ },
+ }],
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented(
+ "Payment method not supported".to_string(),
)
.into()),
- _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
-//TODO: Fill the struct with respective fields
-// Auth Struct
pub struct TrustpaymentsAuthType {
- pub(super) api_key: Secret<String>,
+ pub(super) username: Secret<String>,
+ pub(super) password: Secret<String>,
+ pub(super) site_reference: Secret<String>,
+}
+
+impl TrustpaymentsAuthType {
+ pub fn get_basic_auth_header(&self) -> String {
+ use base64::Engine;
+ let credentials = format!(
+ "{}:{}",
+ self.username.clone().expose(),
+ self.password.clone().expose()
+ );
+ let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
+ format!("Basic {encoded}")
+ }
}
impl TryFrom<&ConnectorAuthType> for TrustpaymentsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_owned(),
+ ConnectorAuthType::SignatureKey {
+ api_key,
+ key1,
+ api_secret,
+ } => Ok(Self {
+ username: api_key.to_owned(),
+ password: key1.to_owned(),
+ site_reference: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
-// PaymentsResponse
-//TODO: Append the remaining status flags
-#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "lowercase")]
-pub enum TrustpaymentsPaymentStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct TrustpaymentsPaymentsResponse {
+ #[serde(alias = "response")]
+ pub responses: Vec<TrustpaymentsPaymentResponseData>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct TrustpaymentsPaymentResponseData {
+ pub errorcode: TrustpaymentsErrorCode,
+ pub errormessage: String,
+ pub authcode: Option<String>,
+ pub baseamount: Option<StringMinorUnit>,
+ pub currencyiso3a: Option<String>,
+ pub transactionreference: Option<String>,
+ pub settlestatus: Option<TrustpaymentsSettleStatus>,
+ pub requesttypedescription: String,
+ pub securityresponsesecuritycode: Option<String>,
}
-impl From<TrustpaymentsPaymentStatus> for common_enums::AttemptStatus {
- fn from(item: TrustpaymentsPaymentStatus) -> Self {
- match item {
- TrustpaymentsPaymentStatus::Succeeded => Self::Charged,
- TrustpaymentsPaymentStatus::Failed => Self::Failure,
- TrustpaymentsPaymentStatus::Processing => Self::Authorizing,
+impl TrustpaymentsPaymentResponseData {
+ pub fn get_payment_status(&self) -> common_enums::AttemptStatus {
+ match self.errorcode {
+ TrustpaymentsErrorCode::Success => {
+ if self.authcode.is_some() {
+ match &self.settlestatus {
+ Some(TrustpaymentsSettleStatus::PendingSettlement) => {
+ // settlestatus "0" = automatic capture, scheduled to settle
+ common_enums::AttemptStatus::Charged
+ }
+ Some(TrustpaymentsSettleStatus::Settled) => {
+ // settlestatus "1" or "100" = transaction has been settled
+ common_enums::AttemptStatus::Charged
+ }
+ Some(TrustpaymentsSettleStatus::ManualCapture) => {
+ // settlestatus "2" = suspended, manual capture needed
+ common_enums::AttemptStatus::Authorized
+ }
+ Some(TrustpaymentsSettleStatus::Voided) => {
+ // settlestatus "3" = transaction has been cancelled
+ common_enums::AttemptStatus::Voided
+ }
+ None => common_enums::AttemptStatus::Authorized,
+ }
+ } else {
+ common_enums::AttemptStatus::Failure
+ }
+ }
+ _ => self.errorcode.get_attempt_status(),
+ }
+ }
+
+ pub fn get_payment_status_for_sync(&self) -> common_enums::AttemptStatus {
+ match self.errorcode {
+ TrustpaymentsErrorCode::Success => {
+ if self.requesttypedescription == "TRANSACTIONQUERY"
+ && self.authcode.is_none()
+ && self.settlestatus.is_none()
+ && self.transactionreference.is_none()
+ {
+ common_enums::AttemptStatus::Authorized
+ } else if self.authcode.is_some() {
+ match &self.settlestatus {
+ Some(TrustpaymentsSettleStatus::PendingSettlement) => {
+ common_enums::AttemptStatus::Authorized
+ }
+ Some(TrustpaymentsSettleStatus::Settled) => {
+ common_enums::AttemptStatus::Charged
+ }
+ Some(TrustpaymentsSettleStatus::ManualCapture) => {
+ common_enums::AttemptStatus::Authorized
+ }
+ Some(TrustpaymentsSettleStatus::Voided) => {
+ common_enums::AttemptStatus::Voided
+ }
+ None => common_enums::AttemptStatus::Authorized,
+ }
+ } else {
+ common_enums::AttemptStatus::Pending
+ }
+ }
+ _ => self.errorcode.get_attempt_status(),
+ }
+ }
+
+ pub fn get_error_message(&self) -> String {
+ if self.errorcode.is_success() {
+ "Success".to_string()
+ } else {
+ format!("Error {}: {}", self.errorcode, self.errormessage)
+ }
+ }
+
+ pub fn get_error_reason(&self) -> Option<String> {
+ if !self.errorcode.is_success() {
+ Some(self.errorcode.get_description().to_string())
+ } else {
+ None
}
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct TrustpaymentsPaymentsResponse {
- status: TrustpaymentsPaymentStatus,
- id: String,
+impl
+ TryFrom<
+ ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Authorize,
+ TrustpaymentsPaymentsResponse,
+ hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >
+ for RouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Authorize,
+ hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Authorize,
+ TrustpaymentsPaymentsResponse,
+ hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let response_data = item
+ .response
+ .responses
+ .first()
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ let status = response_data.get_payment_status();
+ let transaction_id = response_data
+ .transactionreference
+ .clone()
+ .unwrap_or_else(|| "unknown".to_string());
+
+ if !response_data.errorcode.is_success() {
+ let _error_response = TrustpaymentsErrorResponse::from(response_data.clone());
+ return Ok(Self {
+ status,
+ response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
+ code: response_data.errorcode.to_string(),
+ message: response_data.errormessage.clone(),
+ reason: response_data.get_error_reason(),
+ status_code: item.http_code,
+ attempt_status: Some(status),
+ connector_transaction_id: response_data.transactionreference.clone(),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ }),
+ ..item.data
+ });
+ }
+
+ Ok(Self {
+ status,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(transaction_id),
+ incremental_authorization_allowed: None,
+ charges: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl
+ TryFrom<
+ ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::PSync,
+ TrustpaymentsPaymentsResponse,
+ hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ PaymentsResponseData,
+ >,
+ >
+ for RouterData<
+ hyperswitch_domain_models::router_flow_types::payments::PSync,
+ hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ PaymentsResponseData,
+ >
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::PSync,
+ TrustpaymentsPaymentsResponse,
+ hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let response_data = item
+ .response
+ .responses
+ .first()
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let status = response_data.get_payment_status_for_sync();
+ let transaction_id = item
+ .data
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+
+ if !response_data.errorcode.is_success() {
+ return Ok(Self {
+ status,
+ response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
+ code: response_data.errorcode.to_string(),
+ message: response_data.errormessage.clone(),
+ reason: response_data.get_error_reason(),
+ status_code: item.http_code,
+ attempt_status: Some(status),
+ connector_transaction_id: Some(transaction_id.clone()),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ }),
+ ..item.data
+ });
+ }
+
+ Ok(Self {
+ status,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(transaction_id),
+ incremental_authorization_allowed: None,
+ charges: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl
+ TryFrom<
+ ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Capture,
+ TrustpaymentsPaymentsResponse,
+ hyperswitch_domain_models::router_request_types::PaymentsCaptureData,
+ PaymentsResponseData,
+ >,
+ >
+ for RouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Capture,
+ hyperswitch_domain_models::router_request_types::PaymentsCaptureData,
+ PaymentsResponseData,
+ >
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Capture,
+ TrustpaymentsPaymentsResponse,
+ hyperswitch_domain_models::router_request_types::PaymentsCaptureData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let response_data = item
+ .response
+ .responses
+ .first()
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ let transaction_id = item.data.request.connector_transaction_id.clone();
+ let status = if response_data.errorcode.is_success() {
+ common_enums::AttemptStatus::Charged
+ } else {
+ response_data.get_payment_status()
+ };
+
+ if !response_data.errorcode.is_success() {
+ return Ok(Self {
+ status,
+ response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
+ code: response_data.errorcode.to_string(),
+ message: response_data.errormessage.clone(),
+ reason: response_data.get_error_reason(),
+ status_code: item.http_code,
+ attempt_status: Some(status),
+ connector_transaction_id: Some(transaction_id.clone()),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ }),
+ ..item.data
+ });
+ }
+
+ Ok(Self {
+ status,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(transaction_id),
+ incremental_authorization_allowed: None,
+ charges: None,
+ }),
+ ..item.data
+ })
+ }
}
-impl<F, T> TryFrom<ResponseRouterData<F, TrustpaymentsPaymentsResponse, T, PaymentsResponseData>>
- for RouterData<F, T, PaymentsResponseData>
+impl
+ TryFrom<
+ ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Void,
+ TrustpaymentsPaymentsResponse,
+ hyperswitch_domain_models::router_request_types::PaymentsCancelData,
+ PaymentsResponseData,
+ >,
+ >
+ for RouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Void,
+ hyperswitch_domain_models::router_request_types::PaymentsCancelData,
+ PaymentsResponseData,
+ >
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: ResponseRouterData<F, TrustpaymentsPaymentsResponse, T, PaymentsResponseData>,
+ item: ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::Void,
+ TrustpaymentsPaymentsResponse,
+ hyperswitch_domain_models::router_request_types::PaymentsCancelData,
+ PaymentsResponseData,
+ >,
) -> Result<Self, Self::Error> {
+ let response_data = item
+ .response
+ .responses
+ .first()
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ let transaction_id = item.data.request.connector_transaction_id.clone();
+ let status = if response_data.errorcode.is_success() {
+ common_enums::AttemptStatus::Voided
+ } else {
+ response_data.get_payment_status()
+ };
+
+ if !response_data.errorcode.is_success() {
+ return Ok(Self {
+ status,
+ response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
+ code: response_data.errorcode.to_string(),
+ message: response_data.errormessage.clone(),
+ reason: response_data.get_error_reason(),
+ status_code: item.http_code,
+ attempt_status: Some(status),
+ connector_transaction_id: Some(transaction_id.clone()),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ }),
+ ..item.data
+ });
+ }
+
Ok(Self {
- status: common_enums::AttemptStatus::from(item.response.status),
+ status,
response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
@@ -132,12 +843,116 @@ impl<F, T> TryFrom<ResponseRouterData<F, TrustpaymentsPaymentsResponse, T, Payme
}
}
-//TODO: Fill the struct with respective fields
-// REFUND :
-// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize)]
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsCaptureRequest {
+ pub alias: String,
+ pub version: String,
+ pub request: Vec<TrustpaymentsCaptureRequestData>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsCaptureRequestData {
+ pub requesttypedescriptions: Vec<String>,
+ pub filter: TrustpaymentsFilter,
+ pub updates: TrustpaymentsCaptureUpdates,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsCaptureUpdates {
+ pub settlestatus: TrustpaymentsSettleStatus,
+}
+
+impl TryFrom<&TrustpaymentsRouterData<&PaymentsCaptureRouterData>> for TrustpaymentsCaptureRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &TrustpaymentsRouterData<&PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?;
+
+ let transaction_reference = item.router_data.request.connector_transaction_id.clone();
+
+ Ok(Self {
+ alias: auth.username.expose(),
+ version: TRUSTPAYMENTS_API_VERSION.to_string(),
+ request: vec![TrustpaymentsCaptureRequestData {
+ requesttypedescriptions: vec!["TRANSACTIONUPDATE".to_string()],
+ filter: TrustpaymentsFilter {
+ sitereference: vec![TrustpaymentsFilterValue {
+ value: auth.site_reference.expose(),
+ }],
+ transactionreference: vec![TrustpaymentsFilterValue {
+ value: transaction_reference,
+ }],
+ },
+ updates: TrustpaymentsCaptureUpdates {
+ settlestatus: TrustpaymentsSettleStatus::PendingSettlement,
+ },
+ }],
+ })
+ }
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsVoidRequest {
+ pub alias: String,
+ pub version: String,
+ pub request: Vec<TrustpaymentsVoidRequestData>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsVoidRequestData {
+ pub requesttypedescriptions: Vec<String>,
+ pub filter: TrustpaymentsFilter,
+ pub updates: TrustpaymentsVoidUpdates,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsVoidUpdates {
+ pub settlestatus: TrustpaymentsSettleStatus,
+}
+
+impl TryFrom<&PaymentsCancelRouterData> for TrustpaymentsVoidRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?;
+
+ let transaction_reference = item.request.connector_transaction_id.clone();
+
+ Ok(Self {
+ alias: auth.username.expose(),
+ version: TRUSTPAYMENTS_API_VERSION.to_string(),
+ request: vec![TrustpaymentsVoidRequestData {
+ requesttypedescriptions: vec!["TRANSACTIONUPDATE".to_string()],
+ filter: TrustpaymentsFilter {
+ sitereference: vec![TrustpaymentsFilterValue {
+ value: auth.site_reference.expose(),
+ }],
+ transactionreference: vec![TrustpaymentsFilterValue {
+ value: transaction_reference,
+ }],
+ },
+ updates: TrustpaymentsVoidUpdates {
+ settlestatus: TrustpaymentsSettleStatus::Voided,
+ },
+ }],
+ })
+ }
+}
+
+#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsRefundRequest {
- pub amount: StringMinorUnit,
+ pub alias: String,
+ pub version: String,
+ pub request: Vec<TrustpaymentsRefundRequestData>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsRefundRequestData {
+ pub requesttypedescriptions: Vec<String>,
+ pub sitereference: String,
+ pub parenttransactionreference: String,
+ pub baseamount: StringMinorUnit,
+ pub currencyiso3a: String,
}
impl<F> TryFrom<&TrustpaymentsRouterData<&RefundsRouterData<F>>> for TrustpaymentsRefundRequest {
@@ -145,50 +960,132 @@ impl<F> TryFrom<&TrustpaymentsRouterData<&RefundsRouterData<F>>> for Trustpaymen
fn try_from(
item: &TrustpaymentsRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
+ let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?;
+
+ let parent_transaction_reference =
+ item.router_data.request.connector_transaction_id.clone();
+
Ok(Self {
- amount: item.amount.to_owned(),
+ alias: auth.username.expose(),
+ version: TRUSTPAYMENTS_API_VERSION.to_string(),
+ request: vec![TrustpaymentsRefundRequestData {
+ requesttypedescriptions: vec!["REFUND".to_string()],
+ sitereference: auth.site_reference.expose(),
+ parenttransactionreference: parent_transaction_reference,
+ baseamount: item.amount.clone(),
+ currencyiso3a: item.router_data.request.currency.to_string(),
+ }],
})
}
}
-// Type definition for Refund Response
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsSyncRequest {
+ pub alias: String,
+ pub version: String,
+ pub request: Vec<TrustpaymentsSyncRequestData>,
+}
-#[allow(dead_code)]
-#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
-pub enum RefundStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsSyncRequestData {
+ pub requesttypedescriptions: Vec<String>,
+ pub filter: TrustpaymentsFilter,
}
-impl From<RefundStatus> for enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
- match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
- //TODO: Review mapping
- }
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsFilter {
+ pub sitereference: Vec<TrustpaymentsFilterValue>,
+ pub transactionreference: Vec<TrustpaymentsFilterValue>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsFilterValue {
+ pub value: String,
+}
+
+impl TryFrom<&PaymentsSyncRouterData> for TrustpaymentsSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
+ let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?;
+
+ let transaction_reference = item
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+
+ Ok(Self {
+ alias: auth.username.expose(),
+ version: TRUSTPAYMENTS_API_VERSION.to_string(),
+ request: vec![TrustpaymentsSyncRequestData {
+ requesttypedescriptions: vec!["TRANSACTIONQUERY".to_string()],
+ filter: TrustpaymentsFilter {
+ sitereference: vec![TrustpaymentsFilterValue {
+ value: auth.site_reference.expose(),
+ }],
+ transactionreference: vec![TrustpaymentsFilterValue {
+ value: transaction_reference,
+ }],
+ },
+ }],
+ })
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
-pub struct RefundResponse {
- id: String,
- status: RefundStatus,
+pub type TrustpaymentsRefundSyncRequest = TrustpaymentsSyncRequest;
+
+impl TryFrom<&RefundSyncRouterData> for TrustpaymentsRefundSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
+ let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?;
+
+ let refund_transaction_reference = item
+ .request
+ .get_connector_refund_id()
+ .change_context(errors::ConnectorError::MissingConnectorRefundID)?;
+
+ Ok(Self {
+ alias: auth.username.expose(),
+ version: TRUSTPAYMENTS_API_VERSION.to_string(),
+ request: vec![TrustpaymentsSyncRequestData {
+ requesttypedescriptions: vec!["TRANSACTIONQUERY".to_string()],
+ filter: TrustpaymentsFilter {
+ sitereference: vec![TrustpaymentsFilterValue {
+ value: auth.site_reference.expose(),
+ }],
+ transactionreference: vec![TrustpaymentsFilterValue {
+ value: refund_transaction_reference,
+ }],
+ },
+ }],
+ })
+ }
}
+pub type RefundResponse = TrustpaymentsPaymentsResponse;
+
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
+ let response_data = item
+ .response
+ .responses
+ .first()
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ let refund_id = response_data
+ .transactionreference
+ .clone()
+ .unwrap_or_else(|| "unknown".to_string());
+
+ let refund_status = response_data.get_refund_status();
+
Ok(Self {
response: Ok(RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ connector_refund_id: refund_id,
+ refund_status,
}),
..item.data
})
@@ -200,17 +1097,136 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouter
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
+ let response_data = item
+ .response
+ .responses
+ .first()
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ let refund_id = response_data
+ .transactionreference
+ .clone()
+ .unwrap_or_else(|| "unknown".to_string());
+
+ let refund_status = response_data.get_refund_status();
+
Ok(Self {
response: Ok(RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ connector_refund_id: refund_id,
+ refund_status,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsTokenizationRequest {
+ pub alias: String,
+ pub version: String,
+ pub request: Vec<TrustpaymentsTokenizationRequestData>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct TrustpaymentsTokenizationRequestData {
+ pub accounttypedescription: String,
+ pub requesttypedescriptions: Vec<String>,
+ pub sitereference: String,
+ pub pan: cards::CardNumber,
+ pub expirydate: Secret<String>,
+ pub securitycode: Secret<String>,
+ pub credentialsonfile: String,
+}
+
+impl
+ TryFrom<
+ &RouterData<
+ hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
+ hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
+ PaymentsResponseData,
+ >,
+ > for TrustpaymentsTokenizationRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &RouterData<
+ hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
+ hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?;
+
+ match &item.request.payment_method_data {
+ PaymentMethodData::Card(card_data) => Ok(Self {
+ alias: auth.username.expose(),
+ version: TRUSTPAYMENTS_API_VERSION.to_string(),
+ request: vec![TrustpaymentsTokenizationRequestData {
+ accounttypedescription: "ECOM".to_string(),
+ requesttypedescriptions: vec!["ACCOUNTCHECK".to_string()],
+ sitereference: auth.site_reference.expose(),
+ pan: card_data.card_number.clone(),
+ expirydate: card_data
+ .get_card_expiry_month_year_2_digit_with_delimiter("/".to_string())?,
+ securitycode: card_data.card_cvc.clone(),
+ credentialsonfile:
+ TrustpaymentsCredentialsOnFile::CardholderInitiatedTransaction.to_string(),
+ }],
}),
+ _ => Err(errors::ConnectorError::NotImplemented(
+ "Payment method not supported for tokenization".to_string(),
+ )
+ .into()),
+ }
+ }
+}
+
+pub type TrustpaymentsTokenizationResponse = TrustpaymentsPaymentsResponse;
+
+impl
+ TryFrom<
+ ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
+ TrustpaymentsTokenizationResponse,
+ hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
+ PaymentsResponseData,
+ >,
+ >
+ for RouterData<
+ hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
+ hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
+ PaymentsResponseData,
+ >
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<
+ hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
+ TrustpaymentsTokenizationResponse,
+ hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let response_data = item
+ .response
+ .responses
+ .first()
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ let status = response_data.get_payment_status();
+ let token = response_data
+ .transactionreference
+ .clone()
+ .unwrap_or_else(|| "unknown".to_string());
+
+ Ok(Self {
+ status,
+ response: Ok(PaymentsResponseData::TokenizationResponse { token }),
..item.data
})
}
}
-//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct TrustpaymentsErrorResponse {
pub status_code: u16,
@@ -221,3 +1237,112 @@ pub struct TrustpaymentsErrorResponse {
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
}
+
+impl TrustpaymentsErrorResponse {
+ pub fn get_connector_error_type(&self) -> errors::ConnectorError {
+ let error_code: TrustpaymentsErrorCode =
+ serde_json::from_str(&format!("\"{}\"", self.code))
+ .unwrap_or(TrustpaymentsErrorCode::Unknown(self.code.clone()));
+
+ match error_code {
+ TrustpaymentsErrorCode::InvalidCredentials
+ | TrustpaymentsErrorCode::AuthenticationFailed
+ | TrustpaymentsErrorCode::InvalidSiteReference
+ | TrustpaymentsErrorCode::AccessDenied
+ | TrustpaymentsErrorCode::InvalidUsernameOrPassword
+ | TrustpaymentsErrorCode::AccountSuspended => {
+ errors::ConnectorError::InvalidConnectorConfig {
+ config: "authentication",
+ }
+ }
+ TrustpaymentsErrorCode::InvalidCardNumber
+ | TrustpaymentsErrorCode::InvalidExpiryDate
+ | TrustpaymentsErrorCode::InvalidSecurityCode
+ | TrustpaymentsErrorCode::InvalidCardType
+ | TrustpaymentsErrorCode::CardExpired
+ | TrustpaymentsErrorCode::InvalidAmountValue => {
+ errors::ConnectorError::InvalidDataFormat {
+ field_name: "payment_method_data",
+ }
+ }
+ TrustpaymentsErrorCode::InsufficientFunds
+ | TrustpaymentsErrorCode::CardDeclined
+ | TrustpaymentsErrorCode::CardRestricted
+ | TrustpaymentsErrorCode::InvalidMerchant
+ | TrustpaymentsErrorCode::TransactionNotPermitted
+ | TrustpaymentsErrorCode::ExceedsWithdrawalLimit
+ | TrustpaymentsErrorCode::SecurityViolation
+ | TrustpaymentsErrorCode::LostOrStolenCard
+ | TrustpaymentsErrorCode::SuspectedFraud
+ | TrustpaymentsErrorCode::ContactCardIssuer => {
+ errors::ConnectorError::FailedAtConnector {
+ message: self.message.clone(),
+ code: self.code.clone(),
+ }
+ }
+ TrustpaymentsErrorCode::GeneralProcessingError
+ | TrustpaymentsErrorCode::SystemError
+ | TrustpaymentsErrorCode::CommunicationError
+ | TrustpaymentsErrorCode::Timeout
+ | TrustpaymentsErrorCode::InvalidRequest => {
+ errors::ConnectorError::ProcessingStepFailed(None)
+ }
+ TrustpaymentsErrorCode::Processing => errors::ConnectorError::ProcessingStepFailed(
+ Some(bytes::Bytes::from("Transaction is being processed")),
+ ),
+ TrustpaymentsErrorCode::MissingRequiredField
+ | TrustpaymentsErrorCode::InvalidFieldFormat
+ | TrustpaymentsErrorCode::InvalidFieldValue
+ | TrustpaymentsErrorCode::FieldTooLong
+ | TrustpaymentsErrorCode::FieldTooShort
+ | TrustpaymentsErrorCode::InvalidCurrency
+ | TrustpaymentsErrorCode::InvalidAmount
+ | TrustpaymentsErrorCode::NoSearchableFilter => {
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "request_data",
+ }
+ }
+ TrustpaymentsErrorCode::Success => errors::ConnectorError::ProcessingStepFailed(Some(
+ bytes::Bytes::from("Unexpected success code in error response"),
+ )),
+ TrustpaymentsErrorCode::Unknown(_) => errors::ConnectorError::ProcessingStepFailed(
+ Some(bytes::Bytes::from(self.message.clone())),
+ ),
+ }
+ }
+}
+
+impl From<TrustpaymentsPaymentResponseData> for TrustpaymentsErrorResponse {
+ fn from(response: TrustpaymentsPaymentResponseData) -> Self {
+ let error_reason = response.get_error_reason();
+ Self {
+ status_code: if response.errorcode.is_success() {
+ 200
+ } else {
+ 400
+ },
+ code: response.errorcode.to_string(),
+ message: response.errormessage,
+ reason: error_reason,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ }
+ }
+}
+
+impl TrustpaymentsPaymentResponseData {
+ pub fn get_refund_status(&self) -> enums::RefundStatus {
+ match self.errorcode {
+ TrustpaymentsErrorCode::Success => match &self.settlestatus {
+ Some(TrustpaymentsSettleStatus::Settled) => enums::RefundStatus::Success,
+ Some(TrustpaymentsSettleStatus::PendingSettlement) => enums::RefundStatus::Pending,
+ Some(TrustpaymentsSettleStatus::ManualCapture) => enums::RefundStatus::Failure,
+ Some(TrustpaymentsSettleStatus::Voided) => enums::RefundStatus::Failure,
+ None => enums::RefundStatus::Success,
+ },
+ TrustpaymentsErrorCode::Processing => enums::RefundStatus::Pending,
+ _ => enums::RefundStatus::Failure,
+ }
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 01c42dfe63..f675f95e90 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -3905,11 +3905,8 @@ macro_rules! default_imp_for_new_connector_integration_frm {
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm!(
- connectors::Paysafe,
- connectors::Trustpayments,
connectors::Affirm,
connectors::Paytm,
- connectors::Vgs,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authipay,
@@ -3944,10 +3941,10 @@ default_imp_for_new_connector_integration_frm!(
connectors::Flexiti,
connectors::Forte,
connectors::Globepay,
- connectors::Hipay,
connectors::Gocardless,
connectors::Gpayments,
connectors::Helcim,
+ connectors::Hipay,
connectors::HyperswitchVault,
connectors::Hyperwallet,
connectors::Inespay,
@@ -3955,17 +3952,20 @@ default_imp_for_new_connector_integration_frm!(
connectors::Juspaythreedsserver,
connectors::Katapult,
connectors::Mpgs,
- connectors::Nomupay,
- connectors::Nordea,
- connectors::Novalnet,
+ connectors::Mollie,
+ connectors::Multisafepay,
connectors::Netcetera,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nmi,
- connectors::Payone,
+ connectors::Nomupay,
+ connectors::Nordea,
+ connectors::Novalnet,
connectors::Paybox,
connectors::Payeezy,
connectors::Payload,
+ connectors::Payone,
+ connectors::Paysafe,
connectors::Payu,
connectors::Peachpayments,
connectors::Phonepe,
@@ -3973,8 +3973,6 @@ default_imp_for_new_connector_integration_frm!(
connectors::Plaid,
connectors::Powertranz,
connectors::Prophetpay,
- connectors::Mollie,
- connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
@@ -3992,11 +3990,13 @@ default_imp_for_new_connector_integration_frm!(
connectors::Threedsecureio,
connectors::Thunes,
connectors::Tokenio,
+ connectors::Trustpayments,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
+ connectors::Vgs,
+ connectors::Volt,
connectors::Wise,
connectors::Worldline,
- connectors::Volt,
connectors::Worldpay,
connectors::Worldpayvantiv,
connectors::Worldpayxml,
@@ -4049,11 +4049,8 @@ macro_rules! default_imp_for_new_connector_integration_connector_authentication
}
default_imp_for_new_connector_integration_connector_authentication!(
- connectors::Paysafe,
- connectors::Trustpayments,
connectors::Affirm,
connectors::Paytm,
- connectors::Vgs,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authipay,
@@ -4099,15 +4096,18 @@ default_imp_for_new_connector_integration_connector_authentication!(
connectors::Juspaythreedsserver,
connectors::Katapult,
connectors::Mpgs,
- connectors::Nomupay,
- connectors::Nordea,
- connectors::Novalnet,
+ connectors::Mollie,
+ connectors::Multisafepay,
connectors::Netcetera,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Nomupay,
+ connectors::Nordea,
+ connectors::Novalnet,
connectors::Paybox,
connectors::Payeezy,
connectors::Payload,
+ connectors::Paysafe,
connectors::Payu,
connectors::Peachpayments,
connectors::Phonepe,
@@ -4115,13 +4115,11 @@ default_imp_for_new_connector_integration_connector_authentication!(
connectors::Plaid,
connectors::Powertranz,
connectors::Prophetpay,
- connectors::Mollie,
- connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
+ connectors::Recurly,
connectors::Redsys,
connectors::Riskified,
- connectors::Recurly,
connectors::Santander,
connectors::Shift4,
connectors::Sift,
@@ -4134,11 +4132,13 @@ default_imp_for_new_connector_integration_connector_authentication!(
connectors::Threedsecureio,
connectors::Thunes,
connectors::Tokenio,
+ connectors::Trustpayments,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
+ connectors::Vgs,
+ connectors::Volt,
connectors::Wise,
connectors::Worldline,
- connectors::Volt,
connectors::Worldpay,
connectors::Worldpayvantiv,
connectors::Worldpayxml,
@@ -4182,11 +4182,8 @@ macro_rules! default_imp_for_new_connector_integration_revenue_recovery {
}
default_imp_for_new_connector_integration_revenue_recovery!(
- connectors::Paysafe,
- connectors::Trustpayments,
connectors::Affirm,
connectors::Paytm,
- connectors::Vgs,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authipay,
@@ -4212,8 +4209,8 @@ default_imp_for_new_connector_integration_revenue_recovery!(
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Dwolla,
- connectors::Elavon,
connectors::Ebanx,
+ connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
@@ -4232,17 +4229,20 @@ default_imp_for_new_connector_integration_revenue_recovery!(
connectors::Juspaythreedsserver,
connectors::Katapult,
connectors::Mpgs,
- connectors::Nomupay,
- connectors::Nordea,
- connectors::Novalnet,
+ connectors::Mollie,
+ connectors::Multisafepay,
connectors::Netcetera,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nmi,
- connectors::Payone,
+ connectors::Nomupay,
+ connectors::Nordea,
+ connectors::Novalnet,
connectors::Paybox,
connectors::Payeezy,
connectors::Payload,
+ connectors::Payone,
+ connectors::Paysafe,
connectors::Payu,
connectors::Peachpayments,
connectors::Phonepe,
@@ -4250,8 +4250,6 @@ default_imp_for_new_connector_integration_revenue_recovery!(
connectors::Plaid,
connectors::Powertranz,
connectors::Prophetpay,
- connectors::Mollie,
- connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Redsys,
@@ -4268,11 +4266,13 @@ default_imp_for_new_connector_integration_revenue_recovery!(
connectors::Threedsecureio,
connectors::Thunes,
connectors::Tokenio,
+ connectors::Trustpayments,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
+ connectors::Vgs,
+ connectors::Volt,
connectors::Wise,
connectors::Worldline,
- connectors::Volt,
connectors::Worldpay,
connectors::Worldpayvantiv,
connectors::Worldpayxml,
diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs
index 511224e596..b12dd55a4c 100644
--- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs
+++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs
@@ -1590,6 +1590,10 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> {
vec![],
),
),
+ (
+ Connector::Trustpayments,
+ fields(vec![], vec![], card_basic()),
+ ),
(Connector::Tsys, fields(vec![], card_basic(), vec![])),
(
Connector::Wellsfargo,
diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs
index 5ff6937754..1c689f4eef 100644
--- a/crates/router/src/core/connector_validation.rs
+++ b/crates/router/src/core/connector_validation.rs
@@ -487,6 +487,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> {
trustpay::transformers::TrustpayAuthType::try_from(self.auth_type)?;
Ok(())
}
+ api_enums::Connector::Trustpayments => {
+ trustpayments::transformers::TrustpaymentsAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Tokenio => {
tokenio::transformers::TokenioAuthType::try_from(self.auth_type)?;
Ok(())
diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs
index 2333f1c8bc..400a13407e 100644
--- a/crates/router/src/types/api/connector_mapping.rs
+++ b/crates/router/src/types/api/connector_mapping.rs
@@ -440,6 +440,9 @@ impl ConnectorData {
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
+ enums::Connector::Trustpayments => Ok(ConnectorEnum::Old(Box::new(
+ connector::Trustpayments::new(),
+ ))),
enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))),
// enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new(
// connector::UnifiedAuthenticationService,
diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs
index d5480ab2c2..7290acb121 100644
--- a/crates/router/src/types/api/feature_matrix.rs
+++ b/crates/router/src/types/api/feature_matrix.rs
@@ -359,6 +359,9 @@ impl FeatureMatrixConnectorData {
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
+ enums::Connector::Trustpayments => Ok(ConnectorEnum::Old(Box::new(
+ connector::Trustpayments::new(),
+ ))),
enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))),
// enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new(
// connector::UnifiedAuthenticationService,
diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs
index 6bcec0681d..f931e1a0a8 100644
--- a/crates/router/src/types/connector_transformers.rs
+++ b/crates/router/src/types/connector_transformers.rs
@@ -142,6 +142,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
// api_enums::Connector::Thunes => Self::Thunes,
api_enums::Connector::Tokenio => Self::Tokenio,
api_enums::Connector::Trustpay => Self::Trustpay,
+ api_enums::Connector::Trustpayments => Self::Trustpayments,
api_enums::Connector::Tsys => Self::Tsys,
// api_enums::Connector::UnifiedAuthenticationService => {
// Self::UnifiedAuthenticationService
diff --git a/crates/router/tests/connectors/trustpayments.rs b/crates/router/tests/connectors/trustpayments.rs
index 7d07b825aa..3fc6239f1d 100644
--- a/crates/router/tests/connectors/trustpayments.rs
+++ b/crates/router/tests/connectors/trustpayments.rs
@@ -1,6 +1,7 @@
-use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
+use std::str::FromStr;
+
use masking::Secret;
-use router::types::{self, api, storage::enums};
+use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
@@ -13,7 +14,7 @@ impl utils::Connector for TrustpaymentsTest {
use router::connector::Trustpayments;
utils::construct_connector_data_old(
Box::new(Trustpayments::new()),
- types::Connector::Plaid,
+ types::Connector::Trustpayments,
api::GetToken::Connector,
None,
)
@@ -36,11 +37,58 @@ impl utils::Connector for TrustpaymentsTest {
static CONNECTOR: TrustpaymentsTest = TrustpaymentsTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
- None
+ Some(utils::PaymentInfo {
+ address: Some(types::PaymentAddress::new(
+ None,
+ None,
+ Some(hyperswitch_domain_models::address::Address {
+ address: Some(hyperswitch_domain_models::address::AddressDetails {
+ country: Some(common_enums::CountryAlpha2::US),
+ city: Some("New York".to_string()),
+ zip: Some(Secret::new("10001".to_string())),
+ line1: Some(Secret::new("123 Main St".to_string())),
+ line2: None,
+ line3: None,
+ state: Some(Secret::new("NY".to_string())),
+ first_name: Some(Secret::new("John".to_string())),
+ last_name: Some(Secret::new("Doe".to_string())),
+ origin_zip: None,
+ }),
+ phone: Some(hyperswitch_domain_models::address::PhoneDetails {
+ number: Some(Secret::new("1234567890".to_string())),
+ country_code: Some("+1".to_string()),
+ }),
+ email: None,
+ }),
+ None,
+ )),
+ ..Default::default()
+ })
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
- None
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
+ card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
+ card_exp_month: Secret::new("12".to_string()),
+ card_exp_year: Secret::new("2025".to_string()),
+ card_cvc: Secret::new("123".to_string()),
+ card_issuer: None,
+ card_network: None,
+ card_type: None,
+ card_issuing_country: None,
+ bank_code: None,
+ nick_name: None,
+ card_holder_name: Some(Secret::new("John Doe".to_string())),
+ co_badged_card_data: None,
+ }),
+ confirm: true,
+ amount: 100,
+ minor_amount: common_utils::types::MinorUnit::new(100),
+ currency: enums::Currency::USD,
+ capture_method: Some(enums::CaptureMethod::Manual),
+ ..utils::PaymentAuthorizeType::default().0
+ })
}
// Cards Positive Tests
@@ -303,7 +351,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: PaymentMethodData::Card(Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -325,7 +373,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: PaymentMethodData::Card(Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -347,7 +395,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: PaymentMethodData::Card(Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/cypress-tests/cypress/e2e/configs/Payment/TrustPayments.js b/cypress-tests/cypress/e2e/configs/Payment/TrustPayments.js
new file mode 100644
index 0000000000..d7437dfde3
--- /dev/null
+++ b/cypress-tests/cypress/e2e/configs/Payment/TrustPayments.js
@@ -0,0 +1,677 @@
+import { customerAcceptance } from "./Commons";
+
+const successfulNo3DSCardDetails = {
+ card_number: "4111111111111111", // TrustPayments Visa test card
+ card_exp_month: "12",
+ card_exp_year: "30",
+ card_holder_name: "John Doe",
+ card_cvc: "123",
+};
+
+const failedCardDetails = {
+ card_number: "5555666666662222", // Generic declined card
+ card_exp_month: "12",
+ card_exp_year: "30",
+ card_holder_name: "John Doe",
+ card_cvc: "123",
+};
+
+const singleUseMandateData = {
+ customer_acceptance: customerAcceptance,
+ mandate_type: {
+ single_use: {
+ amount: 8000,
+ currency: "USD",
+ },
+ },
+};
+
+const multiUseMandateData = {
+ customer_acceptance: customerAcceptance,
+ mandate_type: {
+ multi_use: {
+ amount: 8000,
+ currency: "USD",
+ },
+ },
+};
+
+// ===== MAIN CONNECTOR DETAILS =====
+
+export const connectorDetails = {
+ card_pm: {
+ // Basic payment intent
+ PaymentIntent: {
+ Request: {
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: null,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ setup_future_usage: null,
+ },
+ },
+ },
+
+ // Successful automatic capture
+ No3DSAutoCapture: {
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: null,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+
+ // Successful manual capture (requires capture)
+ No3DSManualCapture: {
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: null,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_capture",
+ },
+ },
+ },
+
+ // Failed payment - TrustPayments should handle card declines
+ No3DSFailPayment: {
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: failedCardDetails,
+ },
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: null,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "failed",
+ },
+ },
+ },
+
+ // Capture operation
+ Capture: {
+ Request: {
+ amount_to_capture: 6000,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ amount: 6000,
+ amount_capturable: 0,
+ amount_received: 6000,
+ },
+ },
+ },
+
+ // Partial capture
+ PartialCapture: {
+ Request: {
+ amount_to_capture: 2000,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "partially_captured",
+ amount: 6000,
+ },
+ },
+ },
+
+ // Full refund
+ Refund: {
+ Request: {
+ amount: 6000,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "pending",
+ },
+ },
+ },
+
+ // Partial refund
+ PartialRefund: {
+ Request: {
+ amount: 2000,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "pending",
+ },
+ },
+ },
+
+ // Refund sync
+ SyncRefund: {
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+
+ // Manual payment refund
+ manualPaymentRefund: {
+ Request: {
+ amount: 6000,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "pending",
+ },
+ },
+ },
+
+ // Manual payment partial refund
+ manualPaymentPartialRefund: {
+ Request: {
+ amount: 2000,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "pending",
+ },
+ },
+ },
+
+ // Void payment failure (trying to void already captured payment)
+ VoidPaymentFailure: {
+ Request: {
+ cancellation_reason: "merchant_request",
+ },
+ Response: {
+ status: 400,
+ body: {
+ error: {
+ type: "invalid_request_error",
+ code: "processing_error",
+ message:
+ "You cannot cancel this PaymentIntent because it has a status of succeeded.",
+ },
+ },
+ },
+ },
+
+ // Void after confirm (manual capture scenario)
+ VoidAfterConfirm: {
+ Request: {
+ cancellation_reason: "customer_request",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "cancelled",
+ },
+ },
+ },
+
+ // Void payment in early state
+ Void: {
+ Request: {},
+ Response: {
+ status: 200,
+ body: {
+ status: "cancelled",
+ },
+ },
+ },
+
+ // Payment sync
+ SyncPayment: {
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+
+ // Payment with shipping cost
+ PaymentIntentWithShippingCost: {
+ Request: {
+ currency: "USD",
+ shipping_cost: 50,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ shipping_cost: 50,
+ amount: 6000,
+ },
+ },
+ },
+
+ PaymentConfirmWithShippingCost: {
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ customer_acceptance: null,
+ setup_future_usage: null,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ shipping_cost: 50,
+ amount_received: 6050,
+ amount: 6000,
+ net_amount: 6050,
+ },
+ },
+ },
+
+ // ===== MANDATE SCENARIOS (NOT SUPPORTED - SKIP) =====
+
+ MandateSingleUseNo3DSAutoCapture: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ mandate_data: singleUseMandateData,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+
+ MandateSingleUseNo3DSManualCapture: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ mandate_data: singleUseMandateData,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_capture",
+ },
+ },
+ },
+
+ MandateMultiUseNo3DSAutoCapture: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ mandate_data: multiUseMandateData,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+
+ MandateMultiUseNo3DSManualCapture: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ mandate_data: multiUseMandateData,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_capture",
+ },
+ },
+ },
+ MITManualCapture: {
+ Configs: {
+ TRIGGER_SKIP: true, // Skip if TrustPayments doesn't support mandates
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ mandate_data: multiUseMandateData,
+ },
+ Response: {
+ status: 501,
+ body: {
+ error: {
+ type: "invalid_request_error",
+ code: "connector_error",
+ message: "Payment method not supported",
+ },
+ },
+ },
+ },
+
+ // ===== SAVE CARD SCENARIOS (NOT SUPPORTED - SKIP) =====
+
+ SaveCardUseNo3DSAutoCapture: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ setup_future_usage: "on_session",
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+
+ SaveCardUseNo3DSManualCapture: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ setup_future_usage: "on_session",
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 501,
+ body: {
+ error: {
+ type: "invalid_request_error",
+ code: "connector_error",
+ message: "Payment method not supported",
+ },
+ },
+ },
+ },
+
+ // ===== ZERO AUTH SCENARIOS (NOT SUPPORTED - SKIP) =====
+
+ ZeroAuthPaymentIntent: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ amount: 0,
+ setup_future_usage: "off_session",
+ currency: "USD",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ },
+ },
+ },
+
+ ZeroAuthConfirmPayment: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_type: "setup_mandate",
+ payment_method: "card",
+ payment_method_type: "credit",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ },
+ Response: {
+ status: 501,
+ body: {
+ error: {
+ type: "invalid_request_error",
+ code: "connector_error",
+ message: "Payment method not supported",
+ },
+ },
+ },
+ },
+
+ ZeroAuthMandate: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ setup_future_usage: "off_session",
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "processing",
+ },
+ },
+ },
+
+ // ===== MIT (MERCHANT INITIATED TRANSACTION) SCENARIOS (NOT SUPPORTED - SKIP) =====
+
+ MITAutoCapture: {
+ Configs: {
+ TRIGGER_SKIP: true, // Skip if Authipay doesn't support mandates
+ },
+ Request: {},
+ Response: {
+ status: 501,
+ body: {
+ error: {
+ type: "invalid_request_error",
+ code: "connector_error",
+ message: "Payment method not supported",
+ },
+ },
+ },
+ },
+
+ MITWithoutBillingAddress: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ billing: null,
+ },
+ Response: {
+ status: 501,
+ body: {
+ error: {
+ type: "invalid_request_error",
+ code: "connector_error",
+ message: "Payment method not supported",
+ },
+ },
+ },
+ },
+
+ // ===== OFF-SESSION SCENARIOS (NOT SUPPORTED - SKIP) =====
+
+ PaymentIntentOffSession: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ currency: "USD",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ },
+ },
+ },
+
+ SaveCardUseNo3DSAutoCaptureOffSession: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ setup_future_usage: "off_session",
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+
+ SaveCardUseNo3DSManualCaptureOffSession: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ setup_future_usage: "off_session",
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_capture",
+ },
+ },
+ },
+
+ // ===== PAYMENT METHOD SCENARIOS (NOT SUPPORTED - SKIP) =====
+
+ PaymentMethod: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_type: "credit",
+ payment_method_issuer: "Gpay",
+ payment_method_issuer_code: "jp_hdfc",
+ card: successfulNo3DSCardDetails,
+ },
+ Response: {
+ status: 501,
+ body: {
+ error: {
+ type: "invalid_request_error",
+ code: "connector_error",
+ message: "Payment method not supported",
+ },
+ },
+ },
+ },
+
+ PaymentMethodIdMandateNo3DSAutoCapture: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ mandate_data: null,
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+
+ PaymentMethodIdMandateNo3DSManualCapture: {
+ Configs: {
+ TRIGGER_SKIP: true,
+ },
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ currency: "USD",
+ mandate_data: null,
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_capture",
+ },
+ },
+ },
+ },
+};
diff --git a/cypress-tests/cypress/e2e/configs/Payment/Utils.js b/cypress-tests/cypress/e2e/configs/Payment/Utils.js
index 07cb0aa6ab..b486974e6c 100644
--- a/cypress-tests/cypress/e2e/configs/Payment/Utils.js
+++ b/cypress-tests/cypress/e2e/configs/Payment/Utils.js
@@ -55,6 +55,7 @@ import { connectorDetails as squareConnectorDetails } from "./Square.js";
import { connectorDetails as staxConnectorDetails } from "./Stax.js";
import { connectorDetails as stripeConnectorDetails } from "./Stripe.js";
import { connectorDetails as trustpayConnectorDetails } from "./Trustpay.js";
+import { connectorDetails as trustpaymentsConnectorDetails } from "./TrustPayments.js";
import { connectorDetails as tsysConnectorDetails } from "./Tsys.js";
import { connectorDetails as wellsfargoConnectorDetails } from "./WellsFargo.js";
import { connectorDetails as worldpayConnectorDetails } from "./WorldPay.js";
@@ -117,6 +118,7 @@ const connectorDetails = {
stax: staxConnectorDetails,
stripe: stripeConnectorDetails,
trustpay: trustpayConnectorDetails,
+ trustpayments: trustpaymentsConnectorDetails,
tsys: tsysConnectorDetails,
wellsfargo: wellsfargoConnectorDetails,
worldpay: worldpayConnectorDetails,