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): Remove Braintree SDK Flow support (#5264)

awasthi2161a0cb3e1eea
diff --git a/config/config.example.toml b/config/config.example.toml
index 7cbd655130..d01d67cc68 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -194,8 +194,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -543,8 +542,6 @@ adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamal
[bank_config.online_banking_thailand]
adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank"
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[applepay_decrypt_keys]
apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" # Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index be2d22d92a..16b715b7e7 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -34,8 +34,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -158,8 +157,6 @@ card.debit = { connector_list = "cybersource" } # Update Mandate sup
[network_transaction_id_supported_connectors]
connector_list = "stripe,adyen,cybersource"
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[payouts]
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index f265688487..6bf81d3242 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -38,8 +38,7 @@ bitpay.base_url = "https://bitpay.com"
bluesnap.base_url = "https://ws.bluesnap.com/"
bluesnap.secondary_base_url = "https://pay.bluesnap.com/"
boku.base_url = "https://country-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.braintree-api.com/graphql"
+braintree.base_url = "https://payments.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster14.api.cashtocode.com"
checkout.base_url = "https://api.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -155,8 +154,6 @@ bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # M
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[payouts]
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 146a9bb87f..e1e346a825 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -38,8 +38,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -158,8 +157,6 @@ card.debit = { connector_list = "cybersource" } # Update Mandate sup
[network_transaction_id_supported_connectors]
connector_list = "stripe,adyen,cybersource"
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[payouts]
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
diff --git a/config/development.toml b/config/development.toml
index 8888048ccf..1b82a36dc0 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -195,8 +195,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -579,8 +578,6 @@ merchant_ids_send_payment_id_as_connector_request_id = []
[payouts]
payout_eligibility = true
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[applepay_decrypt_keys]
apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index fa5ccaac0a..d893756b7b 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -123,8 +123,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -441,8 +440,6 @@ connector_list = "stripe,adyen,cybersource"
connector_list = "gocardless,stax,stripe"
payout_connector_list = "stripe,wise"
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[payment_method_auth]
redis_expiry = 900
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index fe15422a12..85b310397b 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -1,10 +1,14 @@
-pub mod braintree_graphql_transformers;
pub mod transformers;
-use std::{fmt::Debug, str::FromStr};
+use std::str::FromStr;
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
-use common_utils::{crypto, ext_traits::XmlExt, request::RequestContent};
+use common_utils::{
+ crypto,
+ ext_traits::XmlExt,
+ request::RequestContent,
+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
+};
use diesel_models::enums;
use error_stack::{report, Report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
@@ -37,19 +41,22 @@ use crate::{
utils::{self, BytesExt},
};
-#[derive(Debug, Clone)]
-pub struct Braintree;
-
-pub const BRAINTREE_VERSION: &str = "Braintree-Version";
-pub const BRAINTREE_VERSION_VALUE: &str = "2019-01-01";
-pub const BRAINTREE_API_VERSION: &str = "graphql_api";
+#[derive(Clone)]
+pub struct Braintree {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
+}
impl Braintree {
- pub fn is_braintree_graphql_version(&self, connector_api_version: &Option<String>) -> bool {
- *connector_api_version == Some(BRAINTREE_API_VERSION.to_string())
+ pub const fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMajorUnitForConnector,
+ }
}
}
+pub const BRAINTREE_VERSION: &str = "Braintree-Version";
+pub const BRAINTREE_VERSION_VALUE: &str = "2019-01-01";
+
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Braintree
where
Self: ConnectorIntegration<Flow, Request, Response>,
@@ -94,9 +101,11 @@ impl ConnectorCommon for Braintree {
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let auth = braintree::BraintreeAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let auth_key = format!("{}:{}", auth.public_key.peek(), auth.private_key.peek());
+ let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
- auth.auth_header.into_masked(),
+ auth_header.into_masked(),
)])
}
@@ -105,11 +114,13 @@ impl ConnectorCommon for Braintree {
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: Result<braintree::ErrorResponse, Report<common_utils::errors::ParsingError>> =
- res.response.parse_struct("Braintree Error Response");
+ let response: Result<
+ braintree::ErrorResponses,
+ Report<common_utils::errors::ParsingError>,
+ > = res.response.parse_struct("Braintree Error Response");
match response {
- Ok(braintree::ErrorResponse::BraintreeApiErrorResponse(response)) => {
+ Ok(braintree::ErrorResponses::BraintreeApiErrorResponse(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -139,7 +150,7 @@ impl ConnectorCommon for Braintree {
connector_transaction_id: None,
})
}
- Ok(braintree::ErrorResponse::BraintreeErrorResponse(response)) => {
+ Ok(braintree::ErrorResponses::BraintreeErrorResponse(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -205,109 +216,6 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for Braintree
{
- fn get_headers(
- &self,
- req: &types::PaymentsSessionRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsSessionType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
-
- fn get_content_type(&self) -> &'static str {
- "application/json"
- }
-
- fn get_url(
- &self,
- req: &types::PaymentsSessionRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(format!(
- "{}/merchants/{}/client_token",
- self.base_url(connectors),
- auth_type.merchant_id.peek(),
- ))
- }
-
- fn build_request(
- &self,
- req: &types::PaymentsSessionRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(None),
- false => {
- let request = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsSessionType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::PaymentsSessionType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsSessionType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- );
- Ok(request)
- }
- }
- }
-
- fn get_error_response(
- &self,
- res: types::Response,
- event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res, event_builder)
- }
-
- fn get_request_body(
- &self,
- req: &types::PaymentsSessionRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = braintree::BraintreeSessionRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
-
- fn handle_response(
- &self,
- data: &types::PaymentsSessionRouterData,
- event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> {
- let response: braintree::BraintreeSessionTokenResponse = res
- .response
- .parse_struct("braintree SessionTokenResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
}
impl api::PaymentToken for Braintree {}
@@ -336,12 +244,7 @@ impl
_req: &types::TokenizationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -349,7 +252,7 @@ impl
req: &types::TokenizationRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = braintree_graphql_transformers::BraintreeTokenRequest::try_from(req)?;
+ let connector_req = transformers::BraintreeTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -359,23 +262,18 @@ impl
req: &types::TokenizationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::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(),
- )),
- false => Ok(None),
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::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: &types::TokenizationRouterData,
@@ -385,7 +283,7 @@ impl
where
types::PaymentsResponseData: Clone,
{
- let response: braintree_graphql_transformers::BraintreeTokenResponse = res
+ let response: transformers::BraintreeTokenResponse = res
.response
.parse_struct("BraintreeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -442,11 +340,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version.clone();
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => Ok(vec![]),
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -455,23 +349,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
+ _req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = req.connector_api_version.clone();
- match self.is_braintree_graphql_version(&connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -479,28 +360,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version.clone();
- let connector_router_data =
- braintree_graphql_transformers::BraintreeRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.amount_to_capture,
- req,
- ))?;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreeCaptureRequest::try_from(
- &connector_router_data,
- )?;
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+ let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
+ let connector_req =
+ transformers::BraintreeCaptureRequest::try_from(&connector_router_data)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(errors::ConnectorError::NotImplemented(
- "get_request_body method".to_string(),
- )
- .into()),
- }
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -508,26 +377,19 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- false => Err(errors::ConnectorError::NotImplemented(
- "Capture flow not Implemented".to_string(),
- )
- .into()),
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
fn handle_response(
@@ -536,7 +398,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: braintree_graphql_transformers::BraintreeCaptureResponse = res
+ let response: transformers::BraintreeCaptureResponse = res
.response
.parse_struct("Braintree PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -566,28 +428,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsSyncType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -596,34 +437,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
+ _req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- let connector_payment_id = req
- .request
- .connector_transaction_id
- .get_connector_transaction_id()
- .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
- Ok(format!(
- "{}/merchants/{}/transactions/{connector_payment_id}",
- self.base_url(connectors),
- auth_type.merchant_id.peek()
- ))
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -631,16 +448,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
req: &types::PaymentsSyncRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreePSyncRequest::try_from(req)?;
+ let connector_req = transformers::BraintreePSyncRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(report!(errors::ConnectorError::RequestEncodingFailed)),
- }
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -648,31 +458,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::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(),
- )),
- false => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .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(),
- )),
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::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(),
+ ))
}
fn handle_response(
@@ -681,35 +477,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let response: braintree_graphql_transformers::BraintreePSyncResponse = res
- .response
- .parse_struct("Braintree PaymentSyncResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree::BraintreePaymentsResponse = res
- .response
- .parse_struct("Braintree PaymentsResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
+ let response: transformers::BraintreePSyncResponse = res
+ .response
+ .parse_struct("Braintree PaymentSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
fn get_error_response(
@@ -729,56 +507,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
- }
+ self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ _req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
-
- Ok(format!(
- "{}merchants/{}/transactions",
- self.base_url(connectors),
- auth_type.merchant_id.peek()
- ))
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn build_request(
@@ -808,27 +545,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- let connector_router_data =
- braintree_graphql_transformers::BraintreeRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.amount,
- req,
- ))?;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreePaymentsRequest::try_from(
- &connector_router_data,
- )?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => {
- let connector_req = braintree::BraintreePaymentsRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- }
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
+ let connector_req: transformers::BraintreePaymentsRequest =
+ transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
@@ -837,38 +562,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => match data.request.is_auto_capture()? {
- true => {
- let response: braintree_graphql_transformers::BraintreePaymentsResponse = res
- .response
- .parse_struct("Braintree PaymentsResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree_graphql_transformers::BraintreeAuthResponse = res
- .response
- .parse_struct("Braintree AuthResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- },
- false => {
- let response: braintree::BraintreePaymentsResponse = res
+ match data.request.is_auto_capture()? {
+ true => {
+ let response: transformers::BraintreePaymentsResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -880,6 +576,19 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
http_code: res.status_code,
})
}
+ false => {
+ let response: transformers::BraintreeAuthResponse = res
+ .response
+ .parse_struct("Braintree AuthResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
}
}
@@ -900,28 +609,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsVoidType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -930,30 +618,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
+ _req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(format!(
- "{}merchants/{}/transactions/{}/void",
- self.base_url(connectors),
- auth_type.merchant_id.peek(),
- req.request.connector_transaction_id
- ))
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn build_request(
@@ -979,15 +647,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
req: &types::PaymentsCancelRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreeCancelRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(report!(errors::ConnectorError::RequestEncodingFailed)),
- }
+ let connector_req = transformers::BraintreeCancelRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
@@ -996,37 +657,18 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let response: braintree_graphql_transformers::BraintreeCancelResponse = res
- .response
- .parse_struct("Braintree VoidResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree::BraintreePaymentsResponse = res
- .response
- .parse_struct("Braintree PaymentsVoidResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
+ let response: transformers::BraintreeCancelResponse = res
+ .response
+ .parse_struct("Braintree VoidResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
-
fn get_error_response(
&self,
res: types::Response,
@@ -1048,28 +690,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::RefundExecuteType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -1078,31 +699,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ _req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- let connector_payment_id = req.request.connector_transaction_id.clone();
- Ok(format!(
- "{}merchants/{}/transactions/{}",
- self.base_url(connectors),
- auth_type.merchant_id.peek(),
- connector_payment_id
- ))
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -1110,29 +710,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- let connector_router_data =
- braintree_graphql_transformers::BraintreeRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.refund_amount,
- req,
- ))?;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreeRefundRequest::try_from(
- connector_router_data,
- )?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => {
- let connector_req = braintree::BraintreeRefundRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- }
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
+ let connector_req = transformers::BraintreeRefundRequest::try_from(connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
-
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
@@ -1158,35 +744,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let response: braintree_graphql_transformers::BraintreeRefundResponse = res
- .response
- .parse_struct("Braintree RefundResponse")
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree::RefundResponse = res
- .response
- .parse_struct("Braintree RefundResponse")
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
+ let response: transformers::BraintreeRefundResponse = res
+ .response
+ .parse_struct("Braintree RefundResponse")
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
fn get_error_response(
@@ -1206,11 +774,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => Ok(vec![]),
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -1219,23 +783,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
+ _req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -1243,15 +794,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
req: &types::RefundSyncRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreeRSyncRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(report!(errors::ConnectorError::RequestEncodingFailed)),
- }
+ let connector_req = transformers::BraintreeRSyncRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -1259,21 +803,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
- .set_body(types::RefundSyncType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- false => Ok(None),
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
fn handle_response(
@@ -1285,35 +825,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
errors::ConnectorError,
> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let response: braintree_graphql_transformers::BraintreeRSyncResponse = res
- .response
- .parse_struct("Braintree RefundResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree::RefundResponse = res
- .response
- .parse_struct("Braintree RefundResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
+ let response: transformers::BraintreeRSyncResponse = res
+ .response
+ .parse_struct("Braintree RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
fn get_error_response(
&self,
@@ -1485,9 +1007,7 @@ impl api::IncomingWebhook for Braintree {
currency,
)?,
currency: dispute_data.currency_iso_code,
- dispute_stage: braintree_graphql_transformers::get_dispute_stage(
- dispute_data.kind.as_str(),
- )?,
+ dispute_stage: transformers::get_dispute_stage(dispute_data.kind.as_str())?,
connector_dispute_id: dispute_data.id,
connector_reason: dispute_data.reason,
connector_reason_code: dispute_data.reason_code,
@@ -1516,16 +1036,15 @@ fn get_matching_webhook_signature(
fn get_webhook_object_from_body(
body: &[u8],
-) -> CustomResult<braintree_graphql_transformers::BraintreeWebhookResponse, errors::ParsingError> {
- serde_urlencoded::from_bytes::<braintree_graphql_transformers::BraintreeWebhookResponse>(body)
- .change_context(errors::ParsingError::StructParseFailure(
- "BraintreeWebhookResponse",
- ))
+) -> CustomResult<transformers::BraintreeWebhookResponse, errors::ParsingError> {
+ serde_urlencoded::from_bytes::<transformers::BraintreeWebhookResponse>(body).change_context(
+ errors::ParsingError::StructParseFailure("BraintreeWebhookResponse"),
+ )
}
fn decode_webhook_payload(
payload: &[u8],
-) -> CustomResult<braintree_graphql_transformers::Notification, errors::ConnectorError> {
+) -> CustomResult<transformers::Notification, errors::ConnectorError> {
let decoded_response = consts::BASE64_ENGINE
.decode(payload)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
@@ -1534,7 +1053,7 @@ fn decode_webhook_payload(
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
xml_response
- .parse_xml::<braintree_graphql_transformers::Notification>()
+ .parse_xml::<transformers::Notification>()
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
@@ -1548,17 +1067,16 @@ impl services::ConnectorRedirectResponse for Braintree {
match action {
services::PaymentAction::PSync => match json_payload {
Some(payload) => {
- let redirection_response:braintree_graphql_transformers::BraintreeRedirectionResponse = serde_json::from_value(payload)
-
- .change_context(
- errors::ConnectorError::MissingConnectorRedirectionPayload {
- field_name: "redirection_response",
- },
- )?;
+ let redirection_response: transformers::BraintreeRedirectionResponse =
+ serde_json::from_value(payload).change_context(
+ errors::ConnectorError::MissingConnectorRedirectionPayload {
+ field_name: "redirection_response",
+ },
+ )?;
let braintree_payload =
- serde_json::from_str::<
- braintree_graphql_transformers::BraintreeThreeDsErrorResponse,
- >(&redirection_response.authentication_response);
+ serde_json::from_str::<transformers::BraintreeThreeDsErrorResponse>(
+ &redirection_response.authentication_response,
+ );
let (error_code, error_message) = match braintree_payload {
Ok(braintree_response_payload) => (
braintree_response_payload.code,
@@ -1597,62 +1115,33 @@ impl
req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => Err(errors::ConnectorError::NotImplemented(
- "get_headers method".to_string(),
- ))?,
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
+ _req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => Err(errors::ConnectorError::NotImplemented(
- "get_url method".to_string(),
- ))?,
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &types::PaymentsCompleteAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data =
- braintree_graphql_transformers::BraintreeRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.amount,
- req,
- ))?;
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreePaymentsRequest::try_from(
- &connector_router_data,
- )?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(errors::ConnectorError::NotImplemented(
- "get_request_body method".to_string(),
- ))?,
- }
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
+
+ let connector_req =
+ transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -1660,27 +1149,21 @@ impl
req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCompleteAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .attach_default_headers()
- .headers(types::PaymentsCompleteAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- false => Err(errors::ConnectorError::NotImplemented(
- "payment method".to_string(),
- ))?,
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
fn handle_response(
&self,
@@ -1691,7 +1174,7 @@ impl
match connector_utils::PaymentsCompleteAuthorizeRequestData::is_auto_capture(&data.request)?
{
true => {
- let response: braintree_graphql_transformers::BraintreeCompleteChargeResponse = res
+ let response: transformers::BraintreeCompleteChargeResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -1704,7 +1187,7 @@ impl
})
}
false => {
- let response: braintree_graphql_transformers::BraintreeCompleteAuthResponse = res
+ let response: transformers::BraintreeCompleteAuthResponse = res
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
deleted file mode 100644
index af50bd10ce..0000000000
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ /dev/null
@@ -1,1667 +0,0 @@
-use common_utils::pii;
-use error_stack::ResultExt;
-use masking::{ExposeInterface, Secret};
-use serde::{Deserialize, Serialize};
-use time::PrimitiveDateTime;
-
-use crate::{
- connector::utils::{
- self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
- RefundsRequestData, RouterData,
- },
- consts,
- core::errors,
- services,
- types::{self, api, domain, storage::enums, MandateReference},
- unimplemented_payment_method,
-};
-
-pub const CLIENT_TOKEN_MUTATION: &str = "mutation createClientToken($input: CreateClientTokenInput!) { createClientToken(input: $input) { clientToken}}";
-pub const TOKENIZE_CREDIT_CARD: &str = "mutation tokenizeCreditCard($input: TokenizeCreditCardInput!) { tokenizeCreditCard(input: $input) { clientMutationId paymentMethod { id } } }";
-pub const CHARGE_CREDIT_CARD_MUTATION: &str = "mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id legacyId createdAt amount { value currencyCode } status } } }";
-pub const AUTHORIZE_CREDIT_CARD_MUTATION: &str = "mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
-pub const CAPTURE_TRANSACTION_MUTATION: &str = "mutation captureTransaction($input: CaptureTransactionInput!) { captureTransaction(input: $input) { clientMutationId transaction { id legacyId amount { value currencyCode } status } } }";
-pub const VOID_TRANSACTION_MUTATION: &str = "mutation voidTransaction($input: ReverseTransactionInput!) { reverseTransaction(input: $input) { clientMutationId reversal { ... on Transaction { id legacyId amount { value currencyCode } status } } } }";
-pub const REFUND_TRANSACTION_MUTATION: &str = "mutation refundTransaction($input: RefundTransactionInput!) { refundTransaction(input: $input) {clientMutationId refund { id legacyId amount { value currencyCode } status } } }";
-pub const AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION: &str="mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
-pub const CHARGE_AND_VAULT_TRANSACTION_MUTATION: &str ="mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
-
-#[derive(Debug, Serialize)]
-pub struct BraintreeRouterData<T> {
- pub amount: String,
- pub router_data: T,
-}
-
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BraintreeRouterData<T> {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
- ) -> Result<Self, Self::Error> {
- let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
- Ok(Self {
- amount,
- router_data: item,
- })
- }
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentInput {
- payment_method_id: Secret<String>,
- transaction: TransactionBody,
-}
-
-#[derive(Debug, Serialize)]
-pub struct VariablePaymentInput {
- input: PaymentInput,
-}
-
-#[derive(Debug, Serialize)]
-pub struct CardPaymentRequest {
- query: String,
- variables: VariablePaymentInput,
-}
-
-#[derive(Debug, Serialize)]
-pub struct MandatePaymentRequest {
- query: String,
- variables: VariablePaymentInput,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(untagged)]
-pub enum BraintreePaymentsRequest {
- Card(CardPaymentRequest),
- CardThreeDs(BraintreeClientTokenRequest),
- Mandate(MandatePaymentRequest),
-}
-
-#[derive(Debug, Deserialize)]
-pub struct BraintreeMeta {
- merchant_account_id: Secret<String>,
- merchant_config_currency: enums::Currency,
-}
-
-impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
- let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConnectorConfig {
- config: "metadata",
- })?;
- Ok(metadata)
- }
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct RegularTransactionBody {
- amount: String,
- merchant_account_id: Secret<String>,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct VaultTransactionBody {
- amount: String,
- merchant_account_id: Secret<String>,
- vault_payment_method_after_transacting: TransactionTiming,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(untagged)]
-pub enum TransactionBody {
- Regular(RegularTransactionBody),
- Vault(VaultTransactionBody),
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TransactionTiming {
- when: String,
-}
-
-impl
- TryFrom<(
- &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- String,
- BraintreeMeta,
- )> for MandatePaymentRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- (item, connector_mandate_id, metadata): (
- &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- String,
- BraintreeMeta,
- ),
- ) -> Result<Self, Self::Error> {
- let (query, transaction_body) = (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
- false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Regular(RegularTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- }),
- );
- Ok(Self {
- query,
- variables: VariablePaymentInput {
- input: PaymentInput {
- payment_method_id: connector_mandate_id.into(),
- transaction: transaction_body,
- },
- },
- })
- }
-}
-
-impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
- for BraintreePaymentsRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConnectorConfig {
- config: "metadata",
- })?;
- utils::validate_currency(
- item.router_data.request.currency,
- Some(metadata.merchant_config_currency),
- )?;
- match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(_) => {
- if item.router_data.is_three_ds() {
- Ok(Self::CardThreeDs(BraintreeClientTokenRequest::try_from(
- metadata,
- )?))
- } else {
- Ok(Self::Card(CardPaymentRequest::try_from((item, metadata))?))
- }
- }
- domain::PaymentMethodData::MandatePayment => {
- let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "connector_mandate_id",
- },
- )?;
- Ok(Self::Mandate(MandatePaymentRequest::try_from((
- item,
- connector_mandate_id,
- metadata,
- ))?))
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("braintree"),
- )
- .into())
- }
- }
- }
-}
-
-impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
- for BraintreePaymentsRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
- match item.router_data.payment_method {
- api_models::enums::PaymentMethod::Card => {
- Ok(Self::Card(CardPaymentRequest::try_from(item)?))
- }
- api_models::enums::PaymentMethod::CardRedirect
- | api_models::enums::PaymentMethod::PayLater
- | api_models::enums::PaymentMethod::Wallet
- | api_models::enums::PaymentMethod::BankRedirect
- | api_models::enums::PaymentMethod::BankTransfer
- | api_models::enums::PaymentMethod::Crypto
- | api_models::enums::PaymentMethod::BankDebit
- | api_models::enums::PaymentMethod::Reward
- | api_models::enums::PaymentMethod::RealTimePayment
- | api_models::enums::PaymentMethod::Upi
- | api_models::enums::PaymentMethod::Voucher
- | api_models::enums::PaymentMethod::OpenBanking
- | api_models::enums::PaymentMethod::GiftCard => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message(
- "complete authorize flow",
- ),
- )
- .into())
- }
- }
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct AuthResponse {
- data: DataAuthResponse,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeAuthResponse {
- AuthResponse(Box<AuthResponse>),
- ClientTokenResponse(Box<ClientTokenResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeCompleteAuthResponse {
- AuthResponse(Box<AuthResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-struct PaymentMethodInfo {
- id: Secret<String>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TransactionAuthChargeResponseBody {
- id: String,
- status: BraintreePaymentStatus,
- payment_method: Option<PaymentMethodInfo>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DataAuthResponse {
- authorize_credit_card: AuthChargeCreditCard,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct AuthChargeCreditCard {
- transaction: TransactionAuthChargeResponseBody,
-}
-
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BraintreeAuthResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- BraintreeAuthResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeAuthResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreeAuthResponse::AuthResponse(auth_response) => {
- let transaction_data = auth_response.data.authorize_credit_card.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
- connector_mandate_id: Some(pm.id.clone().expose()),
- payment_method_id: None,
- }
- }),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- BraintreeAuthResponse::ClientTokenResponse(client_token_data) => Ok(Self {
- status: enums::AttemptStatus::AuthenticationPending,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(get_braintree_redirect_form(
- *client_token_data,
- item.data.get_payment_method_token()?,
- item.data.request.payment_method_data.clone(),
- )?),
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- }),
- }
- }
-}
-
-fn build_error_response<T>(
- response: &[ErrorDetails],
- http_code: u16,
-) -> Result<T, types::ErrorResponse> {
- let error_messages = response
- .iter()
- .map(|error| error.message.to_string())
- .collect::<Vec<String>>();
-
- let reason = match !error_messages.is_empty() {
- true => Some(error_messages.join(" ")),
- false => None,
- };
-
- get_error_response(
- response
- .first()
- .and_then(|err_details| err_details.extensions.as_ref())
- .and_then(|extensions| extensions.legacy_code.clone()),
- response
- .first()
- .map(|err_details| err_details.message.clone()),
- reason,
- http_code,
- )
-}
-
-fn get_error_response<T>(
- error_code: Option<String>,
- error_msg: Option<String>,
- error_reason: Option<String>,
- http_code: u16,
-) -> Result<T, types::ErrorResponse> {
- Err(types::ErrorResponse {
- code: error_code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
- message: error_msg.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
- reason: error_reason,
- status_code: http_code,
- attempt_status: None,
- connector_transaction_id: None,
- })
-}
-
-// Using Auth type from braintree/transformer.rs, need this in later time when we use graphql version
-// pub struct BraintreeAuthType {
-// pub(super) auth_header: String,
-// pub(super) merchant_id: Secret<String>,
-// }
-
-// impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType {
-// type Error = error_stack::Report<errors::ConnectorError>;
-// fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
-// if let types::ConnectorAuthType::SignatureKey {
-// api_key: public_key,
-// key1: merchant_id,
-// api_secret: private_key,
-// } = item
-// {
-// let auth_key = format!("{}:{}", public_key.peek(), private_key.peek());
-// let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
-// Ok(Self {
-// auth_header,
-// merchant_id: merchant_id.to_owned(),
-// })
-// } else {
-// Err(errors::ConnectorError::FailedToObtainAuthType)?
-// }
-// }
-// }
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum BraintreePaymentStatus {
- Authorized,
- Authorizing,
- AuthorizedExpired,
- Failed,
- ProcessorDeclined,
- GatewayRejected,
- Voided,
- Settling,
- Settled,
- SettlementPending,
- SettlementDeclined,
- SettlementConfirmed,
- SubmittedForSettlement,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct ErrorDetails {
- pub message: String,
- pub extensions: Option<AdditionalErrorDetails>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AdditionalErrorDetails {
- pub legacy_code: Option<String>,
-}
-
-impl From<BraintreePaymentStatus> for enums::AttemptStatus {
- fn from(item: BraintreePaymentStatus) -> Self {
- match item {
- BraintreePaymentStatus::Settling
- | BraintreePaymentStatus::Settled
- | BraintreePaymentStatus::SettlementConfirmed => Self::Charged,
- BraintreePaymentStatus::Authorizing => Self::Authorizing,
- BraintreePaymentStatus::AuthorizedExpired => Self::AuthorizationFailed,
- BraintreePaymentStatus::Failed
- | BraintreePaymentStatus::GatewayRejected
- | BraintreePaymentStatus::ProcessorDeclined
- | BraintreePaymentStatus::SettlementDeclined => Self::Failure,
- BraintreePaymentStatus::Authorized => Self::Authorized,
- BraintreePaymentStatus::Voided => Self::Voided,
- BraintreePaymentStatus::SubmittedForSettlement
- | BraintreePaymentStatus::SettlementPending => Self::Pending,
- }
- }
-}
-
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BraintreePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- BraintreePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreePaymentsResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors.clone(), item.http_code),
- ..item.data
- }),
- BraintreePaymentsResponse::PaymentsResponse(payment_response) => {
- let transaction_data = payment_response.data.charge_credit_card.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
- connector_mandate_id: Some(pm.id.clone().expose()),
- payment_method_id: None,
- }
- }),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- BraintreePaymentsResponse::ClientTokenResponse(client_token_data) => Ok(Self {
- status: enums::AttemptStatus::AuthenticationPending,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(get_braintree_redirect_form(
- *client_token_data,
- item.data.get_payment_method_token()?,
- item.data.request.payment_method_data.clone(),
- )?),
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- }),
- }
- }
-}
-
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BraintreeCompleteChargeResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- BraintreeCompleteChargeResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeCompleteChargeResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors.clone(), item.http_code),
- ..item.data
- }),
- BraintreeCompleteChargeResponse::PaymentsResponse(payment_response) => {
- let transaction_data = payment_response.data.charge_credit_card.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
- connector_mandate_id: Some(pm.id.clone().expose()),
- payment_method_id: None,
- }
- }),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BraintreeCompleteAuthResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- BraintreeCompleteAuthResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeCompleteAuthResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreeCompleteAuthResponse::AuthResponse(auth_response) => {
- let transaction_data = auth_response.data.authorize_credit_card.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
- connector_mandate_id: Some(pm.id.clone().expose()),
- payment_method_id: None,
- }
- }),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct PaymentsResponse {
- data: DataResponse,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreePaymentsResponse {
- PaymentsResponse(Box<PaymentsResponse>),
- ClientTokenResponse(Box<ClientTokenResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeCompleteChargeResponse {
- PaymentsResponse(Box<PaymentsResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DataResponse {
- charge_credit_card: AuthChargeCreditCard,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct RefundInputData {
- amount: String,
- merchant_account_id: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeRefundInput {
- transaction_id: String,
- refund: RefundInputData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeRefundVariables {
- input: BraintreeRefundInput,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeRefundRequest {
- query: String,
- variables: BraintreeRefundVariables,
-}
-
-impl<F> TryFrom<BraintreeRouterData<&types::RefundsRouterData<F>>> for BraintreeRefundRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: BraintreeRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConnectorConfig {
- config: "metadata",
- })?;
-
- utils::validate_currency(
- item.router_data.request.currency,
- Some(metadata.merchant_config_currency),
- )?;
- let query = REFUND_TRANSACTION_MUTATION.to_string();
- let variables = BraintreeRefundVariables {
- input: BraintreeRefundInput {
- transaction_id: item.router_data.request.connector_transaction_id.clone(),
- refund: RefundInputData {
- amount: item.amount,
- merchant_account_id: metadata.merchant_account_id,
- },
- },
- };
- Ok(Self { query, variables })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum BraintreeRefundStatus {
- SettlementPending,
- Settling,
- Settled,
- SubmittedForSettlement,
- Failed,
-}
-
-impl From<BraintreeRefundStatus> for enums::RefundStatus {
- fn from(item: BraintreeRefundStatus) -> Self {
- match item {
- BraintreeRefundStatus::Settled | BraintreeRefundStatus::Settling => Self::Success,
- BraintreeRefundStatus::SubmittedForSettlement
- | BraintreeRefundStatus::SettlementPending => Self::Pending,
- BraintreeRefundStatus::Failed => Self::Failure,
- }
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct BraintreeRefundTransactionBody {
- pub id: String,
- pub status: BraintreeRefundStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct BraintreeRefundTransaction {
- pub refund: BraintreeRefundTransactionBody,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeRefundResponseData {
- pub refund_transaction: BraintreeRefundTransaction,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-
-pub struct RefundResponse {
- pub data: BraintreeRefundResponseData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeRefundResponse {
- RefundResponse(Box<RefundResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, BraintreeRefundResponse>>
- for types::RefundsRouterData<api::Execute>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, BraintreeRefundResponse>,
- ) -> Result<Self, Self::Error> {
- Ok(Self {
- response: match item.response {
- BraintreeRefundResponse::ErrorResponse(error_response) => {
- build_error_response(&error_response.errors, item.http_code)
- }
- BraintreeRefundResponse::RefundResponse(refund_data) => {
- let refund_data = refund_data.data.refund_transaction.refund;
-
- Ok(types::RefundsResponseData {
- connector_refund_id: refund_data.id.clone(),
- refund_status: enums::RefundStatus::from(refund_data.status),
- })
- }
- },
- ..item.data
- })
- }
-}
-
-#[derive(Debug, Serialize)]
-pub struct BraintreeRSyncRequest {
- query: String,
-}
-
-impl TryFrom<&types::RefundSyncRouterData> for BraintreeRSyncRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta = utils::to_connector_meta_from_secret(
- item.connector_meta_data.clone(),
- )
- .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
- utils::validate_currency(
- item.request.currency,
- Some(metadata.merchant_config_currency),
- )?;
- let refund_id = item.request.get_connector_refund_id()?;
- let query = format!("query {{ search {{ refunds(input: {{ id: {{is: \"{}\"}} }}, first: 1) {{ edges {{ node {{ id status createdAt amount {{ value currencyCode }} orderId }} }} }} }} }}",refund_id);
-
- Ok(Self { query })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncNodeData {
- id: String,
- status: BraintreeRefundStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncEdgeData {
- node: RSyncNodeData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RefundData {
- edges: Vec<RSyncEdgeData>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncSearchData {
- refunds: RefundData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncResponseData {
- search: RSyncSearchData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncResponse {
- data: RSyncResponseData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeRSyncResponse {
- RSyncResponse(Box<RSyncResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, BraintreeRSyncResponse>>
- for types::RefundsRouterData<api::RSync>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, BraintreeRSyncResponse>,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeRSyncResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreeRSyncResponse::RSyncResponse(rsync_response) => {
- let edge_data = rsync_response
- .data
- .search
- .refunds
- .edges
- .first()
- .ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
- let connector_refund_id = &edge_data.node.id;
- let response = Ok(types::RefundsResponseData {
- connector_refund_id: connector_refund_id.to_string(),
- refund_status: enums::RefundStatus::from(edge_data.node.status.clone()),
- });
- Ok(Self {
- response,
- ..item.data
- })
- }
- }
- }
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CreditCardData {
- number: cards::CardNumber,
- expiration_year: Secret<String>,
- expiration_month: Secret<String>,
- cvv: Secret<String>,
- cardholder_name: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClientTokenInput {
- merchant_account_id: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct InputData {
- credit_card: CreditCardData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct InputClientTokenData {
- client_token: ClientTokenInput,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct VariableInput {
- input: InputData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct VariableClientTokenInput {
- input: InputClientTokenData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeTokenRequest {
- query: String,
- variables: VariableInput,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeClientTokenRequest {
- query: String,
- variables: VariableClientTokenInput,
-}
-
-impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
- match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(card_data) => {
- let query = TOKENIZE_CREDIT_CARD.to_string();
- let input = InputData {
- credit_card: CreditCardData {
- number: card_data.card_number,
- expiration_year: card_data.card_exp_year,
- expiration_month: card_data.card_exp_month,
- cvv: card_data.card_cvc,
- cardholder_name: item
- .get_optional_billing_full_name()
- .unwrap_or(Secret::new("".to_string())),
- },
- };
- Ok(Self {
- query,
- variables: VariableInput { input },
- })
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("braintree"),
- )
- .into())
- }
- }
- }
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct TokenizePaymentMethodData {
- id: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TokenizeCreditCardData {
- payment_method: TokenizePaymentMethodData,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClientToken {
- client_token: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TokenizeCreditCard {
- tokenize_credit_card: TokenizeCreditCardData,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClientTokenData {
- create_client_token: ClientToken,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct ClientTokenResponse {
- data: ClientTokenData,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct TokenResponse {
- data: TokenizeCreditCard,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct ErrorResponse {
- errors: Vec<ErrorDetails>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeTokenResponse {
- TokenResponse(Box<TokenResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BraintreeTokenResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<F, BraintreeTokenResponse, T, types::PaymentsResponseData>,
- ) -> Result<Self, Self::Error> {
- Ok(Self {
- response: match item.response {
- BraintreeTokenResponse::ErrorResponse(error_response) => {
- build_error_response(error_response.errors.as_ref(), item.http_code)
- }
-
- BraintreeTokenResponse::TokenResponse(token_response) => {
- Ok(types::PaymentsResponseData::TokenizationResponse {
- token: token_response
- .data
- .tokenize_credit_card
- .payment_method
- .id
- .expose()
- .clone(),
- })
- }
- },
- ..item.data
- })
- }
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CaptureTransactionBody {
- amount: String,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CaptureInputData {
- transaction_id: String,
- transaction: CaptureTransactionBody,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct VariableCaptureInput {
- input: CaptureInputData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeCaptureRequest {
- query: String,
- variables: VariableCaptureInput,
-}
-
-impl TryFrom<&BraintreeRouterData<&types::PaymentsCaptureRouterData>> for BraintreeCaptureRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BraintreeRouterData<&types::PaymentsCaptureRouterData>,
- ) -> Result<Self, Self::Error> {
- let query = CAPTURE_TRANSACTION_MUTATION.to_string();
- let variables = VariableCaptureInput {
- input: CaptureInputData {
- transaction_id: item.router_data.request.connector_transaction_id.clone(),
- transaction: CaptureTransactionBody {
- amount: item.amount.to_owned(),
- },
- },
- };
- Ok(Self { query, variables })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CaptureResponseTransactionBody {
- id: String,
- status: BraintreePaymentStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CaptureTransactionData {
- transaction: CaptureResponseTransactionBody,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CaptureResponseData {
- capture_transaction: CaptureTransactionData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CaptureResponse {
- data: CaptureResponseData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeCaptureResponse {
- CaptureResponse(Box<CaptureResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl TryFrom<types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>>
- for types::PaymentsCaptureRouterData
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeCaptureResponse::CaptureResponse(capture_data) => {
- let transaction_data = capture_data.data.capture_transaction.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- BraintreeCaptureResponse::ErrorResponse(error_data) => Ok(Self {
- response: build_error_response(&error_data.errors, item.http_code),
- ..item.data
- }),
- }
- }
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CancelInputData {
- transaction_id: String,
-}
-
-#[derive(Debug, Serialize)]
-pub struct VariableCancelInput {
- input: CancelInputData,
-}
-
-#[derive(Debug, Serialize)]
-pub struct BraintreeCancelRequest {
- query: String,
- variables: VariableCancelInput,
-}
-
-impl TryFrom<&types::PaymentsCancelRouterData> for BraintreeCancelRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
- let query = VOID_TRANSACTION_MUTATION.to_string();
- let variables = VariableCancelInput {
- input: CancelInputData {
- transaction_id: item.request.connector_transaction_id.clone(),
- },
- };
- Ok(Self { query, variables })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CancelResponseTransactionBody {
- id: String,
- status: BraintreePaymentStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CancelTransactionData {
- reversal: CancelResponseTransactionBody,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CancelResponseData {
- reverse_transaction: CancelTransactionData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CancelResponse {
- data: CancelResponseData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeCancelResponse {
- CancelResponse(Box<CancelResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BraintreeCancelResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<F, BraintreeCancelResponse, T, types::PaymentsResponseData>,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeCancelResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreeCancelResponse::CancelResponse(void_response) => {
- let void_data = void_response.data.reverse_transaction.reversal;
-
- let transaction_id = void_data.id;
- Ok(Self {
- status: enums::AttemptStatus::from(void_data.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_id),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
-#[derive(Debug, Serialize)]
-pub struct BraintreePSyncRequest {
- query: String,
-}
-
-impl TryFrom<&types::PaymentsSyncRouterData> for BraintreePSyncRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
- let transaction_id = item
- .request
- .connector_transaction_id
- .get_connector_transaction_id()
- .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
- let query = format!("query {{ search {{ transactions(input: {{ id: {{is: \"{}\"}} }}, first: 1) {{ edges {{ node {{ id status createdAt amount {{ value currencyCode }} orderId }} }} }} }} }}", transaction_id);
- Ok(Self { query })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct NodeData {
- id: String,
- status: BraintreePaymentStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct EdgeData {
- node: NodeData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct TransactionData {
- edges: Vec<EdgeData>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct SearchData {
- transactions: TransactionData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct PSyncResponseData {
- search: SearchData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreePSyncResponse {
- PSyncResponse(Box<PSyncResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct PSyncResponse {
- data: PSyncResponseData,
-}
-
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BraintreePSyncResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<F, BraintreePSyncResponse, T, types::PaymentsResponseData>,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreePSyncResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreePSyncResponse::PSyncResponse(psync_response) => {
- let edge_data = psync_response
- .data
- .search
- .transactions
- .edges
- .first()
- .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
- let transaction_id = &edge_data.node.id;
- Ok(Self {
- status: enums::AttemptStatus::from(edge_data.node.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- transaction_id.to_string(),
- ),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeThreeDsResponse {
- pub nonce: Secret<String>,
- pub liability_shifted: bool,
- pub liability_shift_possible: bool,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeThreeDsErrorResponse {
- pub code: String,
- pub message: String,
-}
-
-#[derive(Debug, Deserialize)]
-pub struct BraintreeRedirectionResponse {
- pub authentication_response: String,
-}
-
-impl TryFrom<BraintreeMeta> for BraintreeClientTokenRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(metadata: BraintreeMeta) -> Result<Self, Self::Error> {
- Ok(Self {
- query: CLIENT_TOKEN_MUTATION.to_owned(),
- variables: VariableClientTokenInput {
- input: InputClientTokenData {
- client_token: ClientTokenInput {
- merchant_account_id: metadata.merchant_account_id,
- },
- },
- },
- })
- }
-}
-
-impl
- TryFrom<(
- &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- BraintreeMeta,
- )> for CardPaymentRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- (item, metadata): (
- &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- BraintreeMeta,
- ),
- ) -> Result<Self, Self::Error> {
- let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
- (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
- false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Vault(VaultTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- vault_payment_method_after_transacting: TransactionTiming {
- when: "ALWAYS".to_string(),
- },
- }),
- )
- } else {
- (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
- false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Regular(RegularTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- }),
- )
- };
- Ok(Self {
- query,
- variables: VariablePaymentInput {
- input: PaymentInput {
- payment_method_id: match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(token) => token,
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
- unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"),
- )?,
- },
- transaction: transaction_body,
- },
- },
- })
- }
-}
-
-impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
- for CardPaymentRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConnectorConfig {
- config: "metadata",
- })?;
- utils::validate_currency(
- item.router_data.request.currency,
- Some(metadata.merchant_config_currency),
- )?;
- let payload_data = PaymentsCompleteAuthorizeRequestData::get_redirect_response_payload(
- &item.router_data.request,
- )?
- .expose();
- let redirection_response: BraintreeRedirectionResponse = serde_json::from_value(
- payload_data,
- )
- .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
- field_name: "redirection_response",
- })?;
- let three_ds_data = serde_json::from_str::<BraintreeThreeDsResponse>(
- &redirection_response.authentication_response,
- )
- .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
- field_name: "three_ds_data",
- })?;
-
- let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
- (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
- false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Vault(VaultTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- vault_payment_method_after_transacting: TransactionTiming {
- when: "ALWAYS".to_string(),
- },
- }),
- )
- } else {
- (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
- false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Regular(RegularTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- }),
- )
- };
- Ok(Self {
- query,
- variables: VariablePaymentInput {
- input: PaymentInput {
- payment_method_id: three_ds_data.nonce,
- transaction: transaction_body,
- },
- },
- })
- }
-}
-
-fn get_braintree_redirect_form(
- client_token_data: ClientTokenResponse,
- payment_method_token: types::PaymentMethodToken,
- card_details: domain::PaymentMethodData,
-) -> Result<services::RedirectForm, error_stack::Report<errors::ConnectorError>> {
- Ok(services::RedirectForm::Braintree {
- client_token: client_token_data
- .data
- .create_client_token
- .client_token
- .expose(),
- card_token: match payment_method_token {
- types::PaymentMethodToken::Token(token) => token.expose(),
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(unimplemented_payment_method!(
- "Apple Pay",
- "Simplified",
- "Braintree"
- ))?,
- },
- bin: match card_details {
- domain::PaymentMethodData::Card(card_details) => {
- card_details.card_number.get_card_isin()
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => Err(
- errors::ConnectorError::NotImplemented("given payment method".to_owned()),
- )?,
- },
- })
-}
-
-#[derive(Debug, Deserialize)]
-pub struct BraintreeWebhookResponse {
- pub bt_signature: String,
- pub bt_payload: String,
-}
-
-#[derive(Debug, Deserialize, Serialize)]
-#[serde(rename_all = "kebab-case")]
-pub struct Notification {
- pub kind: String, // xml parse only string to fields
- pub timestamp: String,
- pub dispute: Option<BraintreeDisputeData>,
-}
-impl types::transformers::ForeignFrom<&str> for api_models::webhooks::IncomingWebhookEvent {
- fn foreign_from(status: &str) -> Self {
- match status {
- "dispute_opened" => Self::DisputeOpened,
- "dispute_lost" => Self::DisputeLost,
- "dispute_won" => Self::DisputeWon,
- "dispute_accepted" | "dispute_auto_accepted" => Self::DisputeAccepted,
- "dispute_expired" => Self::DisputeExpired,
- "dispute_disputed" => Self::DisputeChallenged,
- _ => Self::EventNotSupported,
- }
- }
-}
-
-#[derive(Debug, Deserialize, Serialize)]
-pub struct BraintreeDisputeData {
- pub amount_disputed: i64,
- pub amount_won: Option<String>,
- pub case_number: Option<String>,
- pub chargeback_protection_level: Option<String>,
- pub currency_iso_code: String,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub created_at: Option<PrimitiveDateTime>,
- pub evidence: Option<DisputeEvidence>,
- pub id: String,
- pub kind: String, // xml parse only string to fields
- pub status: String,
- pub reason: Option<String>,
- pub reason_code: Option<String>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub updated_at: Option<PrimitiveDateTime>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub reply_by_date: Option<PrimitiveDateTime>,
- pub transaction: DisputeTransaction,
-}
-
-#[derive(Debug, Deserialize, Serialize)]
-pub struct DisputeTransaction {
- pub amount: String,
- pub id: String,
-}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct DisputeEvidence {
- pub comment: String,
- pub id: Secret<String>,
- pub created_at: Option<PrimitiveDateTime>,
- pub url: url::Url,
-}
-
-pub(crate) fn get_dispute_stage(code: &str) -> Result<enums::DisputeStage, errors::ConnectorError> {
- match code {
- "CHARGEBACK" => Ok(enums::DisputeStage::Dispute),
- "PRE_ARBITATION" => Ok(enums::DisputeStage::PreArbitration),
- "RETRIEVAL" => Ok(enums::DisputeStage::PreDispute),
- _ => Err(errors::ConnectorError::WebhookBodyDecodingFailed),
- }
-}
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index 717c4afc19..8a4ce8126d 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -1,175 +1,308 @@
-use api_models::payments;
-use base64::Engine;
-use masking::{ExposeInterface, PeekInterface, Secret};
+use common_utils::{pii, types::StringMajorUnit};
+use error_stack::ResultExt;
+use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
+use time::PrimitiveDateTime;
use crate::{
- connector::utils::{self},
+ connector::utils::{
+ self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
+ RefundsRequestData, RouterData,
+ },
consts,
core::errors,
- types::{self, api, domain, storage::enums},
+ services,
+ types::{self, api, domain, storage::enums, MandateReference},
+ unimplemented_payment_method,
};
+pub const CHANNEL_CODE: &str = "HyperSwitchBT_Ecom";
+pub const CLIENT_TOKEN_MUTATION: &str = "mutation createClientToken($input: CreateClientTokenInput!) { createClientToken(input: $input) { clientToken}}";
+pub const TOKENIZE_CREDIT_CARD: &str = "mutation tokenizeCreditCard($input: TokenizeCreditCardInput!) { tokenizeCreditCard(input: $input) { clientMutationId paymentMethod { id } } }";
+pub const CHARGE_CREDIT_CARD_MUTATION: &str = "mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id legacyId createdAt amount { value currencyCode } status } } }";
+pub const AUTHORIZE_CREDIT_CARD_MUTATION: &str = "mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
+pub const CAPTURE_TRANSACTION_MUTATION: &str = "mutation captureTransaction($input: CaptureTransactionInput!) { captureTransaction(input: $input) { clientMutationId transaction { id legacyId amount { value currencyCode } status } } }";
+pub const VOID_TRANSACTION_MUTATION: &str = "mutation voidTransaction($input: ReverseTransactionInput!) { reverseTransaction(input: $input) { clientMutationId reversal { ... on Transaction { id legacyId amount { value currencyCode } status } } } }";
+pub const REFUND_TRANSACTION_MUTATION: &str = "mutation refundTransaction($input: RefundTransactionInput!) { refundTransaction(input: $input) {clientMutationId refund { id legacyId amount { value currencyCode } status } } }";
+pub const AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION: &str="mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
+pub const CHARGE_AND_VAULT_TRANSACTION_MUTATION: &str ="mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
+pub const TRANSACTION_QUERY: &str = "query($input: TransactionSearchInput!) { search { transactions(input: $input) { edges { node { id status } } } } }";
+pub const REFUND_QUERY: &str = "query($input: RefundSearchInput!) { search { refunds(input: $input, first: 1) { edges { node { id status createdAt amount { value currencyCode } orderId } } } } }";
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct DeviceData;
+pub type CardPaymentRequest = GenericBraintreeRequest<VariablePaymentInput>;
+pub type MandatePaymentRequest = GenericBraintreeRequest<VariablePaymentInput>;
+pub type BraintreeClientTokenRequest = GenericBraintreeRequest<VariableClientTokenInput>;
+pub type BraintreeTokenRequest = GenericBraintreeRequest<VariableInput>;
+pub type BraintreeCaptureRequest = GenericBraintreeRequest<VariableCaptureInput>;
+pub type BraintreeRefundRequest = GenericBraintreeRequest<BraintreeRefundVariables>;
+pub type BraintreePSyncRequest = GenericBraintreeRequest<PSyncInput>;
+pub type BraintreeRSyncRequest = GenericBraintreeRequest<RSyncInput>;
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct PaymentOptions {
- submit_for_settlement: bool,
+pub type BraintreeRefundResponse = GenericBraintreeResponse<RefundResponse>;
+pub type BraintreeCaptureResponse = GenericBraintreeResponse<CaptureResponse>;
+pub type BraintreePSyncResponse = GenericBraintreeResponse<PSyncResponse>;
+
+pub type VariablePaymentInput = GenericVariableInput<PaymentInput>;
+pub type VariableClientTokenInput = GenericVariableInput<InputClientTokenData>;
+pub type VariableInput = GenericVariableInput<InputData>;
+pub type VariableCaptureInput = GenericVariableInput<CaptureInputData>;
+pub type BraintreeRefundVariables = GenericVariableInput<BraintreeRefundInput>;
+pub type PSyncInput = GenericVariableInput<TransactionSearchInput>;
+pub type RSyncInput = GenericVariableInput<RefundSearchInput>;
+
+#[derive(Debug, Clone, Serialize)]
+pub struct GenericBraintreeRequest<T> {
+ query: String,
+ variables: T,
+}
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum GenericBraintreeResponse<T> {
+ SuccessResponse(Box<T>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+#[derive(Debug, Clone, Serialize)]
+pub struct GenericVariableInput<T> {
+ input: T,
}
-#[derive(Debug, Deserialize)]
-pub struct BraintreeMeta {
- merchant_account_id: Option<Secret<String>>,
- merchant_config_currency: Option<enums::Currency>,
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+
+pub struct BraintreeApiErrorResponse {
+ pub api_error_response: ApiErrorResponse,
}
-#[derive(Debug, Serialize, Eq, PartialEq)]
-pub struct BraintreePaymentsRequest {
- transaction: TransactionBody,
+#[derive(Debug, Deserialize, Serialize)]
+
+pub struct ErrorsObject {
+ pub errors: Vec<ErrorObject>,
+
+ pub transaction: Option<TransactionError>,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct BraintreeApiVersion {
- version: String,
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+
+pub struct TransactionError {
+ pub errors: Vec<ErrorObject>,
+ pub credit_card: Option<CreditCardError>,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct BraintreeSessionRequest {
- client_token: BraintreeApiVersion,
+#[derive(Debug, Deserialize, Serialize)]
+pub struct CreditCardError {
+ pub errors: Vec<ErrorObject>,
+}
+#[derive(Debug, Serialize)]
+pub struct BraintreeRouterData<T> {
+ pub amount: StringMajorUnit,
+ pub router_data: T,
}
-impl TryFrom<&types::PaymentsSessionRouterData> for BraintreeSessionRequest {
+impl<T> TryFrom<(StringMajorUnit, T)> for BraintreeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(_item.connector_meta_data.clone())?;
-
- utils::validate_currency(_item.request.currency, metadata.merchant_config_currency)?;
+ fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
- client_token: BraintreeApiVersion {
- version: "2".to_string(),
- },
+ amount,
+ router_data: item,
})
}
}
+#[derive(Debug, Deserialize, Serialize)]
+pub struct ErrorObject {
+ pub code: String,
+ pub message: String,
+}
-#[derive(Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct TransactionBody {
- amount: String,
- merchant_account_id: Option<Secret<String>>,
- device_data: DeviceData,
- options: PaymentOptions,
- #[serde(flatten)]
- payment_method_data_type: PaymentMethodType,
- #[serde(rename = "type")]
- kind: String,
-}
-
-#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct BraintreeErrorResponse {
+ pub errors: String,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-#[serde(tag = "type")]
-pub enum PaymentMethodType {
- CreditCard(Card),
- PaymentMethodNonce(Nonce),
+#[serde(untagged)]
+
+pub enum ErrorResponses {
+ BraintreeApiErrorResponse(Box<BraintreeApiErrorResponse>),
+ BraintreeErrorResponse(Box<BraintreeErrorResponse>),
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct Nonce {
- payment_method_nonce: Secret<String>,
+#[derive(Debug, Deserialize, Serialize)]
+pub struct ApiErrorResponse {
+ pub message: String,
+ pub errors: ErrorsObject,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct Card {
- credit_card: CardDetails,
+pub struct BraintreeAuthType {
+ pub(super) public_key: Secret<String>,
+ pub(super) private_key: Secret<String>,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let types::ConnectorAuthType::SignatureKey {
+ api_key,
+ api_secret,
+ key1: _merchant_id,
+ } = item
+ {
+ Ok(Self {
+ public_key: api_key.to_owned(),
+ private_key: api_secret.to_owned(),
+ })
+ } else {
+ Err(errors::ConnectorError::FailedToObtainAuthType)?
+ }
+ }
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct CardDetails {
- number: cards::CardNumber,
- expiration_month: Secret<String>,
- expiration_year: Secret<String>,
- cvv: Secret<String>,
+pub struct PaymentInput {
+ payment_method_id: Secret<String>,
+ transaction: TransactionBody,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(untagged)]
+pub enum BraintreePaymentsRequest {
+ Card(CardPaymentRequest),
+ CardThreeDs(BraintreeClientTokenRequest),
+ Mandate(MandatePaymentRequest),
+}
+
+#[derive(Debug, Deserialize)]
+pub struct BraintreeMeta {
+ merchant_account_id: Secret<String>,
+ merchant_config_currency: enums::Currency,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest {
+impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.connector_meta_data.clone())?;
+ fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
+ let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+ Ok(metadata)
+ }
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RegularTransactionBody {
+ amount: StringMajorUnit,
+ merchant_account_id: Secret<String>,
+ channel: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultTransactionBody {
+ amount: StringMajorUnit,
+ merchant_account_id: Secret<String>,
+ vault_payment_method_after_transacting: TransactionTiming,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(untagged)]
+pub enum TransactionBody {
+ Regular(RegularTransactionBody),
+ Vault(VaultTransactionBody),
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TransactionTiming {
+ when: String,
+}
- utils::validate_currency(item.request.currency, metadata.merchant_config_currency)?;
- let submit_for_settlement = matches!(
- item.request.capture_method,
- Some(enums::CaptureMethod::Automatic) | None
+impl
+ TryFrom<(
+ &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ String,
+ BraintreeMeta,
+ )> for MandatePaymentRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, connector_mandate_id, metadata): (
+ &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ String,
+ BraintreeMeta,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (query, transaction_body) = (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
+ false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Regular(RegularTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ channel: CHANNEL_CODE.to_string(),
+ }),
);
- let merchant_account_id = metadata.merchant_account_id;
- let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?;
- let device_data = DeviceData {};
- let options = PaymentOptions {
- submit_for_settlement,
- };
- let kind = "sale".to_string();
-
- let payment_method_data_type = match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => Ok(PaymentMethodType::CreditCard(Card {
- credit_card: CardDetails {
- number: ccard.card_number,
- expiration_month: ccard.card_exp_month,
- expiration_year: ccard.card_exp_year,
- cvv: ccard.card_cvc,
+ Ok(Self {
+ query,
+ variables: VariablePaymentInput {
+ input: PaymentInput {
+ payment_method_id: connector_mandate_id.into(),
+ transaction: transaction_body,
},
- })),
- domain::PaymentMethodData::Wallet(ref wallet_data) => {
- Ok(PaymentMethodType::PaymentMethodNonce(Nonce {
- payment_method_nonce: match wallet_data {
- domain::WalletData::PaypalSdk(wallet_data) => {
- Ok(wallet_data.token.to_owned())
- }
- domain::WalletData::ApplePay(_)
- | domain::WalletData::GooglePay(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalRedirect(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::Mifinity(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("braintree"),
- ))
- }
- }?
- .into(),
- }))
+ },
+ })
+ }
+}
+
+impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
+ for BraintreePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let metadata: BraintreeMeta =
+ utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+ utils::validate_currency(
+ item.router_data.request.currency,
+ Some(metadata.merchant_config_currency),
+ )?;
+ match item.router_data.request.payment_method_data.clone() {
+ domain::PaymentMethodData::Card(_) => {
+ if item.router_data.is_three_ds() {
+ Ok(Self::CardThreeDs(BraintreeClientTokenRequest::try_from(
+ metadata,
+ )?))
+ } else {
+ Ok(Self::Card(CardPaymentRequest::try_from((item, metadata))?))
+ }
+ }
+ domain::PaymentMethodData::MandatePayment => {
+ let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_mandate_id",
+ },
+ )?;
+ Ok(Self::Mandate(MandatePaymentRequest::try_from((
+ item,
+ connector_mandate_id,
+ metadata,
+ ))?))
}
- domain::PaymentMethodData::PayLater(_)
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
| domain::PaymentMethodData::BankRedirect(_)
| domain::PaymentMethodData::BankDebit(_)
| domain::PaymentMethodData::BankTransfer(_)
| domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::MandatePayment
| domain::PaymentMethodData::Reward
| domain::PaymentMethodData::RealTimePayment(_)
| domain::PaymentMethodData::Upi(_)
@@ -179,74 +312,253 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest {
| domain::PaymentMethodData::CardToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
- ))
+ )
+ .into())
}
- }?;
- let braintree_transaction_body = TransactionBody {
- amount,
- merchant_account_id,
- device_data,
- options,
- payment_method_data_type,
- kind,
- };
- Ok(Self {
- transaction: braintree_transaction_body,
- })
+ }
}
}
-pub struct BraintreeAuthType {
- pub(super) auth_header: String,
- pub(super) merchant_id: Secret<String>,
+impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
+ for BraintreePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.payment_method {
+ api_models::enums::PaymentMethod::Card => {
+ Ok(Self::Card(CardPaymentRequest::try_from(item)?))
+ }
+ api_models::enums::PaymentMethod::CardRedirect
+ | api_models::enums::PaymentMethod::PayLater
+ | api_models::enums::PaymentMethod::Wallet
+ | api_models::enums::PaymentMethod::BankRedirect
+ | api_models::enums::PaymentMethod::BankTransfer
+ | api_models::enums::PaymentMethod::Crypto
+ | api_models::enums::PaymentMethod::BankDebit
+ | api_models::enums::PaymentMethod::Reward
+ | api_models::enums::PaymentMethod::RealTimePayment
+ | api_models::enums::PaymentMethod::Upi
+ | api_models::enums::PaymentMethod::OpenBanking
+ | api_models::enums::PaymentMethod::Voucher
+ | api_models::enums::PaymentMethod::GiftCard => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message(
+ "complete authorize flow",
+ ),
+ )
+ .into())
+ }
+ }
+ }
}
-impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType {
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct AuthResponse {
+ data: DataAuthResponse,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeAuthResponse {
+ AuthResponse(Box<AuthResponse>),
+ ClientTokenResponse(Box<ClientTokenResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeCompleteAuthResponse {
+ AuthResponse(Box<AuthResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+struct PaymentMethodInfo {
+ id: Secret<String>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TransactionAuthChargeResponseBody {
+ id: String,
+ status: BraintreePaymentStatus,
+ payment_method: Option<PaymentMethodInfo>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DataAuthResponse {
+ authorize_credit_card: AuthChargeCreditCard,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct AuthChargeCreditCard {
+ transaction: TransactionAuthChargeResponseBody,
+}
+
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BraintreeAuthResponse,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::SignatureKey {
- api_key: public_key,
- key1: merchant_id,
- api_secret: private_key,
- } = item
- {
- let auth_key = format!("{}:{}", public_key.peek(), private_key.peek());
- let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
- Ok(Self {
- auth_header,
- merchant_id: merchant_id.to_owned(),
- })
- } else {
- Err(errors::ConnectorError::FailedToObtainAuthType)?
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BraintreeAuthResponse,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeAuthResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
+ }),
+ BraintreeAuthResponse::AuthResponse(auth_response) => {
+ let transaction_data = auth_response.data.authorize_credit_card.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
+ MandateReference {
+ connector_mandate_id: Some(pm.id.clone().expose()),
+ payment_method_id: None,
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ BraintreeAuthResponse::ClientTokenResponse(client_token_data) => Ok(Self {
+ status: enums::AttemptStatus::AuthenticationPending,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data: Some(get_braintree_redirect_form(
+ *client_token_data,
+ item.data.get_payment_method_token()?,
+ item.data.request.payment_method_data.clone(),
+ )?),
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ }),
}
}
}
-#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq, Serialize)]
-#[serde(rename_all = "snake_case")]
+fn build_error_response<T>(
+ response: &[ErrorDetails],
+ http_code: u16,
+) -> Result<T, types::ErrorResponse> {
+ let error_messages = response
+ .iter()
+ .map(|error| error.message.to_string())
+ .collect::<Vec<String>>();
+
+ let reason = match !error_messages.is_empty() {
+ true => Some(error_messages.join(" ")),
+ false => None,
+ };
+
+ get_error_response(
+ response
+ .first()
+ .and_then(|err_details| err_details.extensions.as_ref())
+ .and_then(|extensions| extensions.legacy_code.clone()),
+ response
+ .first()
+ .map(|err_details| err_details.message.clone()),
+ reason,
+ http_code,
+ )
+}
+
+fn get_error_response<T>(
+ error_code: Option<String>,
+ error_msg: Option<String>,
+ error_reason: Option<String>,
+ http_code: u16,
+) -> Result<T, types::ErrorResponse> {
+ Err(types::ErrorResponse {
+ code: error_code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
+ message: error_msg.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
+ reason: error_reason,
+ status_code: http_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, strum::Display)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BraintreePaymentStatus {
- Succeeded,
- Failed,
Authorized,
+ Authorizing,
AuthorizedExpired,
+ Failed,
ProcessorDeclined,
GatewayRejected,
Voided,
- SubmittedForSettlement,
- #[default]
Settling,
Settled,
SettlementPending,
SettlementDeclined,
SettlementConfirmed,
+ SubmittedForSettlement,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct ErrorDetails {
+ pub message: String,
+ pub extensions: Option<AdditionalErrorDetails>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AdditionalErrorDetails {
+ pub legacy_code: Option<String>,
}
impl From<BraintreePaymentStatus> for enums::AttemptStatus {
fn from(item: BraintreePaymentStatus) -> Self {
match item {
- BraintreePaymentStatus::Succeeded
- | BraintreePaymentStatus::Settling
- | BraintreePaymentStatus::Settled => Self::Charged,
+ BraintreePaymentStatus::Settling
+ | BraintreePaymentStatus::Settled
+ | BraintreePaymentStatus::SettlementConfirmed => Self::Charged,
+ BraintreePaymentStatus::Authorizing => Self::Authorizing,
BraintreePaymentStatus::AuthorizedExpired => Self::AuthorizationFailed,
BraintreePaymentStatus::Failed
| BraintreePaymentStatus::GatewayRejected
@@ -255,234 +567,1221 @@ impl From<BraintreePaymentStatus> for enums::AttemptStatus {
BraintreePaymentStatus::Authorized => Self::Authorized,
BraintreePaymentStatus::Voided => Self::Voided,
BraintreePaymentStatus::SubmittedForSettlement
- | BraintreePaymentStatus::SettlementPending
- | BraintreePaymentStatus::SettlementConfirmed => Self::Pending,
+ | BraintreePaymentStatus::SettlementPending => Self::Pending,
}
}
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BraintreePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BraintreePaymentsResponse,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
BraintreePaymentsResponse,
- T,
+ types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let id = item.response.transaction.id.clone();
- Ok(Self {
- status: enums::AttemptStatus::from(item.response.transaction.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(id.clone()),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: Some(id),
- incremental_authorization_allowed: None,
- charge_id: None,
+ match item.response {
+ BraintreePaymentsResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors.clone(), item.http_code),
+ ..item.data
}),
- ..item.data
- })
+ BraintreePaymentsResponse::PaymentsResponse(payment_response) => {
+ let transaction_data = payment_response.data.charge_credit_card.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
+ MandateReference {
+ connector_mandate_id: Some(pm.id.clone().expose()),
+ payment_method_id: None,
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ BraintreePaymentsResponse::ClientTokenResponse(client_token_data) => Ok(Self {
+ status: enums::AttemptStatus::AuthenticationPending,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data: Some(get_braintree_redirect_form(
+ *client_token_data,
+ item.data.get_payment_method_token()?,
+ item.data.request.payment_method_data.clone(),
+ )?),
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ }),
+ }
}
}
-impl<F, T>
+impl<F>
TryFrom<
- types::ResponseRouterData<F, BraintreeSessionTokenResponse, T, types::PaymentsResponseData>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+ types::ResponseRouterData<
+ F,
+ BraintreeCompleteChargeResponse,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
- BraintreeSessionTokenResponse,
- T,
+ BraintreeCompleteChargeResponse,
+ types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- Ok(Self {
- response: Ok(types::PaymentsResponseData::SessionResponse {
- session_token: api::SessionToken::Paypal(Box::new(
- payments::PaypalSessionTokenResponse {
- session_token: item.response.client_token.value.expose(),
- connector: "braintree".to_string(),
- sdk_next_action: payments::SdkNextAction {
- next_action: payments::NextActionCall::Confirm,
- },
- },
- )),
+ match item.response {
+ BraintreeCompleteChargeResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors.clone(), item.http_code),
+ ..item.data
}),
- ..item.data
- })
+ BraintreeCompleteChargeResponse::PaymentsResponse(payment_response) => {
+ let transaction_data = payment_response.data.charge_credit_card.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
+ MandateReference {
+ connector_mandate_id: Some(pm.id.clone().expose()),
+ payment_method_id: None,
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ }
}
}
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreePaymentsResponse {
- transaction: TransactionResponse,
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BraintreeCompleteAuthResponse,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BraintreeCompleteAuthResponse,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeCompleteAuthResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
+ }),
+ BraintreeCompleteAuthResponse::AuthResponse(auth_response) => {
+ let transaction_data = auth_response.data.authorize_credit_card.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
+ MandateReference {
+ connector_mandate_id: Some(pm.id.clone().expose()),
+ payment_method_id: None,
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ }
+ }
}
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClientToken {
- pub value: Secret<String>,
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct PaymentsResponse {
+ data: DataResponse,
}
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeSessionTokenResponse {
- pub client_token: ClientToken,
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreePaymentsResponse {
+ PaymentsResponse(Box<PaymentsResponse>),
+ ClientTokenResponse(Box<ClientTokenResponse>),
+ ErrorResponse(Box<ErrorResponse>),
}
-#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq, Serialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeCompleteChargeResponse {
+ PaymentsResponse(Box<PaymentsResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct TransactionResponse {
- id: String,
- currency_iso_code: String,
- amount: String,
- status: BraintreePaymentStatus,
+pub struct DataResponse {
+ charge_credit_card: AuthChargeCreditCard,
}
-#[derive(Debug, Deserialize, Serialize)]
+#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct BraintreeApiErrorResponse {
- pub api_error_response: ApiErrorResponse,
+pub struct RefundInputData {
+ amount: StringMajorUnit,
+ merchant_account_id: Secret<String>,
+}
+#[derive(Serialize, Debug, Clone)]
+struct IdFilter {
+ is: String,
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct ErrorsObject {
- pub errors: Vec<ErrorObject>,
- pub transaction: Option<TransactionError>,
+#[derive(Debug, Clone, Serialize)]
+pub struct TransactionSearchInput {
+ id: IdFilter,
}
-#[derive(Debug, Deserialize, Serialize)]
+#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct TransactionError {
- pub errors: Vec<ErrorObject>,
- pub credit_card: Option<CreditCardError>,
+pub struct BraintreeRefundInput {
+ transaction_id: String,
+ refund: RefundInputData,
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct CreditCardError {
- pub errors: Vec<ErrorObject>,
+impl<F> TryFrom<BraintreeRouterData<&types::RefundsRouterData<F>>> for BraintreeRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: BraintreeRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
+ let metadata: BraintreeMeta =
+ utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+
+ utils::validate_currency(
+ item.router_data.request.currency,
+ Some(metadata.merchant_config_currency),
+ )?;
+ let query = REFUND_TRANSACTION_MUTATION.to_string();
+ let variables = BraintreeRefundVariables {
+ input: BraintreeRefundInput {
+ transaction_id: item.router_data.request.connector_transaction_id.clone(),
+ refund: RefundInputData {
+ amount: item.amount,
+ merchant_account_id: metadata.merchant_account_id,
+ },
+ },
+ };
+ Ok(Self { query, variables })
+ }
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct ErrorObject {
- pub code: String,
- pub message: String,
+#[derive(Debug, Clone, Deserialize, Serialize, strum::Display)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum BraintreeRefundStatus {
+ SettlementPending,
+ Settling,
+ Settled,
+ SubmittedForSettlement,
+ Failed,
}
-#[derive(Debug, Default, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeErrorResponse {
- pub errors: String,
+impl From<BraintreeRefundStatus> for enums::RefundStatus {
+ fn from(item: BraintreeRefundStatus) -> Self {
+ match item {
+ BraintreeRefundStatus::Settled | BraintreeRefundStatus::Settling => Self::Success,
+ BraintreeRefundStatus::SubmittedForSettlement
+ | BraintreeRefundStatus::SettlementPending => Self::Pending,
+ BraintreeRefundStatus::Failed => Self::Failure,
+ }
+ }
}
-#[derive(Debug, Deserialize, Serialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct BraintreeRefundTransactionBody {
+ pub id: String,
+ pub status: BraintreeRefundStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct BraintreeRefundTransaction {
+ pub refund: BraintreeRefundTransactionBody,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
+pub struct BraintreeRefundResponseData {
+ pub refund_transaction: BraintreeRefundTransaction,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+
+pub struct RefundResponse {
+ pub data: BraintreeRefundResponseData,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, BraintreeRefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, BraintreeRefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: match item.response {
+ BraintreeRefundResponse::ErrorResponse(error_response) => {
+ build_error_response(&error_response.errors, item.http_code)
+ }
+ BraintreeRefundResponse::SuccessResponse(refund_data) => {
+ let refund_data = refund_data.data.refund_transaction.refund;
+ let refund_status = enums::RefundStatus::from(refund_data.status.clone());
+ if utils::is_refund_failure(refund_status) {
+ Err(types::ErrorResponse {
+ code: refund_data.status.to_string().clone(),
+ message: refund_data.status.to_string().clone(),
+ reason: Some(refund_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(refund_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::RefundsResponseData {
+ connector_refund_id: refund_data.id.clone(),
+ refund_status,
+ })
+ }
+ }
+ },
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct RefundSearchInput {
+ id: IdFilter,
+}
+impl TryFrom<&types::RefundSyncRouterData> for BraintreeRSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
+ let metadata: BraintreeMeta = utils::to_connector_meta_from_secret(
+ item.connector_meta_data.clone(),
+ )
+ .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
+ utils::validate_currency(
+ item.request.currency,
+ Some(metadata.merchant_config_currency),
+ )?;
+ let refund_id = item.request.get_connector_refund_id()?;
+ Ok(Self {
+ query: REFUND_QUERY.to_string(),
+ variables: RSyncInput {
+ input: RefundSearchInput {
+ id: IdFilter { is: refund_id },
+ },
+ },
+ })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncNodeData {
+ id: String,
+ status: BraintreeRefundStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncEdgeData {
+ node: RSyncNodeData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RefundData {
+ edges: Vec<RSyncEdgeData>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncSearchData {
+ refunds: RefundData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncResponseData {
+ search: RSyncSearchData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncResponse {
+ data: RSyncResponseData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
+pub enum BraintreeRSyncResponse {
+ RSyncResponse(Box<RSyncResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
-pub enum ErrorResponse {
- BraintreeApiErrorResponse(Box<BraintreeApiErrorResponse>),
- BraintreeErrorResponse(Box<BraintreeErrorResponse>),
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, BraintreeRSyncResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, BraintreeRSyncResponse>,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeRSyncResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
+ }),
+ BraintreeRSyncResponse::RSyncResponse(rsync_response) => {
+ let edge_data = rsync_response
+ .data
+ .search
+ .refunds
+ .edges
+ .first()
+ .ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
+ let connector_refund_id = &edge_data.node.id;
+ let response = Ok(types::RefundsResponseData {
+ connector_refund_id: connector_refund_id.to_string(),
+ refund_status: enums::RefundStatus::from(edge_data.node.status.clone()),
+ });
+ Ok(Self {
+ response,
+ ..item.data
+ })
+ }
+ }
+ }
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct ApiErrorResponse {
- pub message: String,
- pub errors: ErrorsObject,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreditCardData {
+ number: cards::CardNumber,
+ expiration_year: Secret<String>,
+ expiration_month: Secret<String>,
+ cvv: Secret<String>,
+ cardholder_name: Secret<String>,
}
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeRefundRequest {
- transaction: Amount,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ClientTokenInput {
+ merchant_account_id: Secret<String>,
}
-#[derive(Default, Debug, Serialize, Clone)]
-pub struct Amount {
- amount: Option<String>,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct InputData {
+ credit_card: CreditCardData,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct InputClientTokenData {
+ client_token: ClientTokenInput,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for BraintreeRefundRequest {
+impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.connector_meta_data.clone())?;
+ fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
+ match item.request.payment_method_data.clone() {
+ domain::PaymentMethodData::Card(card_data) => Ok(Self {
+ query: TOKENIZE_CREDIT_CARD.to_string(),
+ variables: VariableInput {
+ input: InputData {
+ credit_card: CreditCardData {
+ number: card_data.card_number,
+ expiration_year: card_data.card_exp_year,
+ expiration_month: card_data.card_exp_month,
+ cvv: card_data.card_cvc,
+ cardholder_name: item
+ .get_optional_billing_full_name()
+ .unwrap_or(Secret::new("".to_string())),
+ },
+ },
+ },
+ }),
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::OpenBanking(_)
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::RealTimePayment(_)
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("braintree"),
+ )
+ .into())
+ }
+ }
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct TokenizePaymentMethodData {
+ id: Secret<String>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TokenizeCreditCardData {
+ payment_method: TokenizePaymentMethodData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ClientToken {
+ client_token: Secret<String>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TokenizeCreditCard {
+ tokenize_credit_card: TokenizeCreditCardData,
+}
- utils::validate_currency(item.request.currency, metadata.merchant_config_currency)?;
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ClientTokenData {
+ create_client_token: ClientToken,
+}
- let refund_amount =
- utils::to_currency_base_unit(item.request.refund_amount, item.request.currency)?;
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct ClientTokenResponse {
+ data: ClientTokenData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct TokenResponse {
+ data: TokenizeCreditCard,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct ErrorResponse {
+ errors: Vec<ErrorDetails>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeTokenResponse {
+ TokenResponse(Box<TokenResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, BraintreeTokenResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, BraintreeTokenResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- transaction: Amount {
- amount: Some(refund_amount),
+ response: match item.response {
+ BraintreeTokenResponse::ErrorResponse(error_response) => {
+ build_error_response(error_response.errors.as_ref(), item.http_code)
+ }
+
+ BraintreeTokenResponse::TokenResponse(token_response) => {
+ Ok(types::PaymentsResponseData::TokenizationResponse {
+ token: token_response
+ .data
+ .tokenize_credit_card
+ .payment_method
+ .id
+ .expose()
+ .clone(),
+ })
+ }
},
+ ..item.data
})
}
}
-#[allow(dead_code)]
-#[derive(Debug, Default, Deserialize, Clone, Serialize)]
-pub enum RefundStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptureTransactionBody {
+ amount: StringMajorUnit,
}
-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,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptureInputData {
+ transaction_id: String,
+ transaction: CaptureTransactionBody,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PsyncInputData {
+ transaction_id: String,
+}
+
+impl TryFrom<&BraintreeRouterData<&types::PaymentsCaptureRouterData>> for BraintreeCaptureRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BraintreeRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let query = CAPTURE_TRANSACTION_MUTATION.to_string();
+ let variables = VariableCaptureInput {
+ input: CaptureInputData {
+ transaction_id: item.router_data.request.connector_transaction_id.clone(),
+ transaction: CaptureTransactionBody {
+ amount: item.amount.to_owned(),
+ },
+ },
+ };
+ Ok(Self { query, variables })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CaptureResponseTransactionBody {
+ id: String,
+ status: BraintreePaymentStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CaptureTransactionData {
+ transaction: CaptureResponseTransactionBody,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptureResponseData {
+ capture_transaction: CaptureTransactionData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CaptureResponse {
+ data: CaptureResponseData,
+}
+
+impl TryFrom<types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>>
+ for types::PaymentsCaptureRouterData
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeCaptureResponse::SuccessResponse(capture_data) => {
+ let transaction_data = capture_data.data.capture_transaction.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ BraintreeCaptureResponse::ErrorResponse(error_data) => Ok(Self {
+ response: build_error_response(&error_data.errors, item.http_code),
+ ..item.data
+ }),
}
}
}
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct RefundResponse {
- pub id: String,
- pub status: RefundStatus,
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CancelInputData {
+ transaction_id: String,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+#[derive(Debug, Serialize)]
+pub struct VariableCancelInput {
+ input: CancelInputData,
+}
+
+#[derive(Debug, Serialize)]
+pub struct BraintreeCancelRequest {
+ query: String,
+ variables: VariableCancelInput,
+}
+
+impl TryFrom<&types::PaymentsCancelRouterData> for BraintreeCancelRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ let query = VOID_TRANSACTION_MUTATION.to_string();
+ let variables = VariableCancelInput {
+ input: CancelInputData {
+ transaction_id: item.request.connector_transaction_id.clone(),
+ },
+ };
+ Ok(Self { query, variables })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CancelResponseTransactionBody {
+ id: String,
+ status: BraintreePaymentStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CancelTransactionData {
+ reversal: CancelResponseTransactionBody,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CancelResponseData {
+ reverse_transaction: CancelTransactionData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CancelResponse {
+ data: CancelResponseData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeCancelResponse {
+ CancelResponse(Box<CancelResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, BraintreeCancelResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: types::ResponseRouterData<F, BraintreeCancelResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeCancelResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
+ }),
+ BraintreeCancelResponse::CancelResponse(void_response) => {
+ let void_data = void_response.data.reverse_transaction.reversal;
+ let status = enums::AttemptStatus::from(void_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: void_data.status.to_string().clone(),
+ message: void_data.status.to_string().clone(),
+ reason: Some(void_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: None,
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ }
+ }
+}
+
+impl TryFrom<&types::PaymentsSyncRouterData> for BraintreePSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
+ let transaction_id = item
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(Self {
- response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id,
- refund_status: enums::RefundStatus::from(item.response.status),
+ query: TRANSACTION_QUERY.to_string(),
+ variables: PSyncInput {
+ input: TransactionSearchInput {
+ id: IdFilter { is: transaction_id },
+ },
+ },
+ })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct NodeData {
+ id: String,
+ status: BraintreePaymentStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct EdgeData {
+ node: NodeData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct TransactionData {
+ edges: Vec<EdgeData>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct SearchData {
+ transactions: TransactionData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct PSyncResponseData {
+ search: SearchData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct PSyncResponse {
+ data: PSyncResponseData,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, BraintreePSyncResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, BraintreePSyncResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreePSyncResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
}),
- ..item.data
+ BraintreePSyncResponse::SuccessResponse(psync_response) => {
+ let edge_data = psync_response
+ .data
+ .search
+ .transactions
+ .edges
+ .first()
+ .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
+ let status = enums::AttemptStatus::from(edge_data.node.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: edge_data.node.status.to_string().clone(),
+ message: edge_data.node.status.to_string().clone(),
+ reason: Some(edge_data.node.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: None,
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ edge_data.node.id.clone(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ }
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BraintreeThreeDsResponse {
+ pub nonce: Secret<String>,
+ pub liability_shifted: bool,
+ pub liability_shift_possible: bool,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BraintreeThreeDsErrorResponse {
+ pub code: String,
+ pub message: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct BraintreeRedirectionResponse {
+ pub authentication_response: String,
+}
+
+impl TryFrom<BraintreeMeta> for BraintreeClientTokenRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(metadata: BraintreeMeta) -> Result<Self, Self::Error> {
+ Ok(Self {
+ query: CLIENT_TOKEN_MUTATION.to_owned(),
+ variables: VariableClientTokenInput {
+ input: InputClientTokenData {
+ client_token: ClientTokenInput {
+ merchant_account_id: metadata.merchant_account_id,
+ },
+ },
+ },
})
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
+impl
+ TryFrom<(
+ &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ BraintreeMeta,
+ )> for CardPaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ (item, metadata): (
+ &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ BraintreeMeta,
+ ),
) -> Result<Self, Self::Error> {
+ let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
+ (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
+ false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Vault(VaultTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ vault_payment_method_after_transacting: TransactionTiming {
+ when: "ALWAYS".to_string(),
+ },
+ }),
+ )
+ } else {
+ (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
+ false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Regular(RegularTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ channel: CHANNEL_CODE.to_string(),
+ }),
+ )
+ };
Ok(Self {
- response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id,
- refund_status: enums::RefundStatus::from(item.response.status),
- }),
- ..item.data
+ query,
+ variables: VariablePaymentInput {
+ input: PaymentInput {
+ payment_method_id: match item.router_data.get_payment_method_token()? {
+ types::PaymentMethodToken::Token(token) => token,
+ types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
+ unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"),
+ )?,
+ },
+ transaction: transaction_body,
+ },
+ },
+ })
+ }
+}
+
+impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
+ for CardPaymentRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let metadata: BraintreeMeta =
+ utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+ utils::validate_currency(
+ item.router_data.request.currency,
+ Some(metadata.merchant_config_currency),
+ )?;
+ let payload_data = PaymentsCompleteAuthorizeRequestData::get_redirect_response_payload(
+ &item.router_data.request,
+ )?
+ .expose();
+ let redirection_response: BraintreeRedirectionResponse = serde_json::from_value(
+ payload_data,
+ )
+ .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
+ field_name: "redirection_response",
+ })?;
+ let three_ds_data = serde_json::from_str::<BraintreeThreeDsResponse>(
+ &redirection_response.authentication_response,
+ )
+ .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
+ field_name: "three_ds_data",
+ })?;
+
+ let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
+ (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
+ false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Vault(VaultTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ vault_payment_method_after_transacting: TransactionTiming {
+ when: "ALWAYS".to_string(),
+ },
+ }),
+ )
+ } else {
+ (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
+ false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Regular(RegularTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ channel: CHANNEL_CODE.to_string(),
+ }),
+ )
+ };
+ Ok(Self {
+ query,
+ variables: VariablePaymentInput {
+ input: PaymentInput {
+ payment_method_id: three_ds_data.nonce,
+ transaction: transaction_body,
+ },
+ },
})
}
}
+
+fn get_braintree_redirect_form(
+ client_token_data: ClientTokenResponse,
+ payment_method_token: types::PaymentMethodToken,
+ card_details: domain::PaymentMethodData,
+) -> Result<services::RedirectForm, error_stack::Report<errors::ConnectorError>> {
+ Ok(services::RedirectForm::Braintree {
+ client_token: client_token_data
+ .data
+ .create_client_token
+ .client_token
+ .expose(),
+ card_token: match payment_method_token {
+ types::PaymentMethodToken::Token(token) => token.expose(),
+ types::PaymentMethodToken::ApplePayDecrypt(_) => Err(unimplemented_payment_method!(
+ "Apple Pay",
+ "Simplified",
+ "Braintree"
+ ))?,
+ },
+ bin: match card_details {
+ domain::PaymentMethodData::Card(card_details) => {
+ card_details.card_number.get_card_isin()
+ }
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::OpenBanking(_)
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::RealTimePayment(_)
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => Err(
+ errors::ConnectorError::NotImplemented("given payment method".to_owned()),
+ )?,
+ },
+ })
+}
+
+#[derive(Debug, Deserialize)]
+pub struct BraintreeWebhookResponse {
+ pub bt_signature: String,
+ pub bt_payload: String,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub struct Notification {
+ pub kind: String, // xml parse only string to fields
+ pub timestamp: String,
+ pub dispute: Option<BraintreeDisputeData>,
+}
+impl types::transformers::ForeignFrom<&str> for api_models::webhooks::IncomingWebhookEvent {
+ fn foreign_from(status: &str) -> Self {
+ match status {
+ "dispute_opened" => Self::DisputeOpened,
+ "dispute_lost" => Self::DisputeLost,
+ "dispute_won" => Self::DisputeWon,
+ "dispute_accepted" | "dispute_auto_accepted" => Self::DisputeAccepted,
+ "dispute_expired" => Self::DisputeExpired,
+ "dispute_disputed" => Self::DisputeChallenged,
+ _ => Self::EventNotSupported,
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct BraintreeDisputeData {
+ pub amount_disputed: i64,
+ pub amount_won: Option<String>,
+ pub case_number: Option<String>,
+ pub chargeback_protection_level: Option<String>,
+ pub currency_iso_code: String,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub created_at: Option<PrimitiveDateTime>,
+ pub evidence: Option<DisputeEvidence>,
+ pub id: String,
+ pub kind: String, // xml parse only string to fields
+ pub status: String,
+ pub reason: Option<String>,
+ pub reason_code: Option<String>,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub updated_at: Option<PrimitiveDateTime>,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub reply_by_date: Option<PrimitiveDateTime>,
+ pub transaction: DisputeTransaction,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct DisputeTransaction {
+ pub amount: StringMajorUnit,
+ pub id: String,
+}
+#[derive(Debug, Deserialize, Serialize)]
+pub struct DisputeEvidence {
+ pub comment: String,
+ pub id: Secret<String>,
+ pub created_at: Option<PrimitiveDateTime>,
+ pub url: url::Url,
+}
+
+pub(crate) fn get_dispute_stage(code: &str) -> Result<enums::DisputeStage, errors::ConnectorError> {
+ match code {
+ "CHARGEBACK" => Ok(enums::DisputeStage::Dispute),
+ "PRE_ARBITATION" => Ok(enums::DisputeStage::PreArbitration),
+ "RETRIEVAL" => Ok(enums::DisputeStage::PreDispute),
+ _ => Err(errors::ConnectorError::WebhookBodyDecodingFailed),
+ }
+}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index a85cb1f8fa..925fd3c61e 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1299,9 +1299,7 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> {
}
api_enums::Connector::Braintree => {
braintree::transformers::BraintreeAuthType::try_from(self.auth_type)?;
- braintree::braintree_graphql_transformers::BraintreeMeta::try_from(
- self.connector_meta_data,
- )?;
+ braintree::transformers::BraintreeMeta::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Cashtocode => {
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 550b1c7af1..09782b5af5 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -337,7 +337,7 @@ impl ConnectorData {
}
enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(&connector::Boku))),
enums::Connector::Braintree => {
- Ok(ConnectorEnum::Old(Box::new(&connector::Braintree)))
+ Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new())))
}
enums::Connector::Cashtocode => {
Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new())))
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 6bae052394..3fa9bb01c4 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -88,8 +88,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://country-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -288,9 +287,6 @@ discord_invite_url = "https://discord.gg/wJZ7DVW8mm"
[payouts]
payout_eligibility = true
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
-
[mandates.supported_payment_methods]
pay_later.klarna = {connector_list = "adyen"}
wallet.google_pay = {connector_list = "stripe,adyen,bankofamerica"}