feat:H1083-L1-L3-L4-L5 [Payment Authorise and Sync] + [Refunds and Sync] + [Redirection Flow (BNPL)] + [3DS Payment and Sync] for MultiSafePay (#658)

Co-authored-by: Zaid <syed.zaidali@juspay.in>
Co-authored-by: Rajak Rupakkumar Asishkumar <rajak.rupakkumar@juspay.in>
Co-authored-by: Jagan Elavarasan <jaganelavarasan@gmail.com>
This commit is contained in:
rupakrajak
2023-02-28 05:04:26 +05:30
committed by GitHub
parent 0de5d44195
commit 79aa8f3d3d
19 changed files with 1791 additions and 127 deletions

150
Cargo.lock generated
View File

@ -294,6 +294,15 @@ dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "anyhow"
version = "1.0.68"
@ -994,6 +1003,19 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f"
dependencies = [
"iana-time-zone",
"num-integer",
"num-traits",
"serde",
"winapi",
]
[[package]]
name = "clap"
version = "4.1.4"
@ -1028,6 +1050,16 @@ dependencies = [
"os_str_bytes",
]
[[package]]
name = "codespan-reporting"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e"
dependencies = [
"termcolor",
"unicode-width",
]
[[package]]
name = "common_utils"
version = "0.1.0"
@ -1183,6 +1215,50 @@ dependencies = [
"typenum",
]
[[package]]
name = "cxx"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86d3488e7665a7a483b57e25bdd90d0aeb2bc7608c8d0346acf2ad3f1caf1d62"
dependencies = [
"cc",
"cxxbridge-flags",
"cxxbridge-macro",
"link-cplusplus",
]
[[package]]
name = "cxx-build"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48fcaf066a053a41a81dfb14d57d99738b767febb8b735c3016e469fac5da690"
dependencies = [
"cc",
"codespan-reporting",
"once_cell",
"proc-macro2",
"quote",
"scratch",
"syn",
]
[[package]]
name = "cxxbridge-flags"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2ef98b8b717a829ca5603af80e1f9e2e48013ab227b68ef37872ef84ee479bf"
[[package]]
name = "cxxbridge-macro"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "086c685979a698443656e5cf7856c95c642295a38599f12fb1ff76fb28d19892"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "darling"
version = "0.14.3"
@ -1930,6 +2006,30 @@ dependencies = [
"tokio-native-tls",
]
[[package]]
name = "iana-time-zone"
version = "0.1.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"winapi",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca"
dependencies = [
"cxx",
"cxx-build",
]
[[package]]
name = "ident_case"
version = "1.0.1"
@ -2124,6 +2224,15 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "link-cplusplus"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5"
dependencies = [
"cc",
]
[[package]]
name = "linked-hash-map"
version = "0.5.6"
@ -3116,6 +3225,7 @@ dependencies = [
"serde_path_to_error",
"serde_qs 0.11.0",
"serde_urlencoded",
"serde_with",
"serial_test",
"signal-hook",
"signal-hook-tokio",
@ -3276,6 +3386,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "scratch"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddccb15bcce173023b3fedd9436f882a0739b8dfb45e4f6b6002bee5929f61b2"
[[package]]
name = "sct"
version = "0.7.0"
@ -3399,6 +3515,34 @@ dependencies = [
"serde",
]
[[package]]
name = "serde_with"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d904179146de381af4c93d3af6ca4984b3152db687dacb9c3c35e86f39809c"
dependencies = [
"base64 0.13.1",
"chrono",
"hex",
"indexmap",
"serde",
"serde_json",
"serde_with_macros",
"time",
]
[[package]]
name = "serde_with_macros"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1966009f3c05f095697c537312f5415d1e3ed31ce0a56942bac4c771c5c335e"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serial_test"
version = "1.0.0"
@ -4125,6 +4269,12 @@ dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-width"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
[[package]]
name = "untrusted"
version = "0.7.1"

View File

@ -57,6 +57,7 @@ cards = [
"dlocal",
"fiserv",
"globalpay",
"multisafepay",
"nuvei",
"payu",
"shift4",
@ -132,6 +133,9 @@ base_url = "https://ppp-test.nuvei.com/"
[connectors.airwallex]
base_url = "https://api-demo.airwallex.com/"
[connectors.multisafepay]
base_url = "https://testapi.multisafepay.com/"
[connectors.dlocal]
base_url = "https://sandbox.dlocal.com/"

View File

@ -162,6 +162,9 @@ base_url = "https://ppp-test.nuvei.com/"
[connectors.airwallex]
base_url = "https://api-demo.airwallex.com/"
[connectors.multisafepay]
base_url = "https://testapi.multisafepay.com/"
[connectors.dlocal]
base_url = "https://sandbox.dlocal.com/"

View File

@ -114,6 +114,9 @@ base_url = "https://ppp-test.nuvei.com/"
[connectors.airwallex]
base_url = "https://api-demo.airwallex.com/"
[connectors.multisafepay]
base_url = "https://testapi.multisafepay.com/"
[connectors.dlocal]
base_url = "https://sandbox.dlocal.com/"
@ -134,6 +137,7 @@ cards = [
"dlocal",
"fiserv",
"globalpay",
"multisafepay",
"nuvei",
"payu",
"shift4",

View File

@ -555,6 +555,7 @@ pub enum Connector {
Fiserv,
Globalpay,
Klarna,
Multisafepay,
Nuvei,
Payu,
Rapyd,
@ -605,6 +606,7 @@ pub enum RoutableConnectors {
Stripe,
Worldline,
Worldpay,
Multisafepay,
}
/// Wallets which support obtaining session object

View File

@ -66,6 +66,7 @@ serde_json = "1.0.91"
serde_path_to_error = "0.1.9"
serde_qs = { version = "0.11.0", optional = true }
serde_urlencoded = "0.7.1"
serde_with = "2.2.0"
signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"] }
signal-hook = "0.3.14"
strum = { version = "0.24.1", features = ["derive"] }

View File

@ -237,6 +237,7 @@ pub struct Connectors {
pub fiserv: ConnectorParams,
pub globalpay: ConnectorParams,
pub klarna: ConnectorParams,
pub multisafepay: ConnectorParams,
pub nuvei: ConnectorParams,
pub payu: ConnectorParams,
pub rapyd: ConnectorParams,

View File

@ -12,6 +12,7 @@ pub mod dlocal;
pub mod fiserv;
pub mod globalpay;
pub mod klarna;
pub mod multisafepay;
pub mod nuvei;
pub mod payu;
pub mod rapyd;
@ -25,6 +26,6 @@ pub use self::{
aci::Aci, adyen::Adyen, airwallex::Airwallex, applepay::Applepay,
authorizedotnet::Authorizedotnet, bambora::Bambora, bluesnap::Bluesnap, braintree::Braintree,
checkout::Checkout, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv,
globalpay::Globalpay, klarna::Klarna, nuvei::Nuvei, payu::Payu, rapyd::Rapyd, shift4::Shift4,
stripe::Stripe, worldline::Worldline, worldpay::Worldpay,
globalpay::Globalpay, klarna::Klarna, multisafepay::Multisafepay, nuvei::Nuvei, payu::Payu,
rapyd::Rapyd, shift4::Shift4, stripe::Stripe, worldline::Worldline, worldpay::Worldpay,
};

View File

@ -5,7 +5,7 @@ use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
connector::utils::PaymentsRequestData,
connector::utils::RouterData,
consts,
core::errors,
pii::{self, Email, Secret},

View File

@ -0,0 +1,459 @@
mod transformers;
use std::fmt::Debug;
use error_stack::{IntoReport, ResultExt};
use transformers as multisafepay;
use crate::{
configs::settings,
core::{
errors::{self, CustomResult},
payments,
},
headers,
services::{self, ConnectorIntegration},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, Response,
},
utils::{self, BytesExt},
};
#[derive(Debug, Clone)]
pub struct Multisafepay;
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Multisafepay
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> {
Ok(vec![])
}
}
impl ConnectorCommon for Multisafepay {
fn id(&self) -> &'static str {
"multisafepay"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
connectors.multisafepay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &types::ConnectorAuthType,
) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
let auth: multisafepay::MultisafepayAuthType = auth_type
.try_into()
.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: multisafepay::MultisafepayErrorResponse = res
.response
.parse_struct("MultisafepayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code.to_string(),
message: response.error_info,
reason: None,
})
}
}
impl api::Payment for Multisafepay {}
impl api::PreVerify for Multisafepay {}
impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
for Multisafepay
{
}
impl api::PaymentVoid for Multisafepay {}
impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for Multisafepay
{
}
impl api::ConnectorAccessToken for Multisafepay {}
impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
for Multisafepay
{
}
impl api::PaymentSync for Multisafepay {}
impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
for Multisafepay
{
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 url = self.base_url(connectors);
let api_key = multisafepay::MultisafepayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?
.api_key;
let ord_id = req.payment_id.clone();
Ok(format!("{url}v1/json/orders/{ord_id}?api_key={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)?)
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn get_error_response(
&self,
res: Response,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: multisafepay::MultisafepayPaymentsResponse = res
.response
.parse_struct("multisafepay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl api::PaymentCapture for Multisafepay {}
impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
for Multisafepay
{
}
impl api::PaymentSession for Multisafepay {}
impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for Multisafepay
{
//TODO: implement sessions flow
}
impl api::PaymentAuthorize for Multisafepay {}
impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
for Multisafepay
{
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> {
let url = self.base_url(connectors);
let api_key = multisafepay::MultisafepayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?
.api_key;
Ok(format!("{url}v1/json/orders?api_key={api_key}"))
}
fn get_request_body(
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<String>, errors::ConnectorError> {
let req_obj = multisafepay::MultisafepayPaymentsRequest::try_from(req)?;
let multisafepay_req =
utils::Encode::<multisafepay::MultisafepayPaymentsRequest>::encode_to_string_of_json(
&req_obj,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(multisafepay_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,
)?)
.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: multisafepay::MultisafepayPaymentsResponse = res
.response
.parse_struct("MultisafepayPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
}
.try_into()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl api::Refund for Multisafepay {}
impl api::RefundExecute for Multisafepay {}
impl api::RefundSync for Multisafepay {}
impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
for Multisafepay
{
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> {
let url = self.base_url(connectors);
let api_key = multisafepay::MultisafepayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?
.api_key;
let ord_id = req.payment_id.clone();
Ok(format!(
"{url}v1/json/orders/{ord_id}/refunds?api_key={api_key}"
))
}
fn get_request_body(
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
let multisafepay_req =
utils::Encode::<multisafepay::MultisafepayRefundRequest>::convert_and_encode(req)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(multisafepay_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)?)
.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: multisafepay::RefundResponse = res
.response
.parse_struct("multisafepay RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
}
.try_into()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
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 Multisafepay
{
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> {
let url = self.base_url(connectors);
let api_key = multisafepay::MultisafepayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?
.api_key;
let ord_id = req.payment_id.clone();
Ok(format!(
"{url}v1/json/orders/{ord_id}/refunds?api_key={api_key}"
))
}
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)?)
.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: multisafepay::RefundResponse = res
.response
.parse_struct("multisafepay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
}
.try_into()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
#[async_trait::async_trait]
impl api::IncomingWebhook for Multisafepay {
fn get_webhook_object_reference_id(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
}
fn get_webhook_event_type(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
}
fn get_webhook_resource_object(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<serde_json::Value, errors::ConnectorError> {
Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
}
}
impl services::ConnectorRedirectResponse for Multisafepay {
fn get_flow_type(
&self,
_query_params: &str,
) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
Ok(payments::CallConnectorAction::Trigger)
}
}

View File

@ -0,0 +1,588 @@
use common_utils::pii::Email;
use masking::ExposeInterface;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
connector::utils::{self, AddressDetailsData, CardData, RouterData},
core::errors,
pii::{self, Secret},
services,
types::{self, api, storage::enums},
};
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Type {
Direct,
Redirect,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Gateway {
Amex,
CreditCard,
Discover,
Maestro,
MasterCard,
Visa,
Klarna,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Coupons {
pub allow: Option<Vec<String>>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Mistercash {
pub mobile_pay_button_position: Option<String>,
pub disable_mobile_pay_button: Option<String>,
pub qr_only: Option<String>,
pub qr_size: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct Gateways {
pub mistercash: Option<Mistercash>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Settings {
pub coupons: Option<Coupons>,
pub gateways: Option<Gateways>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentOptions {
pub notification_url: Option<String>,
pub notification_method: Option<String>,
pub redirect_url: Option<String>,
pub cancel_url: Option<String>,
pub close_window: Option<bool>,
pub settings: Option<Settings>,
pub template_id: Option<String>,
pub allowed_countries: Option<Vec<String>>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Browser {
pub javascript_enabled: Option<bool>,
pub java_enabled: Option<bool>,
pub cookies_enabled: Option<bool>,
pub language: Option<String>,
pub screen_color_depth: Option<i32>,
pub screen_height: Option<i32>,
pub screen_width: Option<i32>,
pub time_zone: Option<i32>,
pub user_agent: Option<String>,
pub platform: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Customer {
pub browser: Option<Browser>,
pub locale: Option<String>,
pub ip_address: Option<String>,
pub forward_ip: Option<String>,
pub first_name: Option<String>,
pub last_name: Option<String>,
pub gender: Option<String>,
pub birthday: Option<String>,
pub address1: Option<String>,
pub address2: Option<String>,
pub house_number: Option<String>,
pub zip_code: Option<String>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub phone: Option<String>,
pub email: Option<Secret<String, Email>>,
pub user_agent: Option<String>,
pub referrer: Option<String>,
pub reference: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct GatewayInfo {
pub card_number: Option<Secret<String, pii::CardNumber>>,
pub card_holder_name: Option<Secret<String>>,
pub card_expiry_date: Option<i32>,
pub card_cvc: Option<Secret<String>>,
pub flexible_3d: Option<bool>,
pub moto: Option<bool>,
pub term_url: Option<String>,
pub email: Option<Secret<String, Email>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct DeliveryObject {
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
house_number: Secret<String>,
zip_code: Secret<String>,
city: String,
country: String,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct DefaultObject {
shipping_taxed: bool,
rate: f64,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct TaxObject {
pub default: DefaultObject,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct CheckoutOptions {
pub validate_cart: Option<bool>,
pub tax_tables: TaxObject,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Item {
pub name: String,
pub unit_price: f64,
pub description: Option<String>,
pub quantity: i64,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct ShoppingCart {
pub items: Vec<Item>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct MultisafepayPaymentsRequest {
#[serde(rename = "type")]
pub payment_type: Type,
pub gateway: Gateway,
pub order_id: String,
pub currency: String,
pub amount: i64,
pub description: String,
pub payment_options: Option<PaymentOptions>,
pub customer: Option<Customer>,
pub gateway_info: Option<GatewayInfo>,
pub delivery: Option<DeliveryObject>,
pub checkout_options: Option<CheckoutOptions>,
pub shopping_cart: Option<ShoppingCart>,
pub items: Option<String>,
pub recurring_model: Option<String>,
pub recurring_id: Option<String>,
pub capture: Option<String>,
pub days_active: Option<i32>,
pub seconds_active: Option<i32>,
pub var1: Option<String>,
pub var2: Option<String>,
pub var3: Option<String>,
}
impl From<utils::CardIssuer> for Gateway {
fn from(issuer: utils::CardIssuer) -> Self {
match issuer {
utils::CardIssuer::AmericanExpress => Self::Amex,
utils::CardIssuer::Master => Self::MasterCard,
utils::CardIssuer::Maestro => Self::Maestro,
utils::CardIssuer::Visa => Self::Visa,
utils::CardIssuer::Discover => Self::Discover,
}
}
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let payment_type = match item.request.payment_method_data {
api::PaymentMethodData::Card(ref _ccard) => Type::Direct,
api::PaymentMethodData::PayLater(ref _paylater) => Type::Redirect,
_ => Type::Redirect,
};
let gateway = match item.request.payment_method_data {
api::PaymentMethodData::Card(ref ccard) => Gateway::from(ccard.get_card_issuer()?),
api::PaymentMethodData::PayLater(
api_models::payments::PayLaterData::KlarnaRedirect {
billing_email: _,
billing_country: _,
},
) => Gateway::Klarna,
_ => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
};
let description = item.get_description()?;
let payment_options = PaymentOptions {
notification_url: None,
redirect_url: item.router_return_url.clone(),
cancel_url: None,
close_window: None,
notification_method: None,
settings: None,
template_id: None,
allowed_countries: None,
};
let customer = Customer {
browser: None,
locale: None,
ip_address: None,
forward_ip: None,
first_name: None,
last_name: None,
gender: None,
birthday: None,
address1: None,
address2: None,
house_number: None,
zip_code: None,
city: None,
state: None,
country: None,
phone: None,
email: item.request.email.clone(),
user_agent: None,
referrer: None,
reference: None,
};
let billing_address = item
.get_billing()?
.address
.as_ref()
.ok_or_else(utils::missing_field_err("billing.address"))?;
let delivery = DeliveryObject {
first_name: billing_address.get_first_name()?.to_owned(),
last_name: billing_address.get_last_name()?.to_owned(),
address1: billing_address.get_line1()?.to_owned(),
house_number: billing_address.get_line2()?.to_owned(),
zip_code: billing_address.get_zip()?.to_owned(),
city: billing_address.get_city()?.to_owned(),
country: billing_address.get_country()?.to_owned(),
};
let gateway_info = match item.request.payment_method_data {
api::PaymentMethodData::Card(ref ccard) => GatewayInfo {
card_number: Some(ccard.card_number.clone()),
card_expiry_date: Some(
(format!(
"{}{}",
ccard.get_card_expiry_year_2_digit().expose(),
ccard.card_exp_month.clone().expose()
))
.parse::<i32>()
.unwrap_or_default(),
),
card_cvc: Some(ccard.card_cvc.clone()),
card_holder_name: None,
flexible_3d: None,
moto: None,
term_url: None,
email: None,
},
api::PaymentMethodData::PayLater(ref paylater) => GatewayInfo {
card_number: None,
card_expiry_date: None,
card_cvc: None,
card_holder_name: None,
flexible_3d: None,
moto: None,
term_url: None,
email: Some(match paylater {
api_models::payments::PayLaterData::KlarnaRedirect {
billing_email,
billing_country: _,
} => billing_email.clone(),
_ => Err(errors::ConnectorError::NotImplemented(
"Only KlarnaRedirect is implemented".to_string(),
))?,
}),
},
_ => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
};
Ok(Self {
payment_type,
gateway,
order_id: item.payment_id.to_string(),
currency: item.request.currency.to_string(),
amount: item.request.amount,
description,
payment_options: Some(payment_options),
customer: Some(customer),
delivery: Some(delivery),
gateway_info: Some(gateway_info),
checkout_options: None,
shopping_cart: None,
capture: None,
items: None,
recurring_model: if item.request.setup_future_usage
== Some(enums::FutureUsage::OffSession)
{
Some("Unscheduled".to_string())
} else {
None
},
recurring_id: item
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.connector_mandate_id),
days_active: Some(30),
seconds_active: Some(259200),
var1: None,
var2: None,
var3: None,
})
}
}
// Auth Struct
pub struct MultisafepayAuthType {
pub(super) api_key: String,
}
impl TryFrom<&types::ConnectorAuthType> for MultisafepayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type {
Ok(Self {
api_key: api_key.to_string(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Eq, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MultisafepayPaymentStatus {
Completed,
Declined,
#[default]
Initialized,
}
impl From<MultisafepayPaymentStatus> for enums::AttemptStatus {
fn from(item: MultisafepayPaymentStatus) -> Self {
match item {
MultisafepayPaymentStatus::Completed => Self::Charged,
MultisafepayPaymentStatus::Declined => Self::Failure,
MultisafepayPaymentStatus::Initialized => Self::AuthenticationPending,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Data {
#[serde(rename = "type")]
pub payment_type: Option<String>,
pub order_id: String,
pub currency: Option<String>,
pub amount: Option<i64>,
pub description: Option<String>,
pub capture: Option<String>,
pub payment_url: Option<Url>,
pub status: Option<MultisafepayPaymentStatus>,
pub error_code: Option<i32>,
pub error_info: Option<String>,
pub payment_details: Option<MultisafepayPaymentDetails>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct MultisafepayPaymentDetails {
pub account_holder_name: Option<String>,
pub account_id: Option<String>,
pub card_expiry_date: Option<i32>,
pub external_transaction_id: Option<serde_json::Value>,
pub last4: Option<serde_json::Value>,
pub recurring_flow: Option<String>,
pub recurring_id: Option<String>,
pub recurring_model: Option<String>,
#[serde(rename = "type")]
pub payment_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MultisafepayPaymentsResponse {
pub success: bool,
pub data: Data,
}
impl<F, T>
TryFrom<
types::ResponseRouterData<F, MultisafepayPaymentsResponse, T, types::PaymentsResponseData>,
> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(
item: types::ResponseRouterData<
F,
MultisafepayPaymentsResponse,
T,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.data
.payment_url
.clone()
.map(|url| services::RedirectForm::from((url, services::Method::Get)));
let default_status = if item.response.success {
MultisafepayPaymentStatus::Initialized
} else {
MultisafepayPaymentStatus::Declined
};
let status = item.response.data.status.unwrap_or(default_status);
Ok(Self {
status: enums::AttemptStatus::from(status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.data.order_id),
redirection_data,
mandate_reference: item
.response
.data
.payment_details
.and_then(|payment_details| payment_details.recurring_id),
connector_metadata: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct MultisafepayRefundRequest {
pub currency: storage_models::enums::Currency,
pub amount: i64,
pub description: Option<String>,
pub refund_order_id: Option<String>,
pub checkout_data: Option<ShoppingCart>,
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for MultisafepayRefundRequest {
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
currency: item.request.currency,
amount: item.request.amount,
description: item.description.clone(),
refund_order_id: Some(item.request.refund_id.clone()),
checkout_data: None,
})
}
}
// 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,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundData {
pub transaction_id: i64,
pub refund_id: i64,
pub order_id: Option<String>,
pub error_code: Option<i32>,
pub error_info: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub success: bool,
pub data: RefundData,
}
impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
for types::RefundsRouterData<api::Execute>
{
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(
item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_stat = if item.response.success {
RefundStatus::Succeeded
} else {
RefundStatus::Failed
};
Ok(Self {
response: Ok(types::RefundsResponseData {
connector_refund_id: item.response.data.refund_id.to_string(),
refund_status: enums::RefundStatus::from(refund_stat),
}),
..item.data
})
}
}
impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
for types::RefundsRouterData<api::RSync>
{
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(
item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.success {
RefundStatus::Succeeded
} else {
RefundStatus::Failed
};
Ok(Self {
response: Ok(types::RefundsResponseData {
connector_refund_id: item.response.data.refund_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct MultisafepayErrorResponse {
pub success: bool,
pub error_code: i32,
pub error_info: String,
}

View File

@ -1,5 +1,9 @@
use std::collections::HashMap;
use error_stack::{report, IntoReport, ResultExt};
use masking::Secret;
use once_cell::sync::Lazy;
use regex::Regex;
use crate::{
core::errors::{self, CustomResult},
@ -38,17 +42,91 @@ pub trait RouterData {
fn get_billing(&self) -> Result<&api::Address, Error>;
fn get_billing_country(&self) -> Result<String, Error>;
fn get_billing_phone(&self) -> Result<&api::PhoneDetails, Error>;
fn get_description(&self) -> Result<String, Error>;
fn get_billing_address(&self) -> Result<&api::AddressDetails, Error>;
fn get_connector_meta(&self) -> Result<serde_json::Value, Error>;
fn get_session_token(&self) -> Result<String, Error>;
fn get_billing_address(&self) -> Result<&api::AddressDetails, Error>;
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn get_return_url(&self) -> Result<String, Error>;
}
impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> {
fn get_billing(&self) -> Result<&api::Address, Error> {
self.address
.billing
.as_ref()
.ok_or_else(missing_field_err("billing"))
}
fn get_billing_country(&self) -> Result<String, Error> {
self.address
.billing
.as_ref()
.and_then(|a| a.address.as_ref())
.and_then(|ad| ad.country.clone())
.ok_or_else(missing_field_err("billing.address.country"))
}
fn get_billing_phone(&self) -> Result<&api::PhoneDetails, Error> {
self.address
.billing
.as_ref()
.and_then(|a| a.phone.as_ref())
.ok_or_else(missing_field_err("billing.phone"))
}
fn get_description(&self) -> Result<String, Error> {
self.description
.clone()
.ok_or_else(missing_field_err("description"))
}
fn get_billing_address(&self) -> Result<&api::AddressDetails, Error> {
self.address
.billing
.as_ref()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("billing.address"))
}
fn get_connector_meta(&self) -> Result<serde_json::Value, Error> {
self.connector_meta_data
.clone()
.ok_or_else(missing_field_err("connector_meta_data"))
}
fn get_session_token(&self) -> Result<String, Error> {
self.session_token
.clone()
.ok_or_else(missing_field_err("session_token"))
}
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_value::<T>(self.get_connector_meta()?)
.into_report()
.change_context(errors::ConnectorError::NoConnectorMetaData)
}
fn get_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
}
pub trait PaymentsRequestData {
fn get_card(&self) -> Result<api::Card, Error>;
fn get_return_url(&self) -> Result<String, Error>;
}
impl PaymentsRequestData for types::PaymentsAuthorizeRouterData {
fn get_card(&self) -> Result<api::Card, Error> {
match self.request.payment_method_data.clone() {
api::PaymentMethodData::Card(card) => Ok(card),
_ => Err(missing_field_err("card")()),
}
}
}
pub trait PaymentsAuthorizeRequestData {
@ -98,75 +176,33 @@ impl RefundsRequestData for types::RefundsData {
}
}
impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> {
fn get_billing_country(&self) -> Result<String, Error> {
self.address
.billing
.as_ref()
.and_then(|a| a.address.as_ref())
.and_then(|ad| ad.country.clone())
.ok_or_else(missing_field_err("billing.address.country"))
}
static CARD_REGEX: Lazy<HashMap<CardIssuer, Result<Regex, regex::Error>>> = Lazy::new(|| {
let mut map = HashMap::new();
// Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841
// [#379]: Determine card issuer from card BIN number
map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$"));
map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$"));
map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$"));
map.insert(CardIssuer::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$"));
map.insert(
CardIssuer::Maestro,
Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"),
);
map
});
fn get_billing_phone(&self) -> Result<&api::PhoneDetails, Error> {
self.address
.billing
.as_ref()
.and_then(|a| a.phone.as_ref())
.ok_or_else(missing_field_err("billing.phone"))
}
fn get_billing_address(&self) -> Result<&api::AddressDetails, Error> {
self.address
.billing
.as_ref()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("billing.address"))
}
fn get_billing(&self) -> Result<&api::Address, Error> {
self.address
.billing
.as_ref()
.ok_or_else(missing_field_err("billing"))
}
fn get_connector_meta(&self) -> Result<serde_json::Value, Error> {
self.connector_meta_data
.clone()
.ok_or_else(missing_field_err("connector_meta_data"))
}
fn get_session_token(&self) -> Result<String, Error> {
self.session_token
.clone()
.ok_or_else(missing_field_err("session_token"))
}
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_value::<T>(self.get_connector_meta()?)
.into_report()
.change_context(errors::ConnectorError::NoConnectorMetaData)
}
}
impl PaymentsRequestData for types::PaymentsAuthorizeRouterData {
fn get_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("router_return_url"))
}
fn get_card(&self) -> Result<api::Card, Error> {
match self.request.payment_method_data.clone() {
api::PaymentMethodData::Card(card) => Ok(card),
_ => Err(missing_field_err("card")()),
}
}
#[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)]
pub enum CardIssuer {
AmericanExpress,
Master,
Maestro,
Visa,
Discover,
}
pub trait CardData {
fn get_card_expiry_year_2_digit(&self) -> Secret<String>;
fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
}
impl CardData for api::Card {
@ -175,6 +211,24 @@ impl CardData for api::Card {
let year = binding.peek();
Secret::new(year[year.len() - 2..].to_string())
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek().clone().as_str())
}
}
fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> {
for (k, v) in CARD_REGEX.iter() {
let regex: Regex = v
.clone()
.into_report()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if regex.is_match(card_number) {
return Ok(*k);
}
}
Err(error_stack::Report::new(
errors::ConnectorError::NotImplemented("Card Type".into()),
))
}
pub trait PhoneDetailsData {
fn get_number(&self) -> Result<Secret<String>, Error>;

View File

@ -1,14 +1,10 @@
use std::collections::HashMap;
use api_models::payments as api_models;
use common_utils::pii::{self, Email};
use error_stack::{IntoReport, ResultExt};
use masking::{PeekInterface, Secret};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::{
connector::utils::{self, CardData},
core::errors,
types::{
self, api,
@ -17,20 +13,6 @@ use crate::{
},
};
static CARD_REGEX: Lazy<HashMap<CardProduct, Result<Regex, regex::Error>>> = Lazy::new(|| {
let mut map = HashMap::new();
// Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841
// [#379]: Determine card issuer from card BIN number
map.insert(CardProduct::Master, Regex::new(r"^5[1-5][0-9]{14}$"));
map.insert(
CardProduct::AmericanExpress,
Regex::new(r"^3[47][0-9]{13}$"),
);
map.insert(CardProduct::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$"));
map.insert(CardProduct::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$"));
map
});
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
@ -130,12 +112,35 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest {
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub enum Gateway {
Amex = 2,
Discover = 128,
MasterCard = 3,
Visa = 1,
}
impl TryFrom<utils::CardIssuer> for Gateway {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Discover => Ok(Self::Discover),
_ => Err(errors::ConnectorError::NotSupported {
payment_method: format!("{issuer}"),
connector: "worldline",
}
.into()),
}
}
}
fn make_card_request(
address: &types::PaymentAddress,
req: &types::PaymentsAuthorizeData,
ccard: &api_models::Card,
) -> Result<PaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let card_number = ccard.card_number.peek().as_ref();
let expiry_year = ccard.card_exp_year.peek().clone();
let secret_value = format!(
"{}{}",
@ -149,7 +154,8 @@ fn make_card_request(
cvv: ccard.card_cvc.clone(),
expiry_date,
};
let payment_product_id = get_card_product_id(card_number)?;
#[allow(clippy::as_conversions)]
let payment_product_id = Gateway::try_from(ccard.get_card_issuer()?)? as u16;
let card_payment_method_specific_input = CardPaymentMethod {
card,
requires_approval: matches!(req.capture_method, Some(enums::CaptureMethod::Manual)),
@ -179,23 +185,6 @@ fn make_card_request(
})
}
fn get_card_product_id(
card_number: &str,
) -> Result<u16, error_stack::Report<errors::ConnectorError>> {
for (k, v) in CARD_REGEX.iter() {
let regex: Regex = v
.clone()
.into_report()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if regex.is_match(card_number) {
return Ok(k.product_id());
}
}
Err(error_stack::Report::new(
errors::ConnectorError::NotImplemented("Payment Method".into()),
))
}
fn get_address(
payment_address: &types::PaymentAddress,
) -> Option<(&api_models::Address, &api_models::AddressDetails)> {
@ -496,22 +485,3 @@ pub struct ErrorResponse {
pub error_id: Option<String>,
pub errors: Vec<Error>,
}
#[derive(Debug, Eq, Hash, PartialEq)]
pub enum CardProduct {
AmericanExpress,
Master,
Visa,
Discover,
}
impl CardProduct {
fn product_id(&self) -> u16 {
match *self {
Self::AmericanExpress => 2,
Self::Master => 3,
Self::Visa => 1,
Self::Discover => 128,
}
}
}

View File

@ -181,6 +181,7 @@ impl ConnectorData {
"stripe" => Ok(Box::new(&connector::Stripe)),
"worldline" => Ok(Box::new(&connector::Worldline)),
"worldpay" => Ok(Box::new(&connector::Worldpay)),
"multisafepay" => Ok(Box::new(&connector::Multisafepay)),
_ => Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError),

View File

@ -14,6 +14,7 @@ pub(crate) struct ConnectorAuthentication {
pub dlocal: Option<SignatureKey>,
pub fiserv: Option<SignatureKey>,
pub globalpay: Option<HeaderKey>,
pub multisafepay: Option<HeaderKey>,
pub nuvei: Option<SignatureKey>,
pub payu: Option<BodyKey>,
pub rapyd: Option<BodyKey>,

View File

@ -12,6 +12,7 @@ mod cybersource;
mod dlocal;
mod fiserv;
mod globalpay;
mod multisafepay;
mod nuvei;
mod payu;
mod rapyd;

View File

@ -0,0 +1,417 @@
use masking::Secret;
use router::types::{self, api, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct MultisafepayTest;
impl ConnectorActions for MultisafepayTest {}
impl utils::Connector for MultisafepayTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Multisafepay;
types::api::ConnectorData {
connector: Box::new(&Multisafepay),
connector_name: types::Connector::Multisafepay,
get_token: types::api::GetToken::Connector,
}
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
types::ConnectorAuthType::from(
connector_auth::ConnectorAuthentication::new()
.multisafepay
.expect("Missing connector authentication configuration"),
)
}
fn get_name(&self) -> String {
"multisafepay".to_string()
}
}
static CONNECTOR: MultisafepayTest = MultisafepayTest {};
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(None, None)
.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(None, None, None)
.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(
None,
Some(types::PaymentsCaptureData {
amount_to_capture: Some(50),
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(None, None)
.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(),
),
encoded_data: None,
capture_method: None,
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
None,
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
None,
)
.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(None, None, None, None)
.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(
None,
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.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(None, None, None, None)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.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(None, None).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR.make_payment(None, None).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 response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: None,
}),
None,
)
.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(None, None, None)
.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(
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.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(
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.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(None, None, None)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.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: Secret::new("374500000000015".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert!(response.response.is_err());
}
// Creates a payment with empty card number.
#[actix_web::test]
async fn should_fail_payment_for_empty_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: types::api::PaymentMethodData::Card(api::Card {
card_number: Secret::new(String::from("")),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
let x = response.response.is_err();
assert!(x);
}
// 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
}),
None,
)
.await
.unwrap();
assert!(response.response.is_err());
}
// 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
}),
None,
)
.await
.unwrap();
assert!(response.response.is_err());
}
// 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
}),
None,
)
.await
.unwrap();
assert!(response.response.is_err());
}
// 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(None, None).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, None)
.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, None)
.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(
None,
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert!(response.response.is_err());
}

View File

@ -50,6 +50,9 @@ key1 = "Merchant Id"
api_key = "API Key"
api_secret = "API Secret Key"
[multisafepay]
api_key = "API Key"
[dlocal]
key1 = "key1"
api_key = "api_key"
@ -62,4 +65,4 @@ key1= "key1"
[nuvei]
api_key = "api_key"
key1 = "key1"
api_secret = "secret"
api_secret = "secret"

View File

@ -94,6 +94,9 @@ base_url = "https://ppp-test.nuvei.com/"
[connectors.airwallex]
base_url = "https://api-demo.airwallex.com/"
[connectors.multisafepay]
base_url = "https://testapi.multisafepay.com/"
[connectors.dlocal]
base_url = "https://sandbox.dlocal.com/"
@ -115,6 +118,7 @@ cards = [
"dlocal",
"fiserv",
"globalpay",
"multisafepay",
"nuvei",
"payu",
"shift4",