refactor(compatibility): remove specific imports (#181)

This commit is contained in:
Sangamesh Kulkarni
2022-12-20 18:00:40 +05:30
committed by GitHub
parent cb28355459
commit 08e9c079ce
12 changed files with 276 additions and 268 deletions

View File

@ -5,21 +5,19 @@ mod refunds;
mod setup_intents; mod setup_intents;
use actix_web::{web, Scope}; use actix_web::{web, Scope};
mod errors; mod errors;
pub(crate) use errors::ErrorCode;
pub(crate) use self::app::{Customers, PaymentIntents, Refunds, SetupIntents}; use crate::routes;
use crate::routes::AppState;
pub struct StripeApis; pub struct StripeApis;
impl StripeApis { impl StripeApis {
pub(crate) fn server(state: AppState) -> Scope { pub(crate) fn server(state: routes::AppState) -> Scope {
let max_depth = 10; let max_depth = 10;
let strict = false; let strict = false;
web::scope("/vs/v1") web::scope("/vs/v1")
.app_data(web::Data::new(serde_qs::Config::new(max_depth, strict))) .app_data(web::Data::new(serde_qs::Config::new(max_depth, strict)))
.service(SetupIntents::server(state.clone())) .service(app::SetupIntents::server(state.clone()))
.service(PaymentIntents::server(state.clone())) .service(app::PaymentIntents::server(state.clone()))
.service(Refunds::server(state.clone())) .service(app::Refunds::server(state.clone()))
.service(Customers::server(state)) .service(app::Customers::server(state))
} }
} }

View File

@ -1,12 +1,12 @@
use actix_web::{web, Scope}; use actix_web::{web, Scope};
use super::{customers::*, payment_intents::*, refunds::*, setup_intents::*}; use super::{customers::*, payment_intents::*, refunds::*, setup_intents::*};
use crate::routes::AppState; use crate::routes;
pub struct PaymentIntents; pub struct PaymentIntents;
impl PaymentIntents { impl PaymentIntents {
pub fn server(state: AppState) -> Scope { pub fn server(state: routes::AppState) -> Scope {
web::scope("/payment_intents") web::scope("/payment_intents")
.app_data(web::Data::new(state)) .app_data(web::Data::new(state))
.service(payment_intents_create) .service(payment_intents_create)
@ -20,7 +20,7 @@ impl PaymentIntents {
pub struct SetupIntents; pub struct SetupIntents;
impl SetupIntents { impl SetupIntents {
pub fn server(state: AppState) -> Scope { pub fn server(state: routes::AppState) -> Scope {
web::scope("/setup_intents") web::scope("/setup_intents")
.app_data(web::Data::new(state)) .app_data(web::Data::new(state))
.service(setup_intents_create) .service(setup_intents_create)
@ -33,7 +33,7 @@ impl SetupIntents {
pub struct Refunds; pub struct Refunds;
impl Refunds { impl Refunds {
pub fn server(config: AppState) -> Scope { pub fn server(config: routes::AppState) -> Scope {
web::scope("/refunds") web::scope("/refunds")
.app_data(web::Data::new(config)) .app_data(web::Data::new(config))
.service(refund_create) .service(refund_create)
@ -45,7 +45,7 @@ impl Refunds {
pub struct Customers; pub struct Customers;
impl Customers { impl Customers {
pub fn server(config: AppState) -> Scope { pub fn server(config: routes::AppState) -> Scope {
web::scope("/customers") web::scope("/customers")
.app_data(web::Data::new(config)) .app_data(web::Data::new(config))
.service(customer_create) .service(customer_create)

View File

@ -5,9 +5,9 @@ use error_stack::report;
use router_env::{tracing, tracing::instrument}; use router_env::{tracing, tracing::instrument};
use crate::{ use crate::{
compatibility::{stripe, wrap}, compatibility::{stripe::errors, wrap},
core::customers, core::customers,
routes::AppState, routes,
services::api, services::api,
types::api::customers as customer_types, types::api::customers as customer_types,
}; };
@ -15,7 +15,7 @@ use crate::{
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("")] #[post("")]
pub async fn customer_create( pub async fn customer_create(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
@ -23,13 +23,13 @@ pub async fn customer_create(
let payload: types::CreateCustomerRequest = match qs_config.deserialize_bytes(&form_payload) { let payload: types::CreateCustomerRequest = match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let create_cust_req: customer_types::CustomerRequest = payload.into(); let create_cust_req: customer_types::CustomerRequest = payload.into();
wrap::compatibility_api_wrap::<_, _, _, _, _, types::CreateCustomerResponse, stripe::ErrorCode>( wrap::compatibility_api_wrap::<_, _, _, _, _, types::CreateCustomerResponse, errors::ErrorCode>(
&state, &state,
&req, &req,
create_cust_req, create_cust_req,
@ -44,7 +44,7 @@ pub async fn customer_create(
#[instrument(skip_all)] #[instrument(skip_all)]
#[get("/{customer_id}")] #[get("/{customer_id}")]
pub async fn customer_retrieve( pub async fn customer_retrieve(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
req: HttpRequest, req: HttpRequest,
path: web::Path<String>, path: web::Path<String>,
) -> HttpResponse { ) -> HttpResponse {
@ -52,7 +52,7 @@ pub async fn customer_retrieve(
customer_id: path.into_inner(), customer_id: path.into_inner(),
}; };
wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerRetrieveResponse, stripe::ErrorCode>( wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerRetrieveResponse, errors::ErrorCode>(
&state, &state,
&req, &req,
payload, payload,
@ -67,7 +67,7 @@ pub async fn customer_retrieve(
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("/{customer_id}")] #[post("/{customer_id}")]
pub async fn customer_update( pub async fn customer_update(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
path: web::Path<String>, path: web::Path<String>,
@ -76,7 +76,7 @@ pub async fn customer_update(
let payload: types::CustomerUpdateRequest = match qs_config.deserialize_bytes(&form_payload) { let payload: types::CustomerUpdateRequest = match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
@ -84,7 +84,7 @@ pub async fn customer_update(
let mut cust_update_req: customer_types::CustomerRequest = payload.into(); let mut cust_update_req: customer_types::CustomerRequest = payload.into();
cust_update_req.customer_id = customer_id; cust_update_req.customer_id = customer_id;
wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerUpdateResponse, stripe::ErrorCode>( wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerUpdateResponse, errors::ErrorCode>(
&state, &state,
&req, &req,
cust_update_req, cust_update_req,
@ -99,7 +99,7 @@ pub async fn customer_update(
#[instrument(skip_all)] #[instrument(skip_all)]
#[delete("/{customer_id}")] #[delete("/{customer_id}")]
pub async fn customer_delete( pub async fn customer_delete(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
req: HttpRequest, req: HttpRequest,
path: web::Path<String>, path: web::Path<String>,
) -> HttpResponse { ) -> HttpResponse {
@ -107,7 +107,7 @@ pub async fn customer_delete(
customer_id: path.into_inner(), customer_id: path.into_inner(),
}; };
wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerDeleteResponse, stripe::ErrorCode>( wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerDeleteResponse, errors::ErrorCode>(
&state, &state,
&req, &req,
payload, payload,

View File

@ -1,9 +1,9 @@
use std::{convert::From, default::Default}; use std::{convert::From, default::Default};
use masking::{Secret, WithType}; use masking;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{pii::Email, types::api}; use crate::{pii, types::api};
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct CustomerAddress { pub(crate) struct CustomerAddress {
@ -17,10 +17,10 @@ pub(crate) struct CustomerAddress {
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct CreateCustomerRequest { pub(crate) struct CreateCustomerRequest {
pub(crate) email: Option<Secret<String, Email>>, pub(crate) email: Option<masking::Secret<String, pii::Email>>,
pub(crate) invoice_prefix: Option<String>, pub(crate) invoice_prefix: Option<String>,
pub(crate) name: Option<String>, pub(crate) name: Option<String>,
pub(crate) phone: Option<Secret<String, WithType>>, pub(crate) phone: Option<masking::Secret<String, masking::WithType>>,
pub(crate) address: Option<CustomerAddress>, pub(crate) address: Option<CustomerAddress>,
} }
@ -28,8 +28,8 @@ pub(crate) struct CreateCustomerRequest {
pub(crate) struct CustomerUpdateRequest { pub(crate) struct CustomerUpdateRequest {
pub(crate) metadata: Option<String>, pub(crate) metadata: Option<String>,
pub(crate) description: Option<String>, pub(crate) description: Option<String>,
pub(crate) email: Option<Secret<String, Email>>, pub(crate) email: Option<masking::Secret<String, pii::Email>>,
pub(crate) phone: Option<Secret<String, WithType>>, pub(crate) phone: Option<masking::Secret<String, masking::WithType>>,
pub(crate) name: Option<String>, pub(crate) name: Option<String>,
pub(crate) address: Option<CustomerAddress>, pub(crate) address: Option<CustomerAddress>,
} }
@ -40,10 +40,10 @@ pub(crate) struct CreateCustomerResponse {
object: String, object: String,
created: u64, created: u64,
description: Option<String>, description: Option<String>,
email: Option<Secret<String, Email>>, email: Option<masking::Secret<String, pii::Email>>,
metadata: Option<serde_json::Value>, metadata: Option<serde_json::Value>,
name: Option<String>, name: Option<String>,
phone: Option<Secret<String, WithType>>, phone: Option<masking::Secret<String, masking::WithType>>,
} }
pub(crate) type CustomerRetrieveResponse = CreateCustomerResponse; pub(crate) type CustomerRetrieveResponse = CreateCustomerResponse;

View File

@ -1,5 +1,5 @@
#![allow(unused_variables)] #![allow(unused_variables)]
use crate::core::errors::ApiErrorResponse; use crate::core::errors;
#[derive(Debug, router_derive::ApiError)] #[derive(Debug, router_derive::ApiError)]
#[error(error_type_enum = StripeErrorType)] #[error(error_type_enum = StripeErrorType)]
@ -310,90 +310,100 @@ pub(crate) enum StripeErrorType {
InvalidRequestError, InvalidRequestError,
} }
impl From<ApiErrorResponse> for ErrorCode { impl From<errors::ApiErrorResponse> for ErrorCode {
fn from(value: ApiErrorResponse) -> Self { fn from(value: errors::ApiErrorResponse) -> Self {
match value { match value {
ApiErrorResponse::Unauthorized | ApiErrorResponse::InvalidEphermeralKey => { errors::ApiErrorResponse::Unauthorized
ErrorCode::Unauthorized | errors::ApiErrorResponse::InvalidEphermeralKey => ErrorCode::Unauthorized,
} errors::ApiErrorResponse::InvalidRequestUrl
ApiErrorResponse::InvalidRequestUrl | ApiErrorResponse::InvalidHttpMethod => { | errors::ApiErrorResponse::InvalidHttpMethod => ErrorCode::InvalidRequestUrl,
ErrorCode::InvalidRequestUrl errors::ApiErrorResponse::MissingRequiredField { field_name } => {
} ErrorCode::ParameterMissing {
ApiErrorResponse::MissingRequiredField { field_name } => ErrorCode::ParameterMissing {
field_name: field_name.to_owned(), field_name: field_name.to_owned(),
param: field_name, param: field_name,
}, }
}
// parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff // parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff
ApiErrorResponse::InvalidDataFormat { errors::ApiErrorResponse::InvalidDataFormat {
field_name, field_name,
expected_format, expected_format,
} => ErrorCode::ParameterUnknown { } => ErrorCode::ParameterUnknown {
field_name, field_name,
expected_format, expected_format,
}, },
ApiErrorResponse::RefundAmountExceedsPaymentAmount => { errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => {
ErrorCode::RefundAmountExceedsPaymentAmount { ErrorCode::RefundAmountExceedsPaymentAmount {
param: "amount".to_owned(), param: "amount".to_owned(),
} }
} }
ApiErrorResponse::PaymentAuthorizationFailed { data } errors::ApiErrorResponse::PaymentAuthorizationFailed { data }
| ApiErrorResponse::PaymentAuthenticationFailed { data } => { | errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => {
ErrorCode::PaymentIntentAuthenticationFailure { data } ErrorCode::PaymentIntentAuthenticationFailure { data }
} }
ApiErrorResponse::VerificationFailed { data } => ErrorCode::VerificationFailed { data }, errors::ApiErrorResponse::VerificationFailed { data } => {
ApiErrorResponse::PaymentCaptureFailed { data } => { ErrorCode::VerificationFailed { data }
}
errors::ApiErrorResponse::PaymentCaptureFailed { data } => {
ErrorCode::PaymentIntentPaymentAttemptFailed { data } ErrorCode::PaymentIntentPaymentAttemptFailed { data }
} }
ApiErrorResponse::InvalidCardData { data } => ErrorCode::InvalidCardType, // Maybe it is better to de generalize this router error errors::ApiErrorResponse::InvalidCardData { data } => ErrorCode::InvalidCardType, // Maybe it is better to de generalize this router error
ApiErrorResponse::CardExpired { data } => ErrorCode::ExpiredCard, errors::ApiErrorResponse::CardExpired { data } => ErrorCode::ExpiredCard,
ApiErrorResponse::RefundFailed { data } => ErrorCode::RefundFailed, // Nothing at stripe to map errors::ApiErrorResponse::RefundFailed { data } => ErrorCode::RefundFailed, // Nothing at stripe to map
ApiErrorResponse::InternalServerError => ErrorCode::InternalServerError, // not a stripe code errors::ApiErrorResponse::InternalServerError => ErrorCode::InternalServerError, // not a stripe code
ApiErrorResponse::IncorrectConnectorNameGiven => ErrorCode::InternalServerError, errors::ApiErrorResponse::IncorrectConnectorNameGiven => ErrorCode::InternalServerError,
ApiErrorResponse::MandateActive => ErrorCode::MandateActive, //not a stripe code errors::ApiErrorResponse::MandateActive => ErrorCode::MandateActive, //not a stripe code
ApiErrorResponse::CustomerRedacted => ErrorCode::CustomerRedacted, //not a stripe code errors::ApiErrorResponse::CustomerRedacted => ErrorCode::CustomerRedacted, //not a stripe code
ApiErrorResponse::DuplicateRefundRequest => ErrorCode::DuplicateRefundRequest, errors::ApiErrorResponse::DuplicateRefundRequest => ErrorCode::DuplicateRefundRequest,
ApiErrorResponse::RefundNotFound => ErrorCode::RefundNotFound, errors::ApiErrorResponse::RefundNotFound => ErrorCode::RefundNotFound,
ApiErrorResponse::CustomerNotFound => ErrorCode::CustomerNotFound, errors::ApiErrorResponse::CustomerNotFound => ErrorCode::CustomerNotFound,
ApiErrorResponse::PaymentNotFound => ErrorCode::PaymentNotFound, errors::ApiErrorResponse::PaymentNotFound => ErrorCode::PaymentNotFound,
ApiErrorResponse::PaymentMethodNotFound => ErrorCode::PaymentMethodNotFound, errors::ApiErrorResponse::PaymentMethodNotFound => ErrorCode::PaymentMethodNotFound,
ApiErrorResponse::ClientSecretNotGiven => ErrorCode::ClientSecretNotFound, errors::ApiErrorResponse::ClientSecretNotGiven => ErrorCode::ClientSecretNotFound,
ApiErrorResponse::MerchantAccountNotFound => ErrorCode::MerchantAccountNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => ErrorCode::MerchantAccountNotFound,
ApiErrorResponse::ResourceIdNotFound => ErrorCode::ResourceIdNotFound, errors::ApiErrorResponse::ResourceIdNotFound => ErrorCode::ResourceIdNotFound,
ApiErrorResponse::MerchantConnectorAccountNotFound => { errors::ApiErrorResponse::MerchantConnectorAccountNotFound => {
ErrorCode::MerchantConnectorAccountNotFound ErrorCode::MerchantConnectorAccountNotFound
} }
ApiErrorResponse::MandateNotFound => ErrorCode::MandateNotFound, errors::ApiErrorResponse::MandateNotFound => ErrorCode::MandateNotFound,
ApiErrorResponse::MandateValidationFailed { reason } => { errors::ApiErrorResponse::MandateValidationFailed { reason } => {
ErrorCode::PaymentIntentMandateInvalid { message: reason } ErrorCode::PaymentIntentMandateInvalid { message: reason }
} }
ApiErrorResponse::ReturnUrlUnavailable => ErrorCode::ReturnUrlUnavailable, errors::ApiErrorResponse::ReturnUrlUnavailable => ErrorCode::ReturnUrlUnavailable,
ApiErrorResponse::DuplicateMerchantAccount => ErrorCode::DuplicateMerchantAccount, errors::ApiErrorResponse::DuplicateMerchantAccount => {
ApiErrorResponse::DuplicateMerchantConnectorAccount => { ErrorCode::DuplicateMerchantAccount
}
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount => {
ErrorCode::DuplicateMerchantConnectorAccount ErrorCode::DuplicateMerchantConnectorAccount
} }
ApiErrorResponse::DuplicatePaymentMethod => ErrorCode::DuplicatePaymentMethod, errors::ApiErrorResponse::DuplicatePaymentMethod => ErrorCode::DuplicatePaymentMethod,
ApiErrorResponse::ClientSecretInvalid => ErrorCode::PaymentIntentInvalidParameter { errors::ApiErrorResponse::ClientSecretInvalid => {
ErrorCode::PaymentIntentInvalidParameter {
param: "client_secret".to_owned(), param: "client_secret".to_owned(),
}, }
ApiErrorResponse::InvalidRequestData { message } => { }
errors::ApiErrorResponse::InvalidRequestData { message } => {
ErrorCode::InvalidRequestData { message } ErrorCode::InvalidRequestData { message }
} }
ApiErrorResponse::PreconditionFailed { message } => { errors::ApiErrorResponse::PreconditionFailed { message } => {
ErrorCode::PreconditionFailed { message } ErrorCode::PreconditionFailed { message }
} }
ApiErrorResponse::BadCredentials => ErrorCode::Unauthorized, errors::ApiErrorResponse::BadCredentials => ErrorCode::Unauthorized,
ApiErrorResponse::InvalidDataValue { field_name } => ErrorCode::ParameterMissing { errors::ApiErrorResponse::InvalidDataValue { field_name } => {
ErrorCode::ParameterMissing {
field_name: field_name.to_owned(), field_name: field_name.to_owned(),
param: field_name.to_owned(), param: field_name.to_owned(),
}, }
ApiErrorResponse::MaximumRefundCount => ErrorCode::MaximumRefundCount, }
ApiErrorResponse::PaymentNotSucceeded => ErrorCode::PaymentFailed, errors::ApiErrorResponse::MaximumRefundCount => ErrorCode::MaximumRefundCount,
ApiErrorResponse::DuplicateMandate => ErrorCode::DuplicateMandate, errors::ApiErrorResponse::PaymentNotSucceeded => ErrorCode::PaymentFailed,
ApiErrorResponse::SuccessfulPaymentNotFound => ErrorCode::SuccessfulPaymentNotFound, errors::ApiErrorResponse::DuplicateMandate => ErrorCode::DuplicateMandate,
ApiErrorResponse::AddressNotFound => ErrorCode::AddressNotFound, errors::ApiErrorResponse::SuccessfulPaymentNotFound => {
ApiErrorResponse::NotImplemented => ErrorCode::Unauthorized, ErrorCode::SuccessfulPaymentNotFound
ApiErrorResponse::PaymentUnexpectedState { }
errors::ApiErrorResponse::AddressNotFound => ErrorCode::AddressNotFound,
errors::ApiErrorResponse::NotImplemented => ErrorCode::Unauthorized,
errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow, current_flow,
field_name, field_name,
current_value, current_value,

View File

@ -1,25 +1,22 @@
mod types; mod types;
use actix_web::{get, post, web, HttpRequest, HttpResponse}; use actix_web::{get, post, web, HttpRequest, HttpResponse};
use api_models::payments as payment_types;
use error_stack::report; use error_stack::report;
use router_env::{tracing, tracing::instrument}; use router_env::{tracing, tracing::instrument};
use crate::{ use crate::{
compatibility::{stripe, wrap}, compatibility::{stripe::errors, wrap},
core::payments, core::payments,
routes::AppState, routes,
services::api, services::api,
types::api::{ types::api::{self as api_types},
self as api_types, payments::PaymentsCaptureRequest, Authorize, Capture, PSync,
PaymentListConstraints, PaymentsCancelRequest, PaymentsRequest, PaymentsRetrieveRequest,
Void,
},
}; };
#[post("")] #[post("")]
#[instrument(skip_all)] #[instrument(skip_all)]
pub async fn payment_intents_create( pub async fn payment_intents_create(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
@ -28,11 +25,11 @@ pub async fn payment_intents_create(
match qs_config.deserialize_bytes(&form_payload) { match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let create_payment_req: PaymentsRequest = payload.into(); let create_payment_req: payment_types::PaymentsRequest = payload.into();
wrap::compatibility_api_wrap::< wrap::compatibility_api_wrap::<
_, _,
@ -41,14 +38,14 @@ pub async fn payment_intents_create(
_, _,
_, _,
types::StripePaymentIntentResponse, types::StripePaymentIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
create_payment_req, create_payment_req,
|state, merchant_account, req| { |state, merchant_account, req| {
let connector = req.connector; let connector = req.connector;
payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentCreate, payments::PaymentCreate,
@ -66,11 +63,11 @@ pub async fn payment_intents_create(
#[instrument(skip_all)] #[instrument(skip_all)]
#[get("/{payment_id}")] #[get("/{payment_id}")]
pub async fn payment_intents_retrieve( pub async fn payment_intents_retrieve(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
req: HttpRequest, req: HttpRequest,
path: web::Path<String>, path: web::Path<String>,
) -> HttpResponse { ) -> HttpResponse {
let payload = PaymentsRetrieveRequest { let payload = payment_types::PaymentsRetrieveRequest {
resource_id: api_types::PaymentIdType::PaymentIntentId(path.to_string()), resource_id: api_types::PaymentIdType::PaymentIntentId(path.to_string()),
merchant_id: None, merchant_id: None,
force_sync: true, force_sync: true,
@ -91,13 +88,13 @@ pub async fn payment_intents_retrieve(
_, _,
_, _,
types::StripePaymentIntentResponse, types::StripePaymentIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
payload, payload,
|state, merchant_account, payload| { |state, merchant_account, payload| {
payments::payments_core::<PSync, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentStatus, payments::PaymentStatus,
@ -115,7 +112,7 @@ pub async fn payment_intents_retrieve(
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("/{payment_id}")] #[post("/{payment_id}")]
pub async fn payment_intents_update( pub async fn payment_intents_update(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
@ -126,11 +123,11 @@ pub async fn payment_intents_update(
match qs_config.deserialize_bytes(&form_payload) { match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let mut payload: PaymentsRequest = stripe_payload.into(); let mut payload: payment_types::PaymentsRequest = stripe_payload.into();
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id));
let auth_type; let auth_type;
@ -146,14 +143,14 @@ pub async fn payment_intents_update(
_, _,
_, _,
types::StripePaymentIntentResponse, types::StripePaymentIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
payload, payload,
|state, merchant_account, req| { |state, merchant_account, req| {
let connector = req.connector; let connector = req.connector;
payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentUpdate, payments::PaymentUpdate,
@ -171,7 +168,7 @@ pub async fn payment_intents_update(
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("/{payment_id}/confirm")] #[post("/{payment_id}/confirm")]
pub async fn payment_intents_confirm( pub async fn payment_intents_confirm(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
@ -182,11 +179,11 @@ pub async fn payment_intents_confirm(
match qs_config.deserialize_bytes(&form_payload) { match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let mut payload: PaymentsRequest = stripe_payload.into(); let mut payload: payment_types::PaymentsRequest = stripe_payload.into();
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id));
payload.confirm = Some(true); payload.confirm = Some(true);
@ -203,14 +200,14 @@ pub async fn payment_intents_confirm(
_, _,
_, _,
types::StripePaymentIntentResponse, types::StripePaymentIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
payload, payload,
|state, merchant_account, req| { |state, merchant_account, req| {
let connector = req.connector; let connector = req.connector;
payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentConfirm, payments::PaymentConfirm,
@ -227,20 +224,21 @@ pub async fn payment_intents_confirm(
#[post("/{payment_id}/capture")] #[post("/{payment_id}/capture")]
pub async fn payment_intents_capture( pub async fn payment_intents_capture(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
path: web::Path<String>, path: web::Path<String>,
) -> HttpResponse { ) -> HttpResponse {
let stripe_payload: PaymentsCaptureRequest = match qs_config.deserialize_bytes(&form_payload) { let stripe_payload: payment_types::PaymentsCaptureRequest =
match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let capture_payload = PaymentsCaptureRequest { let capture_payload = payment_types::PaymentsCaptureRequest {
payment_id: Some(path.into_inner()), payment_id: Some(path.into_inner()),
..stripe_payload ..stripe_payload
}; };
@ -252,13 +250,13 @@ pub async fn payment_intents_capture(
_, _,
_, _,
types::StripePaymentIntentResponse, types::StripePaymentIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
capture_payload, capture_payload,
|state, merchant_account, payload| { |state, merchant_account, payload| {
payments::payments_core::<Capture, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentCapture, payments::PaymentCapture,
@ -276,7 +274,7 @@ pub async fn payment_intents_capture(
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("/{payment_id}/cancel")] #[post("/{payment_id}/cancel")]
pub async fn payment_intents_cancel( pub async fn payment_intents_cancel(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
@ -287,11 +285,11 @@ pub async fn payment_intents_cancel(
match qs_config.deserialize_bytes(&form_payload) { match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let mut payload: PaymentsCancelRequest = stripe_payload.into(); let mut payload: payment_types::PaymentsCancelRequest = stripe_payload.into();
payload.payment_id = payment_id; payload.payment_id = payment_id;
let auth_type = match api::get_auth_type(&req) { let auth_type = match api::get_auth_type(&req) {
@ -306,13 +304,13 @@ pub async fn payment_intents_cancel(
_, _,
_, _,
types::StripePaymentIntentResponse, types::StripePaymentIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
payload, payload,
|state, merchant_account, req| { |state, merchant_account, req| {
payments::payments_core::<Void, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentCancel, payments::PaymentCancel,
@ -330,11 +328,11 @@ pub async fn payment_intents_cancel(
#[instrument(skip_all)] #[instrument(skip_all)]
#[get("/list")] #[get("/list")]
pub async fn payment_intent_list( pub async fn payment_intent_list(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
req: HttpRequest, req: HttpRequest,
payload: web::Query<types::StripePaymentListConstraints>, payload: web::Query<types::StripePaymentListConstraints>,
) -> HttpResponse { ) -> HttpResponse {
let payload = match PaymentListConstraints::try_from(payload.into_inner()) { let payload = match payment_types::PaymentListConstraints::try_from(payload.into_inner()) {
Ok(p) => p, Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err), Err(err) => return api::log_and_return_error_response(err),
}; };
@ -345,7 +343,7 @@ pub async fn payment_intent_list(
_, _,
_, _,
types::StripePaymentIntentListResponse, types::StripePaymentIntentListResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,

View File

@ -1,30 +1,23 @@
use api_models::{payments, refunds};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{core::errors, types::api::enums as api_enums};
core::errors,
pii::Secret,
types::api::{
enums as api_enums, Address, AddressDetails, CCard, PaymentListConstraints,
PaymentListResponse, PaymentMethod, PaymentsCancelRequest, PaymentsRequest,
PaymentsResponse, PhoneDetails, RefundResponse,
},
};
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub(crate) struct StripeBillingDetails { pub(crate) struct StripeBillingDetails {
pub(crate) address: Option<AddressDetails>, pub(crate) address: Option<payments::AddressDetails>,
pub(crate) email: Option<String>, pub(crate) email: Option<String>,
pub(crate) name: Option<String>, pub(crate) name: Option<String>,
pub(crate) phone: Option<String>, pub(crate) phone: Option<String>,
} }
impl From<StripeBillingDetails> for Address { impl From<StripeBillingDetails> for payments::Address {
fn from(details: StripeBillingDetails) -> Self { fn from(details: StripeBillingDetails) -> Self {
Self { Self {
address: details.address, address: details.address,
phone: Some(PhoneDetails { phone: Some(payments::PhoneDetails {
number: details.phone.map(Secret::new), number: details.phone.map(masking::Secret::new),
country_code: None, country_code: None,
}), }),
} }
@ -71,41 +64,43 @@ pub(crate) enum StripePaymentMethodDetails {
BankTransfer, BankTransfer,
} }
impl From<StripeCard> for CCard { impl From<StripeCard> for payments::CCard {
fn from(card: StripeCard) -> Self { fn from(card: StripeCard) -> Self {
Self { Self {
card_number: Secret::new(card.number), card_number: masking::Secret::new(card.number),
card_exp_month: Secret::new(card.exp_month), card_exp_month: masking::Secret::new(card.exp_month),
card_exp_year: Secret::new(card.exp_year), card_exp_year: masking::Secret::new(card.exp_year),
card_holder_name: Secret::new("stripe_cust".to_owned()), card_holder_name: masking::Secret::new("stripe_cust".to_owned()),
card_cvc: Secret::new(card.cvc), card_cvc: masking::Secret::new(card.cvc),
} }
} }
} }
impl From<StripePaymentMethodDetails> for PaymentMethod { impl From<StripePaymentMethodDetails> for payments::PaymentMethod {
fn from(item: StripePaymentMethodDetails) -> Self { fn from(item: StripePaymentMethodDetails) -> Self {
match item { match item {
StripePaymentMethodDetails::Card(card) => PaymentMethod::Card(CCard::from(card)), StripePaymentMethodDetails::Card(card) => {
StripePaymentMethodDetails::BankTransfer => PaymentMethod::BankTransfer, payments::PaymentMethod::Card(payments::CCard::from(card))
}
StripePaymentMethodDetails::BankTransfer => payments::PaymentMethod::BankTransfer,
} }
} }
} }
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub(crate) struct Shipping { pub(crate) struct Shipping {
pub(crate) address: Option<AddressDetails>, pub(crate) address: Option<payments::AddressDetails>,
pub(crate) name: Option<String>, pub(crate) name: Option<String>,
pub(crate) carrier: Option<String>, pub(crate) carrier: Option<String>,
pub(crate) phone: Option<String>, pub(crate) phone: Option<String>,
pub(crate) tracking_number: Option<String>, pub(crate) tracking_number: Option<String>,
} }
impl From<Shipping> for Address { impl From<Shipping> for payments::Address {
fn from(details: Shipping) -> Self { fn from(details: Shipping) -> Self {
Self { Self {
address: details.address, address: details.address,
phone: Some(PhoneDetails { phone: Some(payments::PhoneDetails {
number: details.phone.map(Secret::new), number: details.phone.map(masking::Secret::new),
country_code: None, country_code: None,
}), }),
} }
@ -134,9 +129,9 @@ pub(crate) struct StripePaymentIntentRequest {
pub(crate) client_secret: Option<String>, pub(crate) client_secret: Option<String>,
} }
impl From<StripePaymentIntentRequest> for PaymentsRequest { impl From<StripePaymentIntentRequest> for payments::PaymentsRequest {
fn from(item: StripePaymentIntentRequest) -> Self { fn from(item: StripePaymentIntentRequest) -> Self {
PaymentsRequest { payments::PaymentsRequest {
amount: item.amount.map(|amount| amount.into()), amount: item.amount.map(|amount| amount.into()),
connector: item.connector, connector: item.connector,
currency: item.currency.as_ref().map(|c| c.to_uppercase()), currency: item.currency.as_ref().map(|c| c.to_uppercase()),
@ -144,31 +139,34 @@ impl From<StripePaymentIntentRequest> for PaymentsRequest {
amount_to_capture: item.amount_capturable, amount_to_capture: item.amount_capturable,
confirm: item.confirm, confirm: item.confirm,
customer_id: item.customer, customer_id: item.customer,
email: item.receipt_email.map(Secret::new), email: item.receipt_email.map(masking::Secret::new),
name: item name: item
.billing_details .billing_details
.as_ref() .as_ref()
.and_then(|b| b.name.as_ref().map(|x| Secret::new(x.to_owned()))), .and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))),
phone: item phone: item
.shipping .shipping
.as_ref() .as_ref()
.and_then(|s| s.phone.as_ref().map(|x| Secret::new(x.to_owned()))), .and_then(|s| s.phone.as_ref().map(|x| masking::Secret::new(x.to_owned()))),
description: item.description, description: item.description,
return_url: item.return_url, return_url: item.return_url,
payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| {
pmd.payment_method_details pmd.payment_method_details
.as_ref() .as_ref()
.map(|spmd| PaymentMethod::from(spmd.to_owned())) .map(|spmd| payments::PaymentMethod::from(spmd.to_owned()))
}), }),
payment_method: item payment_method: item
.payment_method_data .payment_method_data
.as_ref() .as_ref()
.map(|pmd| api_enums::PaymentMethodType::from(pmd.stype.to_owned())), .map(|pmd| api_enums::PaymentMethodType::from(pmd.stype.to_owned())),
shipping: item.shipping.as_ref().map(|s| Address::from(s.to_owned())), shipping: item
.shipping
.as_ref()
.map(|s| payments::Address::from(s.to_owned())),
billing: item billing: item
.billing_details .billing_details
.as_ref() .as_ref()
.map(|b| Address::from(b.to_owned())), .map(|b| payments::Address::from(b.to_owned())),
statement_descriptor_name: item.statement_descriptor, statement_descriptor_name: item.statement_descriptor,
statement_descriptor_suffix: item.statement_descriptor_suffix, statement_descriptor_suffix: item.statement_descriptor_suffix,
metadata: item.metadata, metadata: item.metadata,
@ -235,7 +233,7 @@ pub(crate) struct StripePaymentCancelRequest {
cancellation_reason: Option<CancellationReason>, cancellation_reason: Option<CancellationReason>,
} }
impl From<StripePaymentCancelRequest> for PaymentsCancelRequest { impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest {
fn from(item: StripePaymentCancelRequest) -> Self { fn from(item: StripePaymentCancelRequest) -> Self {
Self { Self {
cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), cancellation_reason: item.cancellation_reason.map(|c| c.to_string()),
@ -258,16 +256,16 @@ pub(crate) struct StripePaymentIntentResponse {
pub(crate) amount_capturable: Option<i64>, pub(crate) amount_capturable: Option<i64>,
pub(crate) currency: String, pub(crate) currency: String,
pub(crate) status: StripePaymentStatus, pub(crate) status: StripePaymentStatus,
pub(crate) client_secret: Option<Secret<String>>, pub(crate) client_secret: Option<masking::Secret<String>>,
#[serde(with = "common_utils::custom_serde::iso8601::option")] #[serde(with = "common_utils::custom_serde::iso8601::option")]
pub(crate) created: Option<time::PrimitiveDateTime>, pub(crate) created: Option<time::PrimitiveDateTime>,
pub(crate) customer: Option<String>, pub(crate) customer: Option<String>,
pub(crate) refunds: Option<Vec<RefundResponse>>, pub(crate) refunds: Option<Vec<refunds::RefundResponse>>,
pub(crate) mandate_id: Option<String>, pub(crate) mandate_id: Option<String>,
} }
impl From<PaymentsResponse> for StripePaymentIntentResponse { impl From<payments::PaymentsResponse> for StripePaymentIntentResponse {
fn from(resp: PaymentsResponse) -> Self { fn from(resp: payments::PaymentsResponse) -> Self {
Self { Self {
object: "payment_intent".to_owned(), object: "payment_intent".to_owned(),
amount: resp.amount, amount: resp.amount,
@ -307,7 +305,7 @@ fn default_limit() -> i64 {
10 10
} }
impl TryFrom<StripePaymentListConstraints> for PaymentListConstraints { impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints {
type Error = error_stack::Report<errors::ApiErrorResponse>; type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> {
Ok(Self { Ok(Self {
@ -349,8 +347,8 @@ pub(crate) struct StripePaymentIntentListResponse {
pub(crate) data: Vec<StripePaymentIntentResponse>, pub(crate) data: Vec<StripePaymentIntentResponse>,
} }
impl From<PaymentListResponse> for StripePaymentIntentListResponse { impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse {
fn from(it: PaymentListResponse) -> Self { fn from(it: payments::PaymentListResponse) -> Self {
Self { Self {
object: "list".to_string(), object: "list".to_string(),
url: "/v1/payment_intents".to_string(), url: "/v1/payment_intents".to_string(),

View File

@ -4,22 +4,22 @@ use actix_web::{get, post, web, HttpRequest, HttpResponse};
use router_env::{tracing, tracing::instrument}; use router_env::{tracing, tracing::instrument};
use crate::{ use crate::{
compatibility::{stripe, wrap}, compatibility::{stripe::errors, wrap},
core::refunds, core::refunds,
routes::AppState, routes,
services::api, services::api,
types::api::refunds::RefundRequest, types::api::refunds as refund_types,
}; };
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("")] #[post("")]
pub(crate) async fn refund_create( pub(crate) async fn refund_create(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Form<types::StripeCreateRefundRequest>, form_payload: web::Form<types::StripeCreateRefundRequest>,
) -> HttpResponse { ) -> HttpResponse {
let payload = form_payload.into_inner(); let payload = form_payload.into_inner();
let create_refund_req: RefundRequest = payload.into(); let create_refund_req: refund_types::RefundRequest = payload.into();
wrap::compatibility_api_wrap::< wrap::compatibility_api_wrap::<
_, _,
@ -28,7 +28,7 @@ pub(crate) async fn refund_create(
_, _,
_, _,
types::StripeCreateRefundResponse, types::StripeCreateRefundResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
@ -42,7 +42,7 @@ pub(crate) async fn refund_create(
#[instrument(skip_all)] #[instrument(skip_all)]
#[get("/{refund_id}")] #[get("/{refund_id}")]
pub(crate) async fn refund_retrieve( pub(crate) async fn refund_retrieve(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
req: HttpRequest, req: HttpRequest,
path: web::Path<String>, path: web::Path<String>,
) -> HttpResponse { ) -> HttpResponse {
@ -54,7 +54,7 @@ pub(crate) async fn refund_retrieve(
_, _,
_, _,
types::StripeCreateRefundResponse, types::StripeCreateRefundResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
@ -75,14 +75,14 @@ pub(crate) async fn refund_retrieve(
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("/{refund_id}")] #[post("/{refund_id}")]
pub(crate) async fn refund_update( pub(crate) async fn refund_update(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
req: HttpRequest, req: HttpRequest,
path: web::Path<String>, path: web::Path<String>,
form_payload: web::Form<types::StripeCreateRefundRequest>, form_payload: web::Form<types::StripeCreateRefundRequest>,
) -> HttpResponse { ) -> HttpResponse {
let refund_id = path.into_inner(); let refund_id = path.into_inner();
let payload = form_payload.into_inner(); let payload = form_payload.into_inner();
let create_refund_update_req: RefundRequest = payload.into(); let create_refund_update_req: refund_types::RefundRequest = payload.into();
wrap::compatibility_api_wrap::< wrap::compatibility_api_wrap::<
_, _,
@ -91,7 +91,7 @@ pub(crate) async fn refund_update(
_, _,
_, _,
types::StripeCreateRefundResponse, types::StripeCreateRefundResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,

View File

@ -2,7 +2,7 @@ use std::{convert::From, default::Default};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::types::api::refunds::{RefundRequest, RefundResponse, RefundStatus}; use crate::types::api::refunds;
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct StripeCreateRefundRequest { pub(crate) struct StripeCreateRefundRequest {
@ -29,7 +29,7 @@ pub(crate) enum StripeRefundStatus {
RequiresAction, RequiresAction,
} }
impl From<StripeCreateRefundRequest> for RefundRequest { impl From<StripeCreateRefundRequest> for refunds::RefundRequest {
fn from(req: StripeCreateRefundRequest) -> Self { fn from(req: StripeCreateRefundRequest) -> Self {
Self { Self {
amount: req.amount, amount: req.amount,
@ -40,19 +40,19 @@ impl From<StripeCreateRefundRequest> for RefundRequest {
} }
} }
impl From<RefundStatus> for StripeRefundStatus { impl From<refunds::RefundStatus> for StripeRefundStatus {
fn from(status: RefundStatus) -> Self { fn from(status: refunds::RefundStatus) -> Self {
match status { match status {
RefundStatus::Succeeded => Self::Succeeded, refunds::RefundStatus::Succeeded => Self::Succeeded,
RefundStatus::Failed => Self::Failed, refunds::RefundStatus::Failed => Self::Failed,
RefundStatus::Pending => Self::Pending, refunds::RefundStatus::Pending => Self::Pending,
RefundStatus::Review => Self::RequiresAction, refunds::RefundStatus::Review => Self::RequiresAction,
} }
} }
} }
impl From<RefundResponse> for StripeCreateRefundResponse { impl From<refunds::RefundResponse> for StripeCreateRefundResponse {
fn from(res: RefundResponse) -> Self { fn from(res: refunds::RefundResponse) -> Self {
Self { Self {
id: res.refund_id, id: res.refund_id,
amount: res.amount, amount: res.amount,

View File

@ -1,21 +1,22 @@
mod types; mod types;
use actix_web::{get, post, web, HttpRequest, HttpResponse}; use actix_web::{get, post, web, HttpRequest, HttpResponse};
use api_models::payments as payment_types;
use error_stack::report; use error_stack::report;
use router_env::{tracing, tracing::instrument}; use router_env::{tracing, tracing::instrument};
use crate::{ use crate::{
compatibility::{stripe, wrap}, compatibility::{stripe::errors, wrap},
core::payments, core::payments,
routes::AppState, routes,
services::api, services::api,
types::api::{self as api_types, PSync, PaymentsRequest, PaymentsRetrieveRequest, Verify}, types::api::{self as api_types},
}; };
#[post("")] #[post("")]
#[instrument(skip_all)] #[instrument(skip_all)]
pub async fn setup_intents_create( pub async fn setup_intents_create(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
@ -24,11 +25,11 @@ pub async fn setup_intents_create(
{ {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let create_payment_req: PaymentsRequest = payload.into(); let create_payment_req: payment_types::PaymentsRequest = payload.into();
wrap::compatibility_api_wrap::< wrap::compatibility_api_wrap::<
_, _,
@ -37,14 +38,14 @@ pub async fn setup_intents_create(
_, _,
_, _,
types::StripeSetupIntentResponse, types::StripeSetupIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
create_payment_req, create_payment_req,
|state, merchant_account, req| { |state, merchant_account, req| {
let connector = req.connector; let connector = req.connector;
payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::Verify, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentCreate, payments::PaymentCreate,
@ -62,11 +63,11 @@ pub async fn setup_intents_create(
#[instrument(skip_all)] #[instrument(skip_all)]
#[get("/{setup_id}")] #[get("/{setup_id}")]
pub async fn setup_intents_retrieve( pub async fn setup_intents_retrieve(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
req: HttpRequest, req: HttpRequest,
path: web::Path<String>, path: web::Path<String>,
) -> HttpResponse { ) -> HttpResponse {
let payload = PaymentsRetrieveRequest { let payload = payment_types::PaymentsRetrieveRequest {
resource_id: api_types::PaymentIdType::PaymentIntentId(path.to_string()), resource_id: api_types::PaymentIdType::PaymentIntentId(path.to_string()),
merchant_id: None, merchant_id: None,
force_sync: true, force_sync: true,
@ -87,13 +88,13 @@ pub async fn setup_intents_retrieve(
_, _,
_, _,
types::StripeSetupIntentResponse, types::StripeSetupIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
payload, payload,
|state, merchant_account, payload| { |state, merchant_account, payload| {
payments::payments_core::<PSync, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentStatus, payments::PaymentStatus,
@ -111,7 +112,7 @@ pub async fn setup_intents_retrieve(
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("/{setup_id}")] #[post("/{setup_id}")]
pub async fn setup_intents_update( pub async fn setup_intents_update(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
@ -122,11 +123,11 @@ pub async fn setup_intents_update(
match qs_config.deserialize_bytes(&form_payload) { match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let mut payload: PaymentsRequest = stripe_payload.into(); let mut payload: payment_types::PaymentsRequest = stripe_payload.into();
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id));
let auth_type; let auth_type;
@ -142,14 +143,14 @@ pub async fn setup_intents_update(
_, _,
_, _,
types::StripeSetupIntentResponse, types::StripeSetupIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
payload, payload,
|state, merchant_account, req| { |state, merchant_account, req| {
let connector = req.connector; let connector = req.connector;
payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::Verify, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentUpdate, payments::PaymentUpdate,
@ -167,7 +168,7 @@ pub async fn setup_intents_update(
#[instrument(skip_all)] #[instrument(skip_all)]
#[post("/{setup_id}/confirm")] #[post("/{setup_id}/confirm")]
pub async fn setup_intents_confirm( pub async fn setup_intents_confirm(
state: web::Data<AppState>, state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>, qs_config: web::Data<serde_qs::Config>,
req: HttpRequest, req: HttpRequest,
form_payload: web::Bytes, form_payload: web::Bytes,
@ -178,11 +179,11 @@ pub async fn setup_intents_confirm(
match qs_config.deserialize_bytes(&form_payload) { match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(err) => {
return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) return api::log_and_return_error_response(report!(errors::ErrorCode::from(err)))
} }
}; };
let mut payload: PaymentsRequest = stripe_payload.into(); let mut payload: payment_types::PaymentsRequest = stripe_payload.into();
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id));
payload.confirm = Some(true); payload.confirm = Some(true);
@ -199,14 +200,14 @@ pub async fn setup_intents_confirm(
_, _,
_, _,
types::StripeSetupIntentResponse, types::StripeSetupIntentResponse,
stripe::ErrorCode, errors::ErrorCode,
>( >(
&state, &state,
&req, &req,
payload, payload,
|state, merchant_account, req| { |state, merchant_account, req| {
let connector = req.connector; let connector = req.connector;
payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>( payments::payments_core::<api_types::Verify, api_types::PaymentsResponse, _, _, _>(
state, state,
merchant_account, merchant_account,
payments::PaymentConfirm, payments::PaymentConfirm,

View File

@ -1,31 +1,27 @@
use api_models::{payments, refunds};
use router_env::logger; use router_env::logger;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{
core::errors, core::errors,
pii::Secret, types::api::{self as api_types, enums as api_enums},
types::api::{
self as api_types, enums as api_enums, Address, AddressDetails, CCard,
PaymentListConstraints, PaymentMethod, PaymentsCancelRequest, PaymentsRequest,
PaymentsResponse, PhoneDetails, RefundResponse,
},
}; };
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub(crate) struct StripeBillingDetails { pub(crate) struct StripeBillingDetails {
pub(crate) address: Option<AddressDetails>, pub(crate) address: Option<payments::AddressDetails>,
pub(crate) email: Option<String>, pub(crate) email: Option<String>,
pub(crate) name: Option<String>, pub(crate) name: Option<String>,
pub(crate) phone: Option<String>, pub(crate) phone: Option<String>,
} }
impl From<StripeBillingDetails> for Address { impl From<StripeBillingDetails> for payments::Address {
fn from(details: StripeBillingDetails) -> Self { fn from(details: StripeBillingDetails) -> Self {
Self { Self {
address: details.address, address: details.address,
phone: Some(PhoneDetails { phone: Some(payments::PhoneDetails {
number: details.phone.map(Secret::new), number: details.phone.map(masking::Secret::new),
country_code: None, country_code: None,
}), }),
} }
@ -72,41 +68,43 @@ pub(crate) enum StripePaymentMethodDetails {
BankTransfer, BankTransfer,
} }
impl From<StripeCard> for CCard { impl From<StripeCard> for payments::CCard {
fn from(card: StripeCard) -> Self { fn from(card: StripeCard) -> Self {
Self { Self {
card_number: Secret::new(card.number), card_number: masking::Secret::new(card.number),
card_exp_month: Secret::new(card.exp_month), card_exp_month: masking::Secret::new(card.exp_month),
card_exp_year: Secret::new(card.exp_year), card_exp_year: masking::Secret::new(card.exp_year),
card_holder_name: Secret::new("stripe_cust".to_owned()), card_holder_name: masking::Secret::new("stripe_cust".to_owned()),
card_cvc: Secret::new(card.cvc), card_cvc: masking::Secret::new(card.cvc),
} }
} }
} }
impl From<StripePaymentMethodDetails> for PaymentMethod { impl From<StripePaymentMethodDetails> for payments::PaymentMethod {
fn from(item: StripePaymentMethodDetails) -> Self { fn from(item: StripePaymentMethodDetails) -> Self {
match item { match item {
StripePaymentMethodDetails::Card(card) => PaymentMethod::Card(CCard::from(card)), StripePaymentMethodDetails::Card(card) => {
StripePaymentMethodDetails::BankTransfer => PaymentMethod::BankTransfer, payments::PaymentMethod::Card(payments::CCard::from(card))
}
StripePaymentMethodDetails::BankTransfer => payments::PaymentMethod::BankTransfer,
} }
} }
} }
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub(crate) struct Shipping { pub(crate) struct Shipping {
pub(crate) address: Option<AddressDetails>, pub(crate) address: Option<payments::AddressDetails>,
pub(crate) name: Option<String>, pub(crate) name: Option<String>,
pub(crate) carrier: Option<String>, pub(crate) carrier: Option<String>,
pub(crate) phone: Option<String>, pub(crate) phone: Option<String>,
pub(crate) tracking_number: Option<String>, pub(crate) tracking_number: Option<String>,
} }
impl From<Shipping> for Address { impl From<Shipping> for payments::Address {
fn from(details: Shipping) -> Self { fn from(details: Shipping) -> Self {
Self { Self {
address: details.address, address: details.address,
phone: Some(PhoneDetails { phone: Some(payments::PhoneDetails {
number: details.phone.map(Secret::new), number: details.phone.map(masking::Secret::new),
country_code: None, country_code: None,
}), }),
} }
@ -129,40 +127,43 @@ pub(crate) struct StripeSetupIntentRequest {
pub(crate) client_secret: Option<String>, pub(crate) client_secret: Option<String>,
} }
impl From<StripeSetupIntentRequest> for PaymentsRequest { impl From<StripeSetupIntentRequest> for payments::PaymentsRequest {
fn from(item: StripeSetupIntentRequest) -> Self { fn from(item: StripeSetupIntentRequest) -> Self {
PaymentsRequest { payments::PaymentsRequest {
amount: Some(api_types::Amount::Zero), amount: Some(api_types::Amount::Zero),
currency: Some(api_enums::Currency::default().to_string()), currency: Some(api_enums::Currency::default().to_string()),
capture_method: None, capture_method: None,
amount_to_capture: None, amount_to_capture: None,
confirm: item.confirm, confirm: item.confirm,
customer_id: item.customer, customer_id: item.customer,
email: item.receipt_email.map(Secret::new), email: item.receipt_email.map(masking::Secret::new),
name: item name: item
.billing_details .billing_details
.as_ref() .as_ref()
.and_then(|b| b.name.as_ref().map(|x| Secret::new(x.to_owned()))), .and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))),
phone: item phone: item
.shipping .shipping
.as_ref() .as_ref()
.and_then(|s| s.phone.as_ref().map(|x| Secret::new(x.to_owned()))), .and_then(|s| s.phone.as_ref().map(|x| masking::Secret::new(x.to_owned()))),
description: item.description, description: item.description,
return_url: item.return_url, return_url: item.return_url,
payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| {
pmd.payment_method_details pmd.payment_method_details
.as_ref() .as_ref()
.map(|spmd| PaymentMethod::from(spmd.to_owned())) .map(|spmd| payments::PaymentMethod::from(spmd.to_owned()))
}), }),
payment_method: item payment_method: item
.payment_method_data .payment_method_data
.as_ref() .as_ref()
.map(|pmd| api_enums::PaymentMethodType::from(pmd.stype.to_owned())), .map(|pmd| api_enums::PaymentMethodType::from(pmd.stype.to_owned())),
shipping: item.shipping.as_ref().map(|s| Address::from(s.to_owned())), shipping: item
.shipping
.as_ref()
.map(|s| payments::Address::from(s.to_owned())),
billing: item billing: item
.billing_details .billing_details
.as_ref() .as_ref()
.map(|b| Address::from(b.to_owned())), .map(|b| payments::Address::from(b.to_owned())),
statement_descriptor_name: item.statement_descriptor, statement_descriptor_name: item.statement_descriptor,
statement_descriptor_suffix: item.statement_descriptor_suffix, statement_descriptor_suffix: item.statement_descriptor_suffix,
metadata: item.metadata, metadata: item.metadata,
@ -232,7 +233,7 @@ pub(crate) struct StripePaymentCancelRequest {
cancellation_reason: Option<CancellationReason>, cancellation_reason: Option<CancellationReason>,
} }
impl From<StripePaymentCancelRequest> for PaymentsCancelRequest { impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest {
fn from(item: StripePaymentCancelRequest) -> Self { fn from(item: StripePaymentCancelRequest) -> Self {
Self { Self {
cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), cancellation_reason: item.cancellation_reason.map(|c| c.to_string()),
@ -245,16 +246,16 @@ pub(crate) struct StripeSetupIntentResponse {
pub(crate) id: Option<String>, pub(crate) id: Option<String>,
pub(crate) object: String, pub(crate) object: String,
pub(crate) status: StripeSetupStatus, pub(crate) status: StripeSetupStatus,
pub(crate) client_secret: Option<Secret<String>>, pub(crate) client_secret: Option<masking::Secret<String>>,
#[serde(with = "common_utils::custom_serde::iso8601::option")] #[serde(with = "common_utils::custom_serde::iso8601::option")]
pub(crate) created: Option<time::PrimitiveDateTime>, pub(crate) created: Option<time::PrimitiveDateTime>,
pub(crate) customer: Option<String>, pub(crate) customer: Option<String>,
pub(crate) refunds: Option<Vec<RefundResponse>>, pub(crate) refunds: Option<Vec<refunds::RefundResponse>>,
pub(crate) mandate_id: Option<String>, pub(crate) mandate_id: Option<String>,
} }
impl From<PaymentsResponse> for StripeSetupIntentResponse { impl From<payments::PaymentsResponse> for StripeSetupIntentResponse {
fn from(resp: PaymentsResponse) -> Self { fn from(resp: payments::PaymentsResponse) -> Self {
Self { Self {
object: "setup_intent".to_owned(), object: "setup_intent".to_owned(),
status: StripeSetupStatus::from(resp.status), status: StripeSetupStatus::from(resp.status),
@ -290,7 +291,7 @@ fn default_limit() -> i64 {
10 10
} }
impl TryFrom<StripePaymentListConstraints> for PaymentListConstraints { impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints {
type Error = error_stack::Report<errors::ApiErrorResponse>; type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> {
Ok(Self { Ok(Self {

View File

@ -8,7 +8,7 @@ use serde::Serialize;
use crate::{ use crate::{
core::errors::{self, RouterResult}, core::errors::{self, RouterResult},
routes, routes,
services::{api, build_redirection_form, logger, BachResponse}, services::{api, logger},
types::storage, types::storage,
}; };
@ -23,7 +23,7 @@ pub(crate) async fn compatibility_api_wrap<'a, 'b, A, T, Q, F, Fut, S, E>(
where where
A: Into<api::ApiAuthentication<'a>> + std::fmt::Debug, A: Into<api::ApiAuthentication<'a>> + std::fmt::Debug,
F: Fn(&'b routes::AppState, storage::MerchantAccount, T) -> Fut, F: Fn(&'b routes::AppState, storage::MerchantAccount, T) -> Fut,
Fut: Future<Output = RouterResult<BachResponse<Q>>>, Fut: Future<Output = RouterResult<api::BachResponse<Q>>>,
Q: Serialize + std::fmt::Debug + 'a, Q: Serialize + std::fmt::Debug + 'a,
S: From<Q> + Serialize, S: From<Q> + Serialize,
E: From<errors::ApiErrorResponse> + Serialize + error_stack::Context + actix_web::ResponseError, E: From<errors::ApiErrorResponse> + Serialize + error_stack::Context + actix_web::ResponseError,
@ -32,7 +32,7 @@ where
let api_authentication = api_authentication.into(); let api_authentication = api_authentication.into();
let resp = api::server_wrap_util(state, request, payload, func, api_authentication).await; let resp = api::server_wrap_util(state, request, payload, func, api_authentication).await;
match resp { match resp {
Ok(BachResponse::Json(router_resp)) => { Ok(api::BachResponse::Json(router_resp)) => {
let pg_resp = S::try_from(router_resp); let pg_resp = S::try_from(router_resp);
match pg_resp { match pg_resp {
Ok(pg_resp) => match serde_json::to_string(&pg_resp) { Ok(pg_resp) => match serde_json::to_string(&pg_resp) {
@ -54,9 +54,10 @@ where
), ),
} }
} }
Ok(BachResponse::StatusOk) => api::http_response_ok(), Ok(api::BachResponse::StatusOk) => api::http_response_ok(),
Ok(BachResponse::TextPlain(text)) => api::http_response_plaintext(text), Ok(api::BachResponse::TextPlain(text)) => api::http_response_plaintext(text),
Ok(BachResponse::JsonForRedirection(response)) => match serde_json::to_string(&response) { Ok(api::BachResponse::JsonForRedirection(response)) => {
match serde_json::to_string(&response) {
Ok(res) => api::http_redirect_response(res, response), Ok(res) => api::http_redirect_response(res, response),
Err(_) => api::http_response_err( Err(_) => api::http_response_err(
r#"{ r#"{
@ -65,8 +66,9 @@ where
} }
}"#, }"#,
), ),
}, }
Ok(BachResponse::Form(form_data)) => build_redirection_form(&form_data) }
Ok(api::BachResponse::Form(form_data)) => api::build_redirection_form(&form_data)
.respond_to(request) .respond_to(request)
.map_into_boxed_body(), .map_into_boxed_body(),
Err(error) => { Err(error) => {