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): [bitpay] Add new crypto connector bitpay & testcases for all crypto connectors (#919)

Arvind Patelf70f10aac58c
diff --git a/Cargo.lock b/Cargo.lock
index a310cff5c1..3ef85ac8f6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2968,7 +2968,7 @@ dependencies = [
[[package]]
name = "opentelemetry"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"opentelemetry_api",
"opentelemetry_sdk",
@@ -2977,7 +2977,7 @@ dependencies = [
[[package]]
name = "opentelemetry-otlp"
version = "0.11.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"async-trait",
"futures",
@@ -2994,7 +2994,7 @@ dependencies = [
[[package]]
name = "opentelemetry-proto"
version = "0.1.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"futures",
"futures-util",
@@ -3006,7 +3006,7 @@ dependencies = [
[[package]]
name = "opentelemetry_api"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"fnv",
"futures-channel",
@@ -3021,7 +3021,7 @@ dependencies = [
[[package]]
name = "opentelemetry_sdk"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"async-trait",
"crossbeam-channel",
diff --git a/config/config.example.toml b/config/config.example.toml
index bda2714247..c0cf57015f 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -150,6 +150,7 @@ airwallex.base_url = "https://api-demo.airwallex.com/"
applepay.base_url = "https://apple-pay-gateway.apple.com/"
authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
+bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
braintree.base_url = "https://api.sandbox.braintreegateway.com/"
checkout.base_url = "https://api.sandbox.checkout.com/"
diff --git a/config/development.toml b/config/development.toml
index b537128d78..2aa9dc58d1 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -57,6 +57,7 @@ cards = [
"airwallex",
"authorizedotnet",
"bambora",
+ "bitpay",
"bluesnap",
"braintree",
"checkout",
@@ -104,6 +105,7 @@ airwallex.base_url = "https://api-demo.airwallex.com/"
applepay.base_url = "https://apple-pay-gateway.apple.com/"
authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
+bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
braintree.base_url = "https://api.sandbox.braintreegateway.com/"
checkout.base_url = "https://api.sandbox.checkout.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 10f5129c77..072dd4108a 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -74,6 +74,7 @@ airwallex.base_url = "https://api-demo.airwallex.com/"
applepay.base_url = "https://apple-pay-gateway.apple.com/"
authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
+bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
braintree.base_url = "https://api.sandbox.braintreegateway.com/"
checkout.base_url = "https://api.sandbox.checkout.com/"
@@ -113,6 +114,7 @@ cards = [
"airwallex",
"authorizedotnet",
"bambora",
+ "bitpay",
"bluesnap",
"braintree",
"checkout",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 2deab45a86..0f5b109da5 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -586,6 +586,7 @@ pub enum Connector {
Airwallex,
Applepay,
Authorizedotnet,
+ Bitpay,
Bluesnap,
Braintree,
Checkout,
@@ -664,6 +665,7 @@ pub enum RoutableConnectors {
Adyen,
Airwallex,
Authorizedotnet,
+ Bitpay,
Bambora,
Bluesnap,
Braintree,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 7f81bfc6d0..4e73119348 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -359,6 +359,7 @@ pub struct Connectors {
pub applepay: ConnectorParams,
pub authorizedotnet: ConnectorParams,
pub bambora: ConnectorParams,
+ pub bitpay: ConnectorParams,
pub bluesnap: ConnectorParams,
pub braintree: ConnectorParams,
pub checkout: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index a57ba2998f..1b0298214e 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -3,6 +3,7 @@ pub mod adyen;
pub mod airwallex;
pub mod authorizedotnet;
pub mod bambora;
+pub mod bitpay;
pub mod bluesnap;
pub mod braintree;
pub mod checkout;
@@ -38,7 +39,7 @@ pub mod mollie;
pub use self::dummyconnector::DummyConnector;
pub use self::{
aci::Aci, adyen::Adyen, airwallex::Airwallex, authorizedotnet::Authorizedotnet,
- bambora::Bambora, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout,
+ bambora::Bambora, bitpay::Bitpay, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout,
coinbase::Coinbase, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte,
globalpay::Globalpay, iatapay::Iatapay, klarna::Klarna, mollie::Mollie,
multisafepay::Multisafepay, nexinets::Nexinets, nuvei::Nuvei, opennode::Opennode,
diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs
new file mode 100644
index 0000000000..703302399f
--- /dev/null
+++ b/crates/router/src/connector/bitpay.rs
@@ -0,0 +1,533 @@
+mod transformers;
+
+use std::fmt::Debug;
+
+use common_utils::{errors::ReportSwitchExt, ext_traits::ByteSliceExt};
+use error_stack::ResultExt;
+use transformers as bitpay;
+
+use self::bitpay::BitpayWebhookDetails;
+use crate::{
+ configs::settings,
+ core::errors::{self, CustomResult},
+ headers,
+ services::{self, ConnectorIntegration},
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, Response,
+ },
+ utils::{self, BytesExt, Encode},
+};
+
+#[derive(Debug, Clone)]
+pub struct Bitpay;
+
+impl api::Payment for Bitpay {}
+impl api::PaymentToken for Bitpay {}
+impl api::PaymentSession for Bitpay {}
+impl api::ConnectorAccessToken for Bitpay {}
+impl api::PreVerify for Bitpay {}
+impl api::PaymentAuthorize for Bitpay {}
+impl api::PaymentSync for Bitpay {}
+impl api::PaymentCapture for Bitpay {}
+impl api::PaymentVoid for Bitpay {}
+impl api::Refund for Bitpay {}
+impl api::RefundExecute for Bitpay {}
+impl api::RefundSync for Bitpay {}
+
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Bitpay
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bitpay
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ _req: &types::RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let header = vec![
+ (
+ headers::CONTENT_TYPE.to_string(),
+ types::PaymentsAuthorizeType::get_content_type(self).to_string(),
+ ),
+ (headers::X_ACCEPT_VERSION.to_string(), "2.0.0".to_string()),
+ ];
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Bitpay {
+ fn id(&self) -> &'static str {
+ "bitpay"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.bitpay.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let auth = bitpay::BitpayAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: bitpay::BitpayErrorResponse =
+ res.response.parse_struct("BitpayErrorResponse").switch()?;
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ })
+ }
+}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Bitpay
+{
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Bitpay
+{
+}
+
+impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
+ for Bitpay
+{
+}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Bitpay
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/invoices", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = bitpay::BitpayPaymentsRequest::try_from(req)?;
+ let bitpay_req =
+ utils::Encode::<bitpay::BitpayPaymentsRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(bitpay_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsAuthorizeType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: bitpay::BitpayPaymentsResponse = res
+ .response
+ .parse_struct("Bitpay PaymentsAuthorizeResponse")
+ .switch()?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Bitpay
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let auth = bitpay::BitpayAuthType::try_from(&req.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let connector_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}/invoices/{}?token={}",
+ self.base_url(connectors),
+ connector_id,
+ auth.api_key
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ 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)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: bitpay::BitpayPaymentsResponse = res
+ .response
+ .parse_struct("bitpay PaymentsSyncResponse")
+ .switch()?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Bitpay
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ 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,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: bitpay::BitpayPaymentsResponse = res
+ .response
+ .parse_struct("Bitpay PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Bitpay
+{
+}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Bitpay {
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = bitpay::BitpayRefundRequest::try_from(req)?;
+ let bitpay_req =
+ utils::Encode::<bitpay::BitpayRefundRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(bitpay_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::RefundExecuteType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ let response: bitpay::RefundResponse =
+ res.response
+ .parse_struct("bitpay RefundResponse")
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Bitpay {
+ fn get_headers(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .body(types::RefundSyncType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ let response: bitpay::RefundResponse = res
+ .response
+ .parse_struct("bitpay RefundSyncResponse")
+ .switch()?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Bitpay {
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ let notif: BitpayWebhookDetails = request
+ .body
+ .parse_struct("BitpayWebhookDetails")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::ConnectorTransactionId(notif.data.id),
+ ))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ let notif: BitpayWebhookDetails = request
+ .body
+ .parse_struct("BitpayWebhookDetails")
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
+ match notif.event.name {
+ bitpay::WebhookEventType::Confirmed | bitpay::WebhookEventType::Completed => {
+ Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ }
+ bitpay::WebhookEventType::Paid => {
+ Ok(api::IncomingWebhookEvent::PaymentIntentProcessing)
+ }
+ bitpay::WebhookEventType::Declined => {
+ Ok(api::IncomingWebhookEvent::PaymentIntentFailure)
+ }
+ _ => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ }
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {
+ let notif: BitpayWebhookDetails = request
+ .body
+ .parse_struct("BitpayWebhookDetails")
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
+ Encode::<BitpayWebhookDetails>::encode_to_value(&notif)
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
+ }
+}
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
new file mode 100644
index 0000000000..92626abd7d
--- /dev/null
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -0,0 +1,287 @@
+use reqwest::Url;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ connector::utils::PaymentsAuthorizeRequestData,
+ core::errors,
+ services,
+ types::{self, api, storage::enums, ConnectorAuthType},
+};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum TransactionSpeed {
+ Low,
+ #[default]
+ Medium,
+ High,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct BitpayPaymentsRequest {
+ price: i64,
+ currency: String,
+ #[serde(rename = "redirectURL")]
+ redirect_url: String,
+ #[serde(rename = "notificationURL")]
+ notification_url: String,
+ transaction_speed: TransactionSpeed,
+ token: String,
+}
+
+impl TryFrom<&types::PaymentsAuthorizeRouterData> for BitpayPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ get_crypto_specific_payment_data(item)
+ }
+}
+
+// Auth Struct
+pub struct BitpayAuthType {
+ pub(super) api_key: String,
+}
+
+impl TryFrom<&ConnectorAuthType> for BitpayAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_string(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum BitpayPaymentStatus {
+ #[default]
+ New,
+ Paid,
+ Confirmed,
+ Complete,
+ Expired,
+ Invalid,
+}
+
+impl From<BitpayPaymentStatus> for enums::AttemptStatus {
+ fn from(item: BitpayPaymentStatus) -> Self {
+ match item {
+ BitpayPaymentStatus::New => Self::AuthenticationPending,
+ BitpayPaymentStatus::Complete | BitpayPaymentStatus::Confirmed => Self::Charged,
+ BitpayPaymentStatus::Expired => Self::Failure,
+ _ => Self::Pending,
+ }
+ }
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum ExceptionStatus {
+ #[default]
+ Unit,
+ Bool(bool),
+ String(String),
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BitpayPaymentResponseData {
+ pub url: Option<Url>,
+ pub status: BitpayPaymentStatus,
+ pub price: i64,
+ pub currency: String,
+ pub amount_paid: i64,
+ pub invoice_time: Option<i64>,
+ pub rate_refresh_time: Option<i64>,
+ pub expiration_time: Option<i64>,
+ pub current_time: Option<i64>,
+ pub id: String,
+ pub low_fee_detected: Option<bool>,
+ pub display_amount_paid: Option<String>,
+ pub exception_status: ExceptionStatus,
+ pub redirect_url: Option<String>,
+ pub refund_address_request_pending: Option<bool>,
+ pub merchant_name: Option<String>,
+ pub token: Option<String>,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct BitpayPaymentsResponse {
+ data: BitpayPaymentResponseData,
+ facade: Option<String>,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, BitpayPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, BitpayPaymentsResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let redirection_data = item
+ .response
+ .data
+ .url
+ .map(|x| services::RedirectForm::from((x, services::Method::Get)));
+ let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id);
+ let attempt_status = item.response.data.status;
+ Ok(Self {
+ status: enums::AttemptStatus::from(attempt_status),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: connector_id,
+ redirection_data,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct BitpayRefundRequest {
+ pub amount: i64,
+}
+
+impl<F> TryFrom<&types::RefundsRouterData<F>> for BitpayRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.request.amount,
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct BitpayErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
+
+fn get_crypto_specific_payment_data(
+ item: &types::PaymentsAuthorizeRouterData,
+) -> Result<BitpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
+ let price = item.request.amount;
+ let currency = item.request.currency.to_string();
+ let redirect_url = item.request.get_return_url()?;
+ let notification_url = item.request.get_webhook_url()?;
+ let transaction_speed = TransactionSpeed::Medium;
+ let auth_type = item.connector_auth_type.clone();
+ let token = match auth_type {
+ ConnectorAuthType::HeaderKey { api_key } => api_key,
+ _ => String::default(),
+ };
+
+ Ok(BitpayPaymentsRequest {
+ price,
+ currency,
+ redirect_url,
+ notification_url,
+ transaction_speed,
+ token,
+ })
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct BitpayWebhookDetails {
+ pub event: Event,
+ pub data: BitpayPaymentResponseData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Event {
+ pub code: i64,
+ pub name: WebhookEventType,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub enum WebhookEventType {
+ #[serde(rename = "invoice_paidInFull")]
+ Paid,
+ #[serde(rename = "invoice_confirmed")]
+ Confirmed,
+ #[serde(rename = "invoice_completed")]
+ Completed,
+ #[serde(rename = "invoice_expired")]
+ Expired,
+ #[serde(rename = "invoice_failedToConfirm")]
+ Invalid,
+ #[serde(rename = "invoice_declined")]
+ Declined,
+ #[serde(rename = "invoice_refundComplete")]
+ Refunded,
+ #[serde(rename = "invoice_manuallyNotified")]
+ Resent,
+}
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 278a1dd24e..6e8fe22685 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -107,6 +107,7 @@ default_imp_for_complete_authorize!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
+ connector::Bitpay,
connector::Braintree,
connector::Checkout,
connector::Coinbase,
@@ -153,6 +154,7 @@ default_imp_for_create_customer!(
connector::Airwallex,
connector::Authorizedotnet,
connector::Bambora,
+ connector::Bitpay,
connector::Braintree,
connector::Checkout,
connector::Coinbase,
@@ -203,6 +205,7 @@ default_imp_for_connector_redirect_response!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
+ connector::Bitpay,
connector::Braintree,
connector::Coinbase,
connector::Cybersource,
@@ -239,6 +242,7 @@ default_imp_for_connector_request_id!(
connector::Airwallex,
connector::Authorizedotnet,
connector::Bambora,
+ connector::Bitpay,
connector::Bluesnap,
connector::Braintree,
connector::Checkout,
@@ -290,6 +294,7 @@ default_imp_for_accept_dispute!(
connector::Airwallex,
connector::Authorizedotnet,
connector::Bambora,
+ connector::Bitpay,
connector::Bluesnap,
connector::Braintree,
connector::Coinbase,
@@ -350,6 +355,7 @@ default_imp_for_file_upload!(
connector::Airwallex,
connector::Authorizedotnet,
connector::Bambora,
+ connector::Bitpay,
connector::Bluesnap,
connector::Braintree,
connector::Coinbase,
@@ -400,6 +406,7 @@ default_imp_for_submit_evidence!(
connector::Airwallex,
connector::Authorizedotnet,
connector::Bambora,
+ connector::Bitpay,
connector::Bluesnap,
connector::Braintree,
connector::Cybersource,
@@ -450,6 +457,7 @@ default_imp_for_defend_dispute!(
connector::Airwallex,
connector::Authorizedotnet,
connector::Bambora,
+ connector::Bitpay,
connector::Bluesnap,
connector::Braintree,
connector::Cybersource,
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index fb2ea5b073..6a1524dc99 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -61,6 +61,7 @@ pub mod headers {
pub const X_TRANS_KEY: &str = "X-Trans-Key";
pub const X_VERSION: &str = "X-Version";
pub const X_CC_VERSION: &str = "X-CC-Version";
+ pub const X_ACCEPT_VERSION: &str = "X-Accept-Version";
pub const X_DATE: &str = "X-Date";
}
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 7af5f62429..d4d7807273 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -203,6 +203,7 @@ impl ConnectorData {
"airwallex" => Ok(Box::new(&connector::Airwallex)),
"authorizedotnet" => Ok(Box::new(&connector::Authorizedotnet)),
"bambora" => Ok(Box::new(&connector::Bambora)),
+ "bitpay" => Ok(Box::new(&connector::Bitpay)),
"bluesnap" => Ok(Box::new(&connector::Bluesnap)),
"braintree" => Ok(Box::new(&connector::Braintree)),
"checkout" => Ok(Box::new(&connector::Checkout)),
diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs
new file mode 100644
index 0000000000..ebba241de1
--- /dev/null
+++ b/crates/router/tests/connectors/bitpay.rs
@@ -0,0 +1,145 @@
+use api_models::payments::CryptoData;
+use masking::Secret;
+use router::types::{self, api, storage::enums, PaymentAddress};
+
+use crate::{
+ connector_auth,
+ utils::{self, ConnectorActions},
+};
+
+#[derive(Clone, Copy)]
+struct BitpayTest;
+impl ConnectorActions for BitpayTest {}
+impl utils::Connector for BitpayTest {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Bitpay;
+ types::api::ConnectorData {
+ connector: Box::new(&Bitpay),
+ connector_name: types::Connector::Bitpay,
+ get_token: types::api::GetToken::Connector,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ types::ConnectorAuthType::from(
+ connector_auth::ConnectorAuthentication::new()
+ .bitpay
+ .expect("Missing connector authentication configuration"),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "bitpay".to_string()
+ }
+}
+
+static CONNECTOR: BitpayTest = BitpayTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ Some(utils::PaymentInfo {
+ address: Some(PaymentAddress {
+ billing: Some(api::Address {
+ address: Some(api::AddressDetails {
+ first_name: Some(Secret::new("first".to_string())),
+ last_name: Some(Secret::new("last".to_string())),
+ line1: Some(Secret::new("line1".to_string())),
+ line2: Some(Secret::new("line2".to_string())),
+ city: Some("city".to_string()),
+ zip: Some(Secret::new("zip".to_string())),
+ country: Some(api_models::enums::CountryAlpha2::IN),
+ ..Default::default()
+ }),
+ phone: Some(api::PhoneDetails {
+ number: Some(Secret::new("1234567890".to_string())),
+ country_code: Some("+91".to_string()),
+ }),
+ }),
+ ..Default::default()
+ }),
+ ..Default::default()
+ })
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ Some(types::PaymentsAuthorizeData {
+ amount: 1,
+ currency: enums::Currency::USD,
+ payment_method_data: types::api::PaymentMethodData::Crypto(CryptoData {}),
+ confirm: true,
+ statement_descriptor_suffix: None,
+ statement_descriptor: None,
+ setup_future_usage: None,
+ mandate_id: None,
+ off_session: None,
+ setup_mandate_details: None,
+ // capture_method: Some(capture_method),
+ browser_info: None,
+ order_details: None,
+ email: None,
+ payment_experience: None,
+ payment_method_type: None,
+ session_token: None,
+ enrolled_for_3ds: false,
+ related_transaction_id: None,
+ router_return_url: Some(String::from("https://google.com/")),
+ webhook_url: Some(String::from("https://google.com/")),
+ complete_authorize_url: None,
+ capture_method: None,
+ })
+}
+
+// Creates a payment using the manual capture flow
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let resp = response.clone().response.ok().unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending);
+ let endpoint = match resp {
+ types::PaymentsResponseData::TransactionResponse {
+ redirection_data, ..
+ } => Some(redirection_data),
+ _ => None,
+ };
+ assert!(endpoint.is_some())
+}
+
+// Synchronizes a successful transaction.
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ "NPf27TDfyU5mhcTCw2oaq4".to_string(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a expired transaction.
+#[actix_web::test]
+async fn should_sync_expired_payment() {
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ "bUsFf4RjQEahjbjGcETRS".to_string(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Failure);
+}
diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs
index 2a01ed7c62..9ad2a4dd05 100644
--- a/crates/router/tests/connectors/coinbase.rs
+++ b/crates/router/tests/connectors/coinbase.rs
@@ -1,7 +1,7 @@
-use std::str::FromStr;
-
+use api_models::payments::CryptoData;
use masking::Secret;
-use router::types::{self, api, storage::enums};
+use router::types::{self, api, storage::enums, PaymentAddress};
+use serde_json::json;
use crate::{
connector_auth,
@@ -37,65 +37,86 @@ impl utils::Connector for CoinbaseTest {
static CONNECTOR: CoinbaseTest = CoinbaseTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
- None
+ Some(utils::PaymentInfo {
+ address: Some(PaymentAddress {
+ billing: Some(api::Address {
+ address: Some(api::AddressDetails {
+ first_name: Some(Secret::new("first".to_string())),
+ last_name: Some(Secret::new("last".to_string())),
+ line1: Some(Secret::new("line1".to_string())),
+ line2: Some(Secret::new("line2".to_string())),
+ city: Some("city".to_string()),
+ zip: Some(Secret::new("zip".to_string())),
+ country: Some(api_models::enums::CountryAlpha2::IN),
+ ..Default::default()
+ }),
+ phone: Some(api::PhoneDetails {
+ number: Some(Secret::new("1234567890".to_string())),
+ country_code: Some("+91".to_string()),
+ }),
+ }),
+ ..Default::default()
+ }),
+ connector_meta_data: Some(json!({"pricing_type": "fixed_price"})),
+ ..Default::default()
+ })
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
- None
-}
-
-// Cards Positive Tests
-// Creates a payment using the manual capture flow (Non 3DS).
+ Some(types::PaymentsAuthorizeData {
+ amount: 1,
+ currency: enums::Currency::USD,
+ payment_method_data: types::api::PaymentMethodData::Crypto(CryptoData {}),
+ confirm: true,
+ statement_descriptor_suffix: None,
+ statement_descriptor: None,
+ setup_future_usage: None,
+ mandate_id: None,
+ off_session: None,
+ setup_mandate_details: None,
+ // capture_method: Some(capture_method),
+ browser_info: None,
+ order_details: None,
+ email: None,
+ payment_experience: None,
+ payment_method_type: None,
+ session_token: None,
+ enrolled_for_3ds: false,
+ related_transaction_id: None,
+ router_return_url: Some(String::from("https://google.com/")),
+ webhook_url: None,
+ complete_authorize_url: None,
+ capture_method: None,
+ })
+}
+
+// Creates a payment using the manual capture flow
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
- assert_eq!(response.status, enums::AttemptStatus::Authorized);
+ assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending);
+ let resp = response.response.ok().unwrap();
+ let endpoint = match resp {
+ types::PaymentsResponseData::TransactionResponse {
+ redirection_data, ..
+ } => Some(redirection_data),
+ _ => None,
+ };
+ assert!(endpoint.is_some())
}
-// Captures a payment using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_capture_authorized_payment() {
- let response = CONNECTOR
- .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
- .await
- .expect("Capture payment response");
- assert_eq!(response.status, enums::AttemptStatus::Charged);
-}
-
-// Partially captures a payment using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_partially_capture_authorized_payment() {
- let response = CONNECTOR
- .authorize_and_capture_payment(
- payment_method_details(),
- Some(types::PaymentsCaptureData {
- amount_to_capture: 50,
- ..utils::PaymentCaptureType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .expect("Capture payment response");
- assert_eq!(response.status, enums::AttemptStatus::Charged);
-}
-
-// Synchronizes a payment using the manual capture flow (Non 3DS).
+// Synchronizes a successful transaction.
#[actix_web::test]
async fn should_sync_authorized_payment() {
- let authorize_response = CONNECTOR
- .authorize_payment(payment_method_details(), get_default_payment_info())
- .await
- .expect("Authorize payment response");
- let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
- txn_id.unwrap(),
+ "ADFY3789".to_string(),
),
..Default::default()
}),
@@ -103,342 +124,62 @@ async fn should_sync_authorized_payment() {
)
.await
.expect("PSync response");
- assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
}
-// Voids a payment using the manual capture flow (Non 3DS).
+// Synchronizes a unresovled(underpaid) transaction.
#[actix_web::test]
-async fn should_void_authorized_payment() {
+async fn should_sync_unresolved_payment() {
let response = CONNECTOR
- .authorize_and_void_payment(
- payment_method_details(),
- Some(types::PaymentsCancelData {
- connector_transaction_id: String::from(""),
- cancellation_reason: Some("requested_by_customer".to_string()),
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ "YJ6RFZXZ".to_string(),
+ ),
..Default::default()
}),
get_default_payment_info(),
)
.await
- .expect("Void payment response");
- assert_eq!(response.status, enums::AttemptStatus::Voided);
-}
-
-// Refunds a payment using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_refund_manually_captured_payment() {
- let response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
- None,
- None,
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Partially refunds a payment using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_partially_refund_manually_captured_payment() {
- let response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
- None,
- Some(types::RefundsData {
- refund_amount: 50,
- ..utils::PaymentRefundType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Synchronizes a refund using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_sync_manually_captured_refund() {
- let refund_response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
- None,
- None,
- get_default_payment_info(),
- )
- .await
- .unwrap();
- let response = CONNECTOR
- .rsync_retry_till_status_matches(
- enums::RefundStatus::Success,
- refund_response.response.unwrap().connector_refund_id,
- None,
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Creates a payment using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_make_payment() {
- let authorize_response = CONNECTOR
- .make_payment(payment_method_details(), get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Unresolved);
}
-// Synchronizes a payment using the automatic capture flow (Non 3DS).
+// Synchronizes a expired transaction.
#[actix_web::test]
-async fn should_sync_auto_captured_payment() {
- let authorize_response = CONNECTOR
- .make_payment(payment_method_details(), get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
- let txn_id = utils::get_connector_transaction_id(authorize_response.response);
- assert_ne!(txn_id, None, "Empty connector transaction id");
+async fn should_sync_expired_payment() {
let response = CONNECTOR
.psync_retry_till_status_matches(
- enums::AttemptStatus::Charged,
+ enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
- txn_id.unwrap(),
+ "FZ89KDDB".to_string(),
),
- capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
- .unwrap();
- assert_eq!(response.status, enums::AttemptStatus::Charged,);
-}
-
-// Refunds a payment using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_refund_auto_captured_payment() {
- let response = CONNECTOR
- .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Partially refunds a payment using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_partially_refund_succeeded_payment() {
- let refund_response = CONNECTOR
- .make_payment_and_refund(
- payment_method_details(),
- Some(types::RefundsData {
- refund_amount: 50,
- ..utils::PaymentRefundType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- refund_response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_refund_succeeded_payment_multiple_times() {
- CONNECTOR
- .make_payment_and_multiple_refund(
- payment_method_details(),
- Some(types::RefundsData {
- refund_amount: 50,
- ..utils::PaymentRefundType::default().0
- }),
- get_default_payment_info(),
- )
- .await;
-}
-
-// Synchronizes a refund using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_sync_refund() {
- let refund_response = CONNECTOR
- .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
- .await
- .unwrap();
- let response = CONNECTOR
- .rsync_retry_till_status_matches(
- enums::RefundStatus::Success,
- refund_response.response.unwrap().connector_refund_id,
- None,
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Cards Negative scenerios
-// Creates a payment with incorrect card number.
-#[actix_web::test]
-async fn should_fail_payment_for_incorrect_card_number() {
- let response = CONNECTOR
- .make_payment(
- Some(types::PaymentsAuthorizeData {
- payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
- ..utils::CCardType::default().0
- }),
- ..utils::PaymentAuthorizeType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Your card number is incorrect.".to_string(),
- );
-}
-
-// Creates a payment with incorrect CVC.
-#[actix_web::test]
-async fn should_fail_payment_for_incorrect_cvc() {
- let response = CONNECTOR
- .make_payment(
- Some(types::PaymentsAuthorizeData {
- payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_cvc: Secret::new("12345".to_string()),
- ..utils::CCardType::default().0
- }),
- ..utils::PaymentAuthorizeType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Your card's security code is invalid.".to_string(),
- );
-}
-
-// Creates a payment with incorrect expiry month.
-#[actix_web::test]
-async fn should_fail_payment_for_invalid_exp_month() {
- let response = CONNECTOR
- .make_payment(
- Some(types::PaymentsAuthorizeData {
- payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_exp_month: Secret::new("20".to_string()),
- ..utils::CCardType::default().0
- }),
- ..utils::PaymentAuthorizeType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Your card's expiration month is invalid.".to_string(),
- );
-}
-
-// Creates a payment with incorrect expiry year.
-#[actix_web::test]
-async fn should_fail_payment_for_incorrect_expiry_year() {
- let response = CONNECTOR
- .make_payment(
- Some(types::PaymentsAuthorizeData {
- payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_exp_year: Secret::new("2000".to_string()),
- ..utils::CCardType::default().0
- }),
- ..utils::PaymentAuthorizeType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Your card's expiration year is invalid.".to_string(),
- );
-}
-
-// Voids a payment using automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_fail_void_payment_for_auto_capture() {
- let authorize_response = CONNECTOR
- .make_payment(payment_method_details(), get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
- let txn_id = utils::get_connector_transaction_id(authorize_response.response);
- assert_ne!(txn_id, None, "Empty connector transaction id");
- let void_response = CONNECTOR
- .void_payment(txn_id.unwrap(), None, get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(
- void_response.response.unwrap_err().message,
- "You cannot cancel this PaymentIntent because it has a status of succeeded."
- );
-}
-
-// Captures a payment using invalid connector payment id.
-#[actix_web::test]
-async fn should_fail_capture_for_invalid_payment() {
- let capture_response = CONNECTOR
- .capture_payment("123456789".to_string(), None, get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(
- capture_response.response.unwrap_err().message,
- String::from("No such payment_intent: '123456789'")
- );
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Failure);
}
-// Refunds a payment with refund amount higher than payment amount.
+// Synchronizes a cancelled transaction.
#[actix_web::test]
-async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+async fn should_sync_cancelled_payment() {
let response = CONNECTOR
- .make_payment_and_refund(
- payment_method_details(),
- Some(types::RefundsData {
- refund_amount: 150,
- ..utils::PaymentRefundType::default().0
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ "C35AAXKF".to_string(),
+ ),
+ ..Default::default()
}),
get_default_payment_info(),
)
.await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
- );
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
}
-
-// Connector dependent test cases goes here
-
-// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs
index 0613f1a84a..e42b579b54 100644
--- a/crates/router/tests/connectors/connector_auth.rs
+++ b/crates/router/tests/connectors/connector_auth.rs
@@ -10,6 +10,7 @@ pub(crate) struct ConnectorAuthentication {
pub airwallex: Option<BodyKey>,
pub authorizedotnet: Option<BodyKey>,
pub bambora: Option<BodyKey>,
+ pub bitpay: Option<HeaderKey>,
pub bluesnap: Option<BodyKey>,
pub checkout: Option<SignatureKey>,
pub coinbase: Option<HeaderKey>,
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 766a67029b..ba31db4cb1 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -11,6 +11,7 @@ mod adyen_ui;
mod airwallex;
mod authorizedotnet;
mod bambora;
+mod bitpay;
mod bluesnap;
mod checkout;
mod coinbase;
diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs
index 8d56878913..06aeb5c4c2 100644
--- a/crates/router/tests/connectors/opennode.rs
+++ b/crates/router/tests/connectors/opennode.rs
@@ -1,7 +1,6 @@
-use std::str::FromStr;
-
+use api_models::payments::CryptoData;
use masking::Secret;
-use router::types::{self, api, storage::enums};
+use router::types::{self, api, storage::enums, PaymentAddress};
use crate::{
connector_auth,
@@ -37,65 +36,86 @@ impl utils::Connector for OpennodeTest {
static CONNECTOR: OpennodeTest = OpennodeTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
- None
+ Some(utils::PaymentInfo {
+ address: Some(PaymentAddress {
+ billing: Some(api::Address {
+ address: Some(api::AddressDetails {
+ first_name: Some(Secret::new("first".to_string())),
+ last_name: Some(Secret::new("last".to_string())),
+ line1: Some(Secret::new("line1".to_string())),
+ line2: Some(Secret::new("line2".to_string())),
+ city: Some("city".to_string()),
+ zip: Some(Secret::new("zip".to_string())),
+ country: Some(api_models::enums::CountryAlpha2::IN),
+ ..Default::default()
+ }),
+ phone: Some(api::PhoneDetails {
+ number: Some(Secret::new("1234567890".to_string())),
+ country_code: Some("+91".to_string()),
+ }),
+ }),
+ ..Default::default()
+ }),
+ return_url: Some(String::from("https://google.com")),
+ ..Default::default()
+ })
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
- None
-}
-
-// Cards Positive Tests
-// Creates a payment using the manual capture flow (Non 3DS).
+ Some(types::PaymentsAuthorizeData {
+ amount: 1,
+ currency: enums::Currency::USD,
+ payment_method_data: types::api::PaymentMethodData::Crypto(CryptoData {}),
+ confirm: true,
+ statement_descriptor_suffix: None,
+ statement_descriptor: None,
+ setup_future_usage: None,
+ mandate_id: None,
+ off_session: None,
+ setup_mandate_details: None,
+ // capture_method: Some(capture_method),
+ browser_info: None,
+ order_details: None,
+ email: None,
+ payment_experience: None,
+ payment_method_type: None,
+ session_token: None,
+ enrolled_for_3ds: false,
+ related_transaction_id: None,
+ router_return_url: Some(String::from("https://google.com/")),
+ webhook_url: Some(String::from("https://google.com/")),
+ complete_authorize_url: None,
+ capture_method: None,
+ })
+}
+
+// Creates a payment using the manual capture flow
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
- assert_eq!(response.status, enums::AttemptStatus::Authorized);
-}
-
-// Captures a payment using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_capture_authorized_payment() {
- let response = CONNECTOR
- .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
- .await
- .expect("Capture payment response");
- assert_eq!(response.status, enums::AttemptStatus::Charged);
-}
-
-// Partially captures a payment using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_partially_capture_authorized_payment() {
- let response = CONNECTOR
- .authorize_and_capture_payment(
- payment_method_details(),
- Some(types::PaymentsCaptureData {
- amount_to_capture: 50,
- ..utils::PaymentCaptureType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .expect("Capture payment response");
- assert_eq!(response.status, enums::AttemptStatus::Charged);
+ assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending);
+ let resp = response.response.ok().unwrap();
+ let endpoint = match resp {
+ types::PaymentsResponseData::TransactionResponse {
+ redirection_data, ..
+ } => Some(redirection_data),
+ _ => None,
+ };
+ assert!(endpoint.is_some())
}
-// Synchronizes a payment using the manual capture flow (Non 3DS).
+// Synchronizes a successful transaction.
#[actix_web::test]
async fn should_sync_authorized_payment() {
- let authorize_response = CONNECTOR
- .authorize_payment(payment_method_details(), get_default_payment_info())
- .await
- .expect("Authorize payment response");
- let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
- txn_id.unwrap(),
+ "5adebfb1-802e-432b-8b42-5db4b754b2eb".to_string(),
),
..Default::default()
}),
@@ -103,342 +123,43 @@ async fn should_sync_authorized_payment() {
)
.await
.expect("PSync response");
- assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
}
-// Voids a payment using the manual capture flow (Non 3DS).
+// Synchronizes a unresovled(underpaid) transaction.
#[actix_web::test]
-async fn should_void_authorized_payment() {
+async fn should_sync_unresolved_payment() {
let response = CONNECTOR
- .authorize_and_void_payment(
- payment_method_details(),
- Some(types::PaymentsCancelData {
- connector_transaction_id: String::from(""),
- cancellation_reason: Some("requested_by_customer".to_string()),
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ "4cf63e6b-5135-49cb-997f-6e0b30fecebc".to_string(),
+ ),
..Default::default()
}),
get_default_payment_info(),
)
.await
- .expect("Void payment response");
- assert_eq!(response.status, enums::AttemptStatus::Voided);
-}
-
-// Refunds a payment using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_refund_manually_captured_payment() {
- let response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
- None,
- None,
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Partially refunds a payment using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_partially_refund_manually_captured_payment() {
- let response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
- None,
- Some(types::RefundsData {
- refund_amount: 50,
- ..utils::PaymentRefundType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Synchronizes a refund using the manual capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_sync_manually_captured_refund() {
- let refund_response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
- None,
- None,
- get_default_payment_info(),
- )
- .await
- .unwrap();
- let response = CONNECTOR
- .rsync_retry_till_status_matches(
- enums::RefundStatus::Success,
- refund_response.response.unwrap().connector_refund_id,
- None,
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Creates a payment using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_make_payment() {
- let authorize_response = CONNECTOR
- .make_payment(payment_method_details(), get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Unresolved);
}
-// Synchronizes a payment using the automatic capture flow (Non 3DS).
+// Synchronizes a expired transaction.
#[actix_web::test]
-async fn should_sync_auto_captured_payment() {
- let authorize_response = CONNECTOR
- .make_payment(payment_method_details(), get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
- let txn_id = utils::get_connector_transaction_id(authorize_response.response);
- assert_ne!(txn_id, None, "Empty connector transaction id");
+async fn should_sync_expired_payment() {
let response = CONNECTOR
.psync_retry_till_status_matches(
- enums::AttemptStatus::Charged,
+ enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
- txn_id.unwrap(),
+ "c36a097a-5091-4317-8749-80343a71c1c4".to_string(),
),
- capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
- .unwrap();
- assert_eq!(response.status, enums::AttemptStatus::Charged,);
-}
-
-// Refunds a payment using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_refund_auto_captured_payment() {
- let response = CONNECTOR
- .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Partially refunds a payment using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_partially_refund_succeeded_payment() {
- let refund_response = CONNECTOR
- .make_payment_and_refund(
- payment_method_details(),
- Some(types::RefundsData {
- refund_amount: 50,
- ..utils::PaymentRefundType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- refund_response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_refund_succeeded_payment_multiple_times() {
- CONNECTOR
- .make_payment_and_multiple_refund(
- payment_method_details(),
- Some(types::RefundsData {
- refund_amount: 50,
- ..utils::PaymentRefundType::default().0
- }),
- get_default_payment_info(),
- )
- .await;
-}
-
-// Synchronizes a refund using the automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_sync_refund() {
- let refund_response = CONNECTOR
- .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
- .await
- .unwrap();
- let response = CONNECTOR
- .rsync_retry_till_status_matches(
- enums::RefundStatus::Success,
- refund_response.response.unwrap().connector_refund_id,
- None,
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
- );
-}
-
-// Cards Negative scenerios
-// Creates a payment with incorrect card number.
-#[actix_web::test]
-async fn should_fail_payment_for_incorrect_card_number() {
- let response = CONNECTOR
- .make_payment(
- Some(types::PaymentsAuthorizeData {
- payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
- ..utils::CCardType::default().0
- }),
- ..utils::PaymentAuthorizeType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Your card number is incorrect.".to_string(),
- );
-}
-
-// Creates a payment with incorrect CVC.
-#[actix_web::test]
-async fn should_fail_payment_for_incorrect_cvc() {
- let response = CONNECTOR
- .make_payment(
- Some(types::PaymentsAuthorizeData {
- payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_cvc: Secret::new("12345".to_string()),
- ..utils::CCardType::default().0
- }),
- ..utils::PaymentAuthorizeType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Your card's security code is invalid.".to_string(),
- );
-}
-
-// Creates a payment with incorrect expiry month.
-#[actix_web::test]
-async fn should_fail_payment_for_invalid_exp_month() {
- let response = CONNECTOR
- .make_payment(
- Some(types::PaymentsAuthorizeData {
- payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_exp_month: Secret::new("20".to_string()),
- ..utils::CCardType::default().0
- }),
- ..utils::PaymentAuthorizeType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Your card's expiration month is invalid.".to_string(),
- );
-}
-
-// Creates a payment with incorrect expiry year.
-#[actix_web::test]
-async fn should_fail_payment_for_incorrect_expiry_year() {
- let response = CONNECTOR
- .make_payment(
- Some(types::PaymentsAuthorizeData {
- payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_exp_year: Secret::new("2000".to_string()),
- ..utils::CCardType::default().0
- }),
- ..utils::PaymentAuthorizeType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Your card's expiration year is invalid.".to_string(),
- );
-}
-
-// Voids a payment using automatic capture flow (Non 3DS).
-#[actix_web::test]
-async fn should_fail_void_payment_for_auto_capture() {
- let authorize_response = CONNECTOR
- .make_payment(payment_method_details(), get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
- let txn_id = utils::get_connector_transaction_id(authorize_response.response);
- assert_ne!(txn_id, None, "Empty connector transaction id");
- let void_response = CONNECTOR
- .void_payment(txn_id.unwrap(), None, get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(
- void_response.response.unwrap_err().message,
- "You cannot cancel this PaymentIntent because it has a status of succeeded."
- );
-}
-
-// Captures a payment using invalid connector payment id.
-#[actix_web::test]
-async fn should_fail_capture_for_invalid_payment() {
- let capture_response = CONNECTOR
- .capture_payment("123456789".to_string(), None, get_default_payment_info())
- .await
- .unwrap();
- assert_eq!(
- capture_response.response.unwrap_err().message,
- String::from("No such payment_intent: '123456789'")
- );
-}
-
-// Refunds a payment with refund amount higher than payment amount.
-#[actix_web::test]
-async fn should_fail_for_refund_amount_higher_than_payment_amount() {
- let response = CONNECTOR
- .make_payment_and_refund(
- payment_method_details(),
- Some(types::RefundsData {
- refund_amount: 150,
- ..utils::PaymentRefundType::default().0
- }),
- get_default_payment_info(),
- )
- .await
- .unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
- );
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Failure);
}
-
-// Connector dependent test cases goes here
-
-// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 262ab819dd..0448e782eb 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -97,6 +97,9 @@ api_key = "api_key"
key1 = "key1"
api_secret = "secret"
+[bitpay]
+api_key="API Key"
+
[iatapay]
key1 = "key1"
api_key = "api_key"
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 86571a26b5..5c5653fdc7 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -63,6 +63,7 @@ airwallex.base_url = "https://api-demo.airwallex.com/"
applepay.base_url = "https://apple-pay-gateway.apple.com/"
authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
+bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
braintree.base_url = "https://api.sandbox.braintreegateway.com/"
checkout.base_url = "https://api.sandbox.checkout.com/"
@@ -101,6 +102,7 @@ cards = [
"airwallex",
"authorizedotnet",
"bambora",
+ "bitpay",
"bluesnap",
"braintree",
"checkout",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 261513e128..4430f7808b 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -4,7 +4,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# add new connector to existing list and sort it
- connectors=(aci adyen airwallex applepay authorizedotnet bambora bluesnap braintree checkout coinbase cybersource dlocal dummyconnector fiserv forte globalpay iatapay klarna mollie multisafepay nexinets nuvei opennode payeezy paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1")
+ connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap braintree checkout coinbase cybersource dlocal dummyconnector fiserv forte globalpay iatapay klarna mollie multisafepay nexinets nuvei opennode payeezy paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp