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

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),