text
string | file_path
string | module
string | type
string | tokens
int64 | language
string | struct_name
string | type_name
string | trait_name
string | impl_type
string | function_name
string | source
string | section
string | keys
list | macro_type
string | url
string | title
string | chunk_index
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
amount_converter_to_float_major_unit: &FloatMajorUnitForConnector,
amount_converter_to_string_minor_unit: &StringMinorUnitForConnector,
}
}
|
crates/hyperswitch_connectors/src/connectors/trustpay.rs
|
hyperswitch_connectors
|
function_signature
| 58
|
rust
| null | null | null | null |
new
| null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.SamsungPayMerchantPaymentInformation
{
"type": "object",
"required": [
"name",
"country_code"
],
"properties": {
"name": {
"type": "string",
"description": "Merchant name, this will be displayed on the Samsung Pay screen"
},
"url": {
"type": "string",
"description": "Merchant domain that process payments, required for web payments",
"nullable": true
},
"country_code": {
"$ref": "#/components/schemas/CountryAlpha2"
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 137
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"SamsungPayMerchantPaymentInformation"
] | null | null | null | null |
impl api::PaymentVoid for Worldpay {}
|
crates/hyperswitch_connectors/src/connectors/worldpay.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Worldpay
|
api::PaymentVoid for
|
impl api::PaymentVoid for for Worldpay
| null | null | null | null | null | null | null | null |
impl webhooks::IncomingWebhook for Phonepe {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
|
crates/hyperswitch_connectors/src/connectors/phonepe.rs
|
hyperswitch_connectors
|
impl_block
| 210
|
rust
| null |
Phonepe
|
webhooks::IncomingWebhook for
|
impl webhooks::IncomingWebhook for for Phonepe
| null | null | null | null | null | null | null | null |
pub struct Billwerk {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
|
crates/hyperswitch_connectors/src/connectors/billwerk.rs
|
hyperswitch_connectors
|
struct_definition
| 26
|
rust
|
Billwerk
| null | null | null | null | null | null | null | null | null | null | null |
pub fn new(value: FredRedisValue) -> Self {
Self { inner: value }
}
|
crates/redis_interface/src/types.rs
|
redis_interface
|
function_signature
| 21
|
rust
| null | null | null | null |
new
| null | null | null | null | null | null | null |
pub struct FlexitiRefundRequest {
pub amount: FloatMajorUnit,
}
|
crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 17
|
rust
|
FlexitiRefundRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct VgsAliasItem {
alias: String,
format: String,
}
|
crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 18
|
rust
|
VgsAliasItem
| null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorValidation for Redsys {}
|
crates/hyperswitch_connectors/src/connectors/redsys.rs
|
hyperswitch_connectors
|
impl_block
| 7
|
rust
| null |
Redsys
|
ConnectorValidation for
|
impl ConnectorValidation for for Redsys
| null | null | null | null | null | null | null | null |
pub struct NoonPaymentsResponseResult {
order: NoonPaymentsOrderResponse,
checkout_data: Option<NoonCheckoutData>,
subscription: Option<NoonSubscriptionObject>,
}
|
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 37
|
rust
|
NoonPaymentsResponseResult
| null | null | null | null | null | null | null | null | null | null | null |
pub trait GlobalStorageInterface:
Send
+ Sync
+ dyn_clone::DynClone
+ user::UserInterface
+ user_role::UserRoleInterface
+ user_key_store::UserKeyStoreInterface
+ role::RoleInterface
+ RedisConnInterface
+ 'static
{
fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)>;
}
|
crates/router/src/db.rs
|
router
|
trait_definition
| 91
|
rust
| null | null |
GlobalStorageInterface
| null | null | null | null | null | null | null | null | null |
pub async fn payments_update(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsUpdate;
let mut payload = json_payload.into_inner();
if let Err(err) = payload
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
{
return api::log_and_return_error_response(err.into());
};
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id));
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
authorize_verify_select::<_>(
payments::PaymentUpdate,
state,
req_state,
merchant_context,
auth.profile_id,
HeaderPayload::default(),
req,
auth_flow,
)
},
&*auth_type,
locking_action,
))
.await
}
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| 424
|
rust
| null | null | null | null |
payments_update
| null | null | null | null | null | null | null |
pub async fn check_if_profile_id_is_present_in_payment_intent(
payment_id: PaymentId,
state: &SessionState,
auth_data: &AuthenticationData,
) -> CustomResult<(), errors::ApiErrorResponse> {
let db = &*state.store;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
auth_data.merchant_account.get_id(),
&auth_data.key_store,
auth_data.merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
utils::validate_profile_id_from_auth_layer(auth_data.profile_id.clone(), &payment_intent)
}
|
crates/router/src/core/verification/utils.rs
|
router
|
function_signature
| 146
|
rust
| null | null | null | null |
check_if_profile_id_is_present_in_payment_intent
| null | null | null | null | null | null | null |
pub fn new(method: Method, url: &str) -> Self {
Self {
method,
url: String::from(url),
headers: std::collections::HashSet::new(),
certificate: None,
certificate_key: None,
body: None,
ca_certificate: None,
}
}
|
crates/common_utils/src/request.rs
|
common_utils
|
function_signature
| 66
|
rust
| null | null | null | null |
new
| null | null | null | null | null | null | null |
pub async fn get_dispute_evidence_block(
state: &SessionState,
merchant_context: &domain::MerchantContext,
evidence_type: EvidenceType,
file_id: String,
) -> CustomResult<api_models::disputes::DisputeEvidenceBlock, errors::ApiErrorResponse> {
let file_metadata = state
.store
.find_file_metadata_by_merchant_id_file_id(
merchant_context.get_merchant_account().get_id(),
&file_id,
)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)
.attach_printable("Unable to retrieve file_metadata")?;
let file_metadata_response =
api_models::files::FileMetadataResponse::foreign_from(file_metadata);
Ok(api_models::disputes::DisputeEvidenceBlock {
evidence_type,
file_metadata_response,
})
}
|
crates/router/src/core/disputes/transformers.rs
|
router
|
function_signature
| 180
|
rust
| null | null | null | null |
get_dispute_evidence_block
| null | null | null | null | null | null | null |
pub struct HipayMaintenanceRequest {
operation: Operation,
currency: Option<enums::Currency>,
amount: Option<StringMajorUnit>,
}
|
crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 30
|
rust
|
HipayMaintenanceRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct BankAccountConnectorDetails {
pub connector: String,
pub account_id: masking::Secret<String>,
pub mca_id: id_type::MerchantConnectorAccountId,
pub access_token: BankAccountAccessCreds,
}
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
| 48
|
rust
|
BankAccountConnectorDetails
| null | null | null | null | null | null | null | null | null | null | null |
impl api::ConnectorAccessToken for Rapyd {}
|
crates/hyperswitch_connectors/src/connectors/rapyd.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Rapyd
|
api::ConnectorAccessToken for
|
impl api::ConnectorAccessToken for for Rapyd
| null | null | null | null | null | null | null | null |
File: crates/router_derive/src/macros/try_get_enum.rs
Public functions: 1
Public structs: 1
use proc_macro2::Span;
use quote::ToTokens;
use syn::{parse::Parse, punctuated::Punctuated};
mod try_get_keyword {
use syn::custom_keyword;
custom_keyword!(error_type);
}
#[derive(Debug)]
pub struct TryGetEnumMeta {
error_type: syn::Ident,
variant: syn::Ident,
}
impl Parse for TryGetEnumMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let error_type = input.parse()?;
_ = input.parse::<syn::Token![::]>()?;
let variant = input.parse()?;
Ok(Self {
error_type,
variant,
})
}
}
trait TryGetDeriveInputExt {
/// Get all the error metadata associated with an enum.
fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>>;
}
impl TryGetDeriveInputExt for syn::DeriveInput {
fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>> {
super::helpers::get_metadata_inner("error", &self.attrs)
}
}
impl ToTokens for TryGetEnumMeta {
fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {}
}
/// Try and get the variants for an enum
pub fn try_get_enum_variant(
input: syn::DeriveInput,
) -> Result<proc_macro2::TokenStream, syn::Error> {
let name = &input.ident;
let parsed_error_type = input.get_metadata()?;
let (error_type, error_variant) = parsed_error_type
.first()
.ok_or(syn::Error::new(
Span::call_site(),
"One error should be specified",
))
.map(|error_struct| (&error_struct.error_type, &error_struct.variant))?;
let (impl_generics, generics, where_clause) = input.generics.split_for_impl();
let variants = get_enum_variants(&input.data)?;
let try_into_fns = variants.iter().map(|variant| {
let variant_name = &variant.ident;
let variant_field = get_enum_variant_field(variant)?;
let variant_types = variant_field.iter().map(|f|f.ty.clone());
let try_into_fn = syn::Ident::new(
&format!("try_into_{}", variant_name.to_string().to_lowercase()),
Span::call_site(),
);
Ok(quote::quote! {
pub fn #try_into_fn(self)->Result<(#(#variant_types),*),error_stack::Report<#error_type>> {
match self {
Self::#variant_name(inner) => Ok(inner),
_=> Err(error_stack::report!(#error_type::#error_variant)),
}
}
})
}).collect::<Result<Vec<proc_macro2::TokenStream>,syn::Error>>()?;
let expanded = quote::quote! {
impl #impl_generics #name #generics #where_clause {
#(#try_into_fns)*
}
};
Ok(expanded)
}
/// Get variants from Enum
fn get_enum_variants(data: &syn::Data) -> syn::Result<Punctuated<syn::Variant, syn::token::Comma>> {
if let syn::Data::Enum(syn::DataEnum { variants, .. }) = data {
Ok(variants.clone())
} else {
Err(super::helpers::non_enum_error())
}
}
/// Get Field from an enum variant
fn get_enum_variant_field(
variant: &syn::Variant,
) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> {
let field = match variant.fields.clone() {
syn::Fields::Unnamed(un) => un.unnamed,
syn::Fields::Named(n) => n.named,
syn::Fields::Unit => {
return Err(super::helpers::syn_error(
Span::call_site(),
"The enum is a unit variant it's not supported",
))
}
};
Ok(field)
}
|
crates/router_derive/src/macros/try_get_enum.rs
|
router_derive
|
full_file
| 886
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct BankOfAmericaClientReferenceResponse {
id: String,
status: BankofamericaPaymentStatus,
client_reference_information: ClientReferenceInformation,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
risk_information: Option<ClientRiskInformation>,
token_information: Option<BankOfAmericaTokenInformation>,
error_information: Option<BankOfAmericaErrorInformation>,
issuer_information: Option<IssuerInformation>,
sender_information: Option<SenderInformation>,
payment_account_information: Option<PaymentAccountInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 157
|
rust
|
BankOfAmericaClientReferenceResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn find_by_merchant_id_payment_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
None,
None,
Some(dsl::created_at.asc()),
)
.await
}
|
crates/diesel_models/src/query/authorization.rs
|
diesel_models
|
function_signature
| 131
|
rust
| null | null | null | null |
find_by_merchant_id_payment_id
| null | null | null | null | null | null | null |
impl api::PaymentSync for Tokenio {}
|
crates/hyperswitch_connectors/src/connectors/tokenio.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Tokenio
|
api::PaymentSync for
|
impl api::PaymentSync for for Tokenio
| null | null | null | null | null | null | null | null |
### Miscellaneous Tasks
- **CODEOWNERS:** Add hyperswitch-maintainers as default owners for all files ([#1210](https://github.com/juspay/hyperswitch/pull/1210)) ([`985670d`](https://github.com/juspay/hyperswitch/commit/985670da9c90cbc904162d7863c9c508f5cf5e19))
- **git-cliff:** Simplify `git-cliff` config files ([#1213](https://github.com/juspay/hyperswitch/pull/1213)) ([`bd0069e`](https://github.com/juspay/hyperswitch/commit/bd0069e2a8bd3c3389c92590c688ce945cd7ebec))
### Revert
- **connector:** Fix stripe status to attempt status map ([#1179](https://github.com/juspay/hyperswitch/pull/1179)) ([`bd8868e`](https://github.com/juspay/hyperswitch/commit/bd8868efd00748cf64c46519c4ed7ba04ad06d5e))
- Fix(connector): Added signifyd to routableconnectors for frm ([#1203](https://github.com/juspay/hyperswitch/pull/1203)) ([`dbc5bc5`](https://github.com/juspay/hyperswitch/commit/dbc5bc538a218ae287e96c44de0223c26c1583f0))
- - -
## 0.5.14 (2023-05-16)
### Features
- **connector:**
- [Stripe] implement Bancontact Bank Redirect for stripe ([#1169](https://github.com/juspay/hyperswitch/pull/1169)) ([`5b22e96`](https://github.com/juspay/hyperswitch/commit/5b22e967981b604be6070f5b373555756a5c62f7))
- [Noon] Add script generated template code ([#1164](https://github.com/juspay/hyperswitch/pull/1164)) ([`bfaf75f`](https://github.com/juspay/hyperswitch/commit/bfaf75fca38e535ceb3ea4327e252d807fb61892))
- [Adyen] implement BACS Direct Debits for Adyen ([#1159](https://github.com/juspay/hyperswitch/pull/1159)) ([`9f47f20`](https://github.com/juspay/hyperswitch/commit/9f47f2070216eb8c64db14eae555073a507cc634))
- **router:** Add retrieve dispute evidence API ([#1114](https://github.com/juspay/hyperswitch/pull/1114)) ([`354ee01`](https://github.com/juspay/hyperswitch/commit/354ee0137a968862e545d9b437ade27aa0b0f8f3))
- Add accounts in-memory cache ([#1086](https://github.com/juspay/hyperswitch/pull/1086)) ([`da4d721`](https://github.com/juspay/hyperswitch/commit/da4d721424d329af618a63034aabe2d9248eb041))
### Bug Fixes
- **connector:**
- [Checkout] Change error handling condition for empty response ([#1168](https://github.com/juspay/hyperswitch/pull/1168)) ([`e3fcfdd`](https://github.com/juspay/hyperswitch/commit/e3fcfdd3377df298058b5e1f69f0e553c09ac603))
- Change payment method handling in dummy connector ([#1175](https://github.com/juspay/hyperswitch/pull/1175)) ([`32a3722`](https://github.com/juspay/hyperswitch/commit/32a3722f073c3ea22220abfa62034e476ee8acef))
### Refactors
- **connector:** Update error handling for Paypal, Checkout, Mollie to include detailed messages ([#1150](https://github.com/juspay/hyperswitch/pull/1150)) ([`e044c2f`](https://github.com/juspay/hyperswitch/commit/e044c2fd9a4464e59ffc372b9333af6acbc9809a))
### Documentation
- **CHANGELOG:** Add changelog for 0.5.13 ([#1166](https://github.com/juspay/hyperswitch/pull/1166)) ([`94fe1af`](https://github.com/juspay/hyperswitch/commit/94fe1af1b0bce3b4ecaef8665909fc8f5cd4bbbb))
- - -
## 0.5.13 (2023-05-15)
### Features
- **config:** Add API route `set_config` ([#1144](https://github.com/juspay/hyperswitch/pull/1144)) ([`f31926b`](https://github.com/juspay/hyperswitch/commit/f31926b833557f18f93620d34765c90ac16fbeeb))
- **connector:**
- Add payment, refund urls for dummy connector ([#1084](https://github.com/juspay/hyperswitch/pull/1084)) ([`fee0e9d`](https://github.com/juspay/hyperswitch/commit/fee0e9dadd2e20c5c75dcee50de0e53f4e5e6deb))
- [ACI] Implement Trustly Bank Redirect ([#1130](https://github.com/juspay/hyperswitch/pull/1130)) ([`46b40ec`](https://github.com/juspay/hyperswitch/commit/46b40ecce540b61eced7156555c0fcdcec170405))
- Add multiple dummy connectors and enable them ([#1147](https://github.com/juspay/hyperswitch/pull/1147)) ([`8a35f7c`](https://github.com/juspay/hyperswitch/commit/8a35f7c926f3cbd0d5cd3c2c9470575246985ca3))
- [ACI] Implement Alipay and MB WAY Wallets ([#1140](https://github.com/juspay/hyperswitch/pull/1140)) ([`d7cfb4a`](https://github.com/juspay/hyperswitch/commit/d7cfb4a179083580a7e195fa07077af23a262ceb))
- [Stripe] Implement Przelewy24 bank redirect ([#1111](https://github.com/juspay/hyperswitch/pull/1111)) ([`54ff02d`](https://github.com/juspay/hyperswitch/commit/54ff02d9ddb4cbe2f085f894c833b9800ce8d597))
- **error:**
- Add feature-gated stacktrace to error received from API ([#1104](https://github.com/juspay/hyperswitch/pull/1104)) ([`bf2352b`](https://github.com/juspay/hyperswitch/commit/bf2352b14ae7d7343474424be0f0a4b0fee1b0f2))
- Add `DateTimeParsingError` and `EmailParsingError` variants to `ParsingError` enum ([#1146](https://github.com/juspay/hyperswitch/pull/1146)) ([`7eed8e7`](https://github.com/juspay/hyperswitch/commit/7eed8e7f3e84a7ab4ce8bd4b7892a931211dbe3f))
- **payment_request:** Add field `amount` to `OrderDetails` and make `order_details` a `Vec` in `payments_create` request ([#964](https://github.com/juspay/hyperswitch/pull/964)) ([`60e8c73`](https://github.com/juspay/hyperswitch/commit/60e8c7317a2d1cc99f0179479891565f990df685))
- **router:**
- Add payment, refund routes for dummy connector ([#1071](https://github.com/juspay/hyperswitch/pull/1071)) ([`822fc69`](https://github.com/juspay/hyperswitch/commit/822fc695a38560e6ea4ff13bc837d46214ee9249))
- Add attach dispute evidence api ([#1070](https://github.com/juspay/hyperswitch/pull/1070)) ([`a5756aa`](https://github.com/juspay/hyperswitch/commit/a5756aaecf1b96ef4d04c57592b85f2a20da6639))
### Bug Fixes
- **connector:**
- [Adyen] fix status mapping for Adyen authorize, capture, refund API ([#1149](https://github.com/juspay/hyperswitch/pull/1149)) ([`2932a5f`](https://github.com/juspay/hyperswitch/commit/2932a5f0ff5aa8dabd69fc683b5c688a20c405f9))
- Fix Stripe status to attempt status map ([#1132](https://github.com/juspay/hyperswitch/pull/1132)) ([`8b85647`](https://github.com/juspay/hyperswitch/commit/8b85647a169d1d3ea59d2b472eabb99482f71eda))
- **mandate:** Allow card details to be provided in case of network transaction id ([#1138](https://github.com/juspay/hyperswitch/pull/1138)) ([`cc121d0`](https://github.com/juspay/hyperswitch/commit/cc121d0febcb397a989e512928d33a8cff2fbdee))
- - -
## 0.5.12 (2023-05-11)
### Features
- **Connector:** [ACI] Implement Przelewy24 Bank Redirect ([#1064](https://github.com/juspay/hyperswitch/pull/1064)) ([`cef8914`](https://github.com/juspay/hyperswitch/commit/cef8914372fa051f074e89fc76b76c6aee0d7bca))
- **connector:**
- [Iatapay] Implement AccessTokenAuth, Authorize, PSync, Refund, RSync and testcases ([#1034](https://github.com/juspay/hyperswitch/pull/1034)) ([`a2527b5`](https://github.com/juspay/hyperswitch/commit/a2527b5b2af0a72422e1169f0827b6c55e21d673))
- [bitpay] Add new crypto connector bitpay & testcases for all crypto connectors ([#919](https://github.com/juspay/hyperswitch/pull/919)) ([`f70f10a`](https://github.com/juspay/hyperswitch/commit/f70f10aac58cce805b150badf634271c0f98d478))
- Add connector nmi with card, applepay and googlepay support ([#771](https://github.com/juspay/hyperswitch/pull/771)) ([`baf5fd9`](https://github.com/juspay/hyperswitch/commit/baf5fd91cf7fbb9f787e1ba137d1a3c597fe44ef))
- [ACI] Implement Interac Online Bank Redirect ([#1108](https://github.com/juspay/hyperswitch/pull/1108)) ([`0177f1d`](https://github.com/juspay/hyperswitch/commit/0177f1d1b90bfa6bfb817bf282f3fb1f52eae7f6))
- **pm_list:** Add pm list support for bank_debits ([#1120](https://github.com/juspay/hyperswitch/pull/1120)) ([`dfc6be4`](https://github.com/juspay/hyperswitch/commit/dfc6be4e4f3333ae4639bf4b98c4ec834a66f460))
### Bug Fixes
- **connector:** Fix checkout error response type ([#1124](https://github.com/juspay/hyperswitch/pull/1124)) ([`5fd1614`](https://github.com/juspay/hyperswitch/commit/5fd16146dba52f65f7c5fe26f0a7526875e4e4e2))
- **connector_customer:** Create connector_customer on requirement basis ([#1097](https://github.com/juspay/hyperswitch/pull/1097)) ([`e833a1d`](https://github.com/juspay/hyperswitch/commit/e833a1ddeeae06cd58cb9d6fc760d8e3b0d82b6b))
- **google_pay:** Allow custom fields in `GpayTokenParameters` for google pay via stripe ([#1125](https://github.com/juspay/hyperswitch/pull/1125)) ([`f790099`](https://github.com/juspay/hyperswitch/commit/f790099368ed6ed73ecc729cb18b85e0c6b5f809))
- **mandate:** Only trigger mandate procedure on successful connector call ([#1122](https://github.com/juspay/hyperswitch/pull/1122)) ([`a904d2b`](https://github.com/juspay/hyperswitch/commit/a904d2b4d945c8ecaacae41bf44c6a2ce6ac632e))
- **payments:** Fix address_insert error propagation in get_address_for_payment_request function ([#1079](https://github.com/juspay/hyperswitch/pull/1079)) ([`da3b520`](https://github.com/juspay/hyperswitch/commit/da3b5201b4e30a6047bbf3069b2542482f8f9e51))
- **router:** Fix webhooks flow for checkout connector ([#1126](https://github.com/juspay/hyperswitch/pull/1126)) ([`7f3ceb4`](https://github.com/juspay/hyperswitch/commit/7f3ceb42fb95a117a39bc679ce2f7830bffbec54))
### Refactors
- **api_models:**
- Remove unused mapping of attempt status to intent status ([#1127](https://github.com/juspay/hyperswitch/pull/1127)) ([`45ccc41`](https://github.com/juspay/hyperswitch/commit/45ccc410eacd425c6b68179ffa7b4258ab341e61))
- Derive serialize on`PaymentsCaptureRequest` struct ([#1129](https://github.com/juspay/hyperswitch/pull/1129)) ([`e779ee7`](https://github.com/juspay/hyperswitch/commit/e779ee78a47e1b6d08c4df4afc3762c33db51eeb))
- **errors:** Add parsing error types for context info ([#911](https://github.com/juspay/hyperswitch/pull/911)) ([`0d46690`](https://github.com/juspay/hyperswitch/commit/0d466905024018e7ca5a7acc66ee98784337e7d3))
### Revert
- Refactor(merchant_account): add back `api_key` field for backward compatibility ([#761](https://github.com/juspay/hyperswitch/pull/761)) ([#1062](https://github.com/juspay/hyperswitch/pull/1062)) ([`f481abb`](https://github.com/juspay/hyperswitch/commit/f481abb8551f3ec5e495cf9916d9d8a5cecd62da))
- - -
## 0.5.11 (2023-05-10)
### Features
- **Connector:**
- [Adyen]Implement ACH Direct Debits for Adyen ([#1033](https://github.com/juspay/hyperswitch/pull/1033)) ([`eee55bd`](https://github.com/juspay/hyperswitch/commit/eee55bdfbe67e5f4be7ed7e388f5ed93e70165ff))
- [Stripe] Implemented Alipay Digital Wallet ([#1048](https://github.com/juspay/hyperswitch/pull/1048)) ([`7c7185b`](https://github.com/juspay/hyperswitch/commit/7c7185bc1a783efe81a994fef179a73313954d9d))
- [Stripe] Implement Wechatpay Digital Wallet ([#1049](https://github.com/juspay/hyperswitch/pull/1049)) ([`93947ea`](https://github.com/juspay/hyperswitch/commit/93947eaf258ddb74315f4776b2faec87f42e6216))
- **cards:** Add credit card number validation ([#889](https://github.com/juspay/hyperswitch/pull/889)) ([`d6e71b9`](https://github.com/juspay/hyperswitch/commit/d6e71b959ddbdc99411fc7d669df61f373de4e32))
- **connector:**
- Mandates for alternate payment methods via Adyen ([#1046](https://github.com/juspay/hyperswitch/pull/1046)) ([`4403634`](https://github.com/juspay/hyperswitch/commit/4403634dda41b1b7fbbe56ee6177722bcbe2e29b))
- Add klarna, afterpay support in Nuvei ([#1081](https://github.com/juspay/hyperswitch/pull/1081)) ([`0bb0437`](https://github.com/juspay/hyperswitch/commit/0bb0437b7fca30b9a1d1567ab22afebeb7bce744))
- Add dispute and refund webhooks for Airwallex ([#1021](https://github.com/juspay/hyperswitch/pull/1021)) ([`8c34114`](https://github.com/juspay/hyperswitch/commit/8c3411413847ac2dda3fef485d1e402a11376780))
- Add bank redirect support for worldline ([#1060](https://github.com/juspay/hyperswitch/pull/1060)) ([`bc4ac52`](https://github.com/juspay/hyperswitch/commit/bc4ac529aa981150de6882d425bd274bc6272e30))
- [Adyen] Implement SEPA Direct debits for Adyen ([#1055](https://github.com/juspay/hyperswitch/pull/1055)) ([`7f796a6`](https://github.com/juspay/hyperswitch/commit/7f796a6709e18cc92668e50a044408bad8aeee3d))
- **refunds:** Add connector field in refund response ([#1059](https://github.com/juspay/hyperswitch/pull/1059)) ([`3fe24b3`](https://github.com/juspay/hyperswitch/commit/3fe24b3255039d6a5dff59203ffcfd024ff0d60b))
- **router:**
- Added retrieval flow for connector file uploads and added support for stripe connector ([#990](https://github.com/juspay/hyperswitch/pull/990)) ([`38aa9ea`](https://github.com/juspay/hyperswitch/commit/38aa9eab3f2453593e7b0c3fa63b37f7f2609514))
- Add disputes block in payments retrieve response ([#1038](https://github.com/juspay/hyperswitch/pull/1038)) ([`1304d91`](https://github.com/juspay/hyperswitch/commit/1304d912e53cf223f8f15760e29b84faafe4f6ea))
- Allow payment cancels for more statuses ([#1027](https://github.com/juspay/hyperswitch/pull/1027)) ([`a2a6bab`](https://github.com/juspay/hyperswitch/commit/a2a6bab56cc70463d25232ce40ca4f115bee24e0))
### Bug Fixes
- **applepay:** Rename applepay_session_response to lowercase ([#1090](https://github.com/juspay/hyperswitch/pull/1090)) ([`736a236`](https://github.com/juspay/hyperswitch/commit/736a236651523b7f72ff95ad9223f4dda875301a))
- **router:** Fix recursion bug in straight through algorithm ([#1080](https://github.com/juspay/hyperswitch/pull/1080)) ([`aa610c4`](https://github.com/juspay/hyperswitch/commit/aa610c49f5a24e3e858515d9dfe0872d43251ee5))
- **tests:** Remove ui tests from ci pipeline ([#1082](https://github.com/juspay/hyperswitch/pull/1082)) ([`2ab7f83`](https://github.com/juspay/hyperswitch/commit/2ab7f83103d0907095e5b15a35f298ae60e6d180))
- Connector-customer-id missing bug fix ([#1085](https://github.com/juspay/hyperswitch/pull/1085)) ([`c5db5c3`](https://github.com/juspay/hyperswitch/commit/c5db5c37ec8f15e90d56aca59d14331fd8a2ea30))
### Refactors
- **router:** Add `id` field in `MerchantConnectorAccountNotFound` ([#1098](https://github.com/juspay/hyperswitch/pull/1098)) ([`5214e22`](https://github.com/juspay/hyperswitch/commit/5214e22f20c01e7dfb402ae619fdf2e7339d0fe7))
### Documentation
- **changelog:** Adding changelog for v0.5.10 ([#1078](https://github.com/juspay/hyperswitch/pull/1078)) ([`cb77b01`](https://github.com/juspay/hyperswitch/commit/cb77b012a2751f10395c3ff698aed4714a6b4223))
### Miscellaneous Tasks
- **CODEOWNERS:** Update CODEOWNERS ([#1076](https://github.com/juspay/hyperswitch/pull/1076)) ([`1456580`](https://github.com/juspay/hyperswitch/commit/1456580366c618300db4e0746db08a7466e04ea8))
- - -
## 0.5.10 (2023-05-08)
### Features
- **common_utils:**
- Impl deref for email newtype ([#1073](https://github.com/juspay/hyperswitch/pull/1073)) ([`fa8683a`](https://github.com/juspay/hyperswitch/commit/fa8683a54b0056f4cc31d096765de373f8ae8a43))
- Impl from for email newtype ([#1074](https://github.com/juspay/hyperswitch/pull/1074)) ([`7c6f0fd`](https://github.com/juspay/hyperswitch/commit/7c6f0fdec5c8f03863d26fc6dabf1fb3225e3d59))
- **connector:**
- Add authorize, capture, void, psync, refund, rsync for Forte connector ([#955](https://github.com/juspay/hyperswitch/pull/955)) ([`f0464bc`](https://github.com/juspay/hyperswitch/commit/f0464bc4f584b52c4983df62a28befd60f67cca4))
- Add dummy connector template code ([#970](https://github.com/juspay/hyperswitch/pull/970)) ([`e5cc0d9`](https://github.com/juspay/hyperswitch/commit/e5cc0d9d45d41c391720ceb3f6c18151ac5a00f2))
- Add payment routes for dummy connector ([#980](https://github.com/juspay/hyperswitch/pull/980)) ([`4ece376`](https://github.com/juspay/hyperswitch/commit/4ece376b56549b53bd81c16fd9fdebbd0b9b1114))
- [Bluesnap] add cards 3DS support ([#1057](https://github.com/juspay/hyperswitch/pull/1057)) ([`9c331e4`](https://github.com/juspay/hyperswitch/commit/9c331e411ba524ef41352c1c7c69635492fcec23))
- Mandates for alternate payment methods via Stripe ([#1041](https://github.com/juspay/hyperswitch/pull/1041)) ([`64721b8`](https://github.com/juspay/hyperswitch/commit/64721b80ae0d276820404ff1208af91303cf1473))
- **errors:** Add reverse errorswitch trait for foreign errors ([#909](https://github.com/juspay/hyperswitch/pull/909)) ([`ab55d21`](https://github.com/juspay/hyperswitch/commit/ab55d21013a279568379b97821da98457a10754a))
### Bug Fixes
- **common_utils:** Manually implement diesel queryable for email newtype ([#1072](https://github.com/juspay/hyperswitch/pull/1072)) ([`3519649`](https://github.com/juspay/hyperswitch/commit/35196493c4509a6f9f1c202bf8b8a6aa7605346b))
- **connector:**
- [worldline] fix worldline unit test ([#1054](https://github.com/juspay/hyperswitch/pull/1054)) ([`3131bc8`](https://github.com/juspay/hyperswitch/commit/3131bc84af008f05508aab9049f6ee492ca89460))
- [ACI] Add amount currency conversion and update error codes ([#1065](https://github.com/juspay/hyperswitch/pull/1065)) ([`b760cba`](https://github.com/juspay/hyperswitch/commit/b760cba5460395487c63ea4363665b0d7e5a6118))
- **mandate:**
- Make payment_method_data optional for mandate scenario ([#1032](https://github.com/juspay/hyperswitch/pull/1032)) ([`9cb3fa2`](https://github.com/juspay/hyperswitch/commit/9cb3fa216ce490d62f99525b23430809b4943dcb))
- Fix payment_method_data becoming empty when mandate_id is not present ([#1077](https://github.com/juspay/hyperswitch/pull/1077)) ([`5c5c3ef`](https://github.com/juspay/hyperswitch/commit/5c5c3ef3831991ccfefd9b0561f5eac976ed2191))
- **redis:** Fix recreation on redis connection pool ([#1063](https://github.com/juspay/hyperswitch/pull/1063)) ([`982c27f`](https://github.com/juspay/hyperswitch/commit/982c27fce72074d2644c0a9f229b201b927c55da))
- Impl `Drop` for `RedisConnectionPool` ([#1051](https://github.com/juspay/hyperswitch/pull/1051)) ([`3d05e50`](https://github.com/juspay/hyperswitch/commit/3d05e50abcb92fe7e6c4472faafc03fb70920048))
- Throw PreconditionFailed error when routing_algorithm is not configured ([#1017](https://github.com/juspay/hyperswitch/pull/1017)) ([`8853702`](https://github.com/juspay/hyperswitch/commit/8853702f4b98c72655d6e36ed6acc13b7c261ad5))
### Refactors
- **compatibility:** Refactor stripe compatibility routes using `web::resource` ([#1022](https://github.com/juspay/hyperswitch/pull/1022)) ([`92ae2d9`](https://github.com/juspay/hyperswitch/commit/92ae2d92f18577d5cc88805340fa63c5e50dbc37))
- **router:**
|
CHANGELOG.md#chunk61
| null |
doc_chunk
| 8,120
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub struct RoleInfo {
role_id: String,
role_name: String,
groups: Vec<PermissionGroup>,
scope: RoleScope,
entity_type: EntityType,
is_invitable: bool,
is_deletable: bool,
is_updatable: bool,
is_internal: bool,
}
|
crates/router/src/services/authorization/roles.rs
|
router
|
struct_definition
| 66
|
rust
|
RoleInfo
| null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorSpecifications for Paypal {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYPAL_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYPAL_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PAYPAL_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/paypal.rs
|
hyperswitch_connectors
|
impl_block
| 104
|
rust
| null |
Paypal
|
ConnectorSpecifications for
|
impl ConnectorSpecifications for for Paypal
| null | null | null | null | null | null | null | null |
pub fn is_recovery_transaction_event(&self) -> bool {
matches!(
self,
Self::RecoveryPaymentFailure
| Self::RecoveryPaymentSuccess
| Self::RecoveryPaymentPending
)
}
|
crates/api_models/src/webhooks.rs
|
api_models
|
function_signature
| 48
|
rust
| null | null | null | null |
is_recovery_transaction_event
| null | null | null | null | null | null | null |
pub fn make_any_aggregator<M: Metadata>(
&mut self,
nodes: &[(NodeId, Relation, Strength)
|
crates/hyperswitch_constraint_graph/src/builder.rs
|
hyperswitch_constraint_graph
|
function_signature
| 26
|
rust
| null | null | null | null |
make_any_aggregator
| null | null | null | null | null | null | null |
.as_ref()
.and_then(|extra_p| {
extra_p.token.as_ref().map(|token| MandateReference {
connector_mandate_id: Some(token.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})
});
let status = match non_threeds_data.status.as_str() {
"00" => {
if item.data.request.is_auto_capture()? {
Ok(enums::AttemptStatus::Charged)
} else {
Ok(enums::AttemptStatus::Authorized)
}
}
"11" => Ok(enums::AttemptStatus::Failure),
"22" => Ok(enums::AttemptStatus::Pending),
other => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_owned()),
)),
}?;
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: non_threeds_data
.error_code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: non_threeds_data
.error_desc
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: non_threeds_data.error_desc.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(data.txn_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(data.txn_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
},
FiuuPaymentsResponse::RecurringResponse(ref recurring_response_vec) => {
let recurring_response_item = recurring_response_vec.first();
let router_data_response = match recurring_response_item {
Some(recurring_response) => {
let status =
common_enums::AttemptStatus::from(recurring_response.status.clone());
let connector_transaction_id = recurring_response
.tran_id
.as_ref()
.map_or(ResponseId::NoResponseId, |tran_id| {
ResponseId::ConnectorTransactionId(tran_id.clone())
});
let response = if status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: recurring_response
.reason
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: recurring_response
.reason
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: recurring_response.reason.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: recurring_response.tran_id.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_transaction_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Self {
status,
response,
..item.data
}
}
None => {
// It is not expected to get empty response from the connnector, if we get we are not updating the payment response since we don't have any info in the authorize response.
let response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
});
Self {
response,
..item.data
}
}
};
Ok(router_data_response)
}
}
}
}
impl From<FiuuRecurringStautus> for common_enums::AttemptStatus {
fn from(status: FiuuRecurringStautus) -> Self {
match status {
FiuuRecurringStautus::Accepted => Self::Charged,
FiuuRecurringStautus::Failed => Self::Failure,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuRefundRequest {
pub refund_type: RefundType,
#[serde(rename = "MerchantID")]
pub merchant_id: Secret<String>,
#[serde(rename = "RefID")]
pub ref_id: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub amount: StringMajorUnit,
pub signature: Secret<String>,
#[serde(rename = "notify_url")]
pub notify_url: Option<Url>,
}
#[derive(Debug, Serialize, Display)]
pub enum RefundType {
#[serde(rename = "P")]
#[strum(serialize = "P")]
Partial,
}
impl TryFrom<&FiuuRouterData<&RefundsRouterData<Execute>>> for FiuuRefundRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &FiuuRouterData<&RefundsRouterData<Execute>>) -> Result<Self, Self::Error> {
let auth: FiuuAuthType = FiuuAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_id = auth.merchant_id.peek().to_string();
let txn_amount = item.amount.clone();
let reference_no = item.router_data.connector_request_reference_id.clone();
let txn_id = item.router_data.request.connector_transaction_id.clone();
let secret_key = auth.secret_key.peek().to_string();
Ok(Self {
refund_type: RefundType::Partial,
merchant_id: auth.merchant_id,
ref_id: reference_no.clone(),
txn_id: txn_id.clone(),
amount: txn_amount.clone(),
signature: calculate_signature(format!(
"{}{merchant_id}{reference_no}{txn_id}{}{secret_key}",
RefundType::Partial,
txn_amount.get_amount_as_string()
))?,
notify_url: Some(
Url::parse(&item.router_data.request.get_webhook_url()?)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuRefundSuccessResponse {
#[serde(rename = "RefundID")]
refund_id: i64,
status: String,
#[serde(rename = "reason")]
reason: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FiuuRefundResponse {
Success(FiuuRefundSuccessResponse),
Error(FiuuErrorResponse),
}
impl TryFrom<RefundsResponseRouterData<Execute, FiuuRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, FiuuRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response {
FiuuRefundResponse::Error(error) => Ok(Self {
response: Err(ErrorResponse {
code: error.error_code.clone(),
message: error.error_desc.clone(),
reason: Some(error.error_desc),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
FiuuRefundResponse::Success(refund_data) => {
let refund_status = match refund_data.status.as_str() {
"00" => Ok(enums::RefundStatus::Success),
"11" => Ok(enums::RefundStatus::Failure),
"22" => Ok(enums::RefundStatus::Pending),
other => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_owned()),
)),
}?;
if refund_status == enums::RefundStatus::Failure {
Ok(Self {
response: Err(ErrorResponse {
code: refund_data.status.clone(),
message: refund_data
.reason
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: refund_data.reason.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(refund_data.refund_id.to_string()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
} else {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_data.refund_id.clone().to_string(),
refund_status,
}),
..item.data
})
}
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiuuErrorResponse {
pub error_code: String,
pub error_desc: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiuuPaymentSyncRequest {
amount: StringMajorUnit,
#[serde(rename = "txID")]
tx_id: String,
domain: String,
skey: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum FiuuPaymentResponse {
FiuuPaymentSyncResponse(FiuuPaymentSyncResponse),
FiuuWebhooksPaymentResponse(FiuuWebhooksPaymentResponse),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuPaymentSyncResponse {
stat_code: StatCode,
stat_name: StatName,
#[serde(rename = "TranID")]
tran_id: String,
error_code: Option<String>,
error_desc: Option<String>,
#[serde(rename = "miscellaneous")]
miscellaneous: Option<HashMap<String, Secret<String>>>,
#[serde(rename = "SchemeTransactionID")]
scheme_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Display, Clone, PartialEq)]
pub enum StatCode {
#[serde(rename = "00")]
Success,
#[serde(rename = "11")]
Failure,
#[serde(rename = "22")]
Pending,
}
#[derive(Debug, Serialize, Deserialize, Display, Clone, Copy, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum StatName {
Captured,
Settled,
Authorized,
Failed,
Cancelled,
Chargeback,
Release,
#[serde(rename = "reject/hold")]
RejectHold,
Blocked,
#[serde(rename = "ReqCancel")]
ReqCancel,
#[serde(rename = "ReqChargeback")]
ReqChargeback,
#[serde(rename = "Pending")]
Pending,
#[serde(rename = "Unknown")]
Unknown,
}
impl TryFrom<&PaymentsSyncRouterData> for FiuuPaymentSyncRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.connector_auth_type)?;
let txn_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let merchant_id = auth.merchant_id.peek().to_string();
let verify_key = auth.verify_key.peek().to_string();
let amount = StringMajorUnitForConnector
.convert(item.request.amount, item.request.currency)
.change_context(errors::ConnectorError::AmountConversionFailed)?;
Ok(Self {
amount: amount.clone(),
tx_id: txn_id.clone(),
domain: merchant_id.clone(),
skey: calculate_signature(format!(
"{txn_id}{merchant_id}{verify_key}{}",
amount.get_amount_as_string()
))?,
})
}
}
struct ErrorInputs {
encoded_data: Option<String>,
response_error_code: Option<String>,
response_error_desc: Option<String>,
}
struct ErrorDetails {
pub code: String,
pub message: String,
pub reason: Option<String>,
}
impl TryFrom<ErrorInputs> for ErrorDetails {
type Error = Report<errors::ConnectorError>;
fn try_from(value: ErrorInputs) -> Result<Self, Self::Error> {
let query_params = value
.encoded_data
.as_ref()
.map(|encoded_data| {
serde_urlencoded::from_str::<FiuuPaymentRedirectResponse>(encoded_data)
})
.transpose()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Failed to deserialize FiuuPaymentRedirectResponse")?;
let error_message = value
.response_error_desc
.as_ref()
.filter(|s| !s.is_empty())
.cloned()
.or_else(|| {
query_params
.as_ref()
.and_then(|qp| qp.error_desc.as_ref())
.filter(|s| !s.is_empty())
.cloned()
});
let error_code = value
.response_error_code
.as_ref()
.filter(|s| !s.is_empty())
.cloned()
.or_else(|| {
query_params
.as_ref()
.and_then(|qp| qp.error_code.as_ref())
.filter(|s| !s.is_empty())
.cloned()
})
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned());
Ok(Self {
code: error_code,
message: error_message
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()),
reason: error_message,
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSyncRouterData {
type Error = Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<FiuuPaymentResponse>,
) -> Result<Self, Self::Error> {
match item.response {
FiuuPaymentResponse::FiuuPaymentSyncResponse(response) => {
let stat_name = response.stat_name;
let stat_code = response.stat_code.clone();
let txn_id = response.tran_id;
let status = enums::AttemptStatus::try_from(FiuuSyncStatus {
stat_name,
stat_code,
})?;
let error_response = if status == enums::AttemptStatus::Failure {
let error_details = ErrorDetails::try_from(ErrorInputs {
encoded_data: item.data.request.encoded_data.clone(),
response_error_code: response.error_code.clone(),
response_error_desc: response.error_desc.clone(),
})?;
Some(ErrorResponse {
status_code: item.http_code,
code: error_details.code,
message: error_details.message,
reason: error_details.reason,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(txn_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn_id.clone().to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: response
.scheme_transaction_id
.as_ref()
.map(|id| id.clone().expose()),
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
FiuuPaymentResponse::FiuuWebhooksPaymentResponse(response) => {
let status = enums::AttemptStatus::try_from(FiuuWebhookStatus {
capture_method: item.data.request.capture_method,
status: response.status,
})?;
let txn_id = response.tran_id;
let mandate_reference = response.extra_parameters.as_ref().and_then(|extra_p| {
let mandate_token: Result<ExtraParameters, _> = serde_json::from_str(&extra_p.clone().expose());
match mandate_token {
Ok(token) => {
token.token.as_ref().map(|token| MandateReference {
connector_mandate_id: Some(token.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id:None
})
}
Err(err) => {
router_env::logger::warn!(
"Failed to convert 'extraP' from fiuu webhook response to fiuu::ExtraParameters. \
Input: '{:?}', Error: {}",
extra_p,
err
);
None
}
}
});
let error_response = if status == enums::AttemptStatus::Failure {
let error_details = ErrorDetails::try_from(ErrorInputs {
encoded_data: item.data.request.encoded_data.clone(),
response_error_code: response.error_code.clone(),
response_error_desc: response.error_desc.clone(),
})?;
Some(ErrorResponse {
status_code: item.http_code,
code: error_details.code,
message: error_details.message,
reason: error_details.reason,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(txn_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn_id.clone().to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
}
}
pub struct FiuuWebhookStatus {
pub capture_method: Option<CaptureMethod>,
pub status: FiuuPaymentWebhookStatus,
}
impl TryFrom<FiuuWebhookStatus> for enums::AttemptStatus {
type Error = Report<errors::ConnectorError>;
fn try_from(webhook_status: FiuuWebhookStatus) -> Result<Self, Self::Error> {
match webhook_status.status {
FiuuPaymentWebhookStatus::Success => match webhook_status.capture_method {
Some(CaptureMethod::Automatic) | Some(CaptureMethod::SequentialAutomatic) => {
Ok(Self::Charged)
}
Some(CaptureMethod::Manual) => Ok(Self::Authorized),
_ => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(webhook_status.status.to_string()),
))?,
},
FiuuPaymentWebhookStatus::Failure => Ok(Self::Failure),
FiuuPaymentWebhookStatus::Pending => Ok(Self::AuthenticationPending),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentCaptureRequest {
domain: String,
#[serde(rename = "tranID")]
tran_id: String,
amount: StringMajorUnit,
#[serde(rename = "RefID")]
ref_id: String,
skey: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentCaptureResponse {
#[serde(rename = "TranID")]
tran_id: String,
stat_code: String,
}
pub struct FiuuSyncStatus {
pub stat_name: StatName,
pub stat_code: StatCode,
}
impl TryFrom<FiuuSyncStatus> for enums::AttemptStatus {
type Error = errors::ConnectorError;
fn try_from(sync_status: FiuuSyncStatus) -> Result<Self, Self::Error> {
match (sync_status.stat_code, sync_status.stat_name) {
(StatCode::Success, StatName::Captured | StatName::Settled) => Ok(Self::Charged), // For Success as StatCode we can only expect Captured,Settled and Authorized as StatName.
(StatCode::Success, StatName::Authorized) => Ok(Self::Authorized),
(StatCode::Pending, StatName::Pending) => Ok(Self::AuthenticationPending), // For Pending as StatCode we can only expect Pending and Unknown as StatName.
(StatCode::Pending, StatName::Unknown) => Ok(Self::Pending),
(StatCode::Failure, StatName::Cancelled) | (StatCode::Failure, StatName::ReqCancel) => {
Ok(Self::Voided)
}
(StatCode::Failure, _) => Ok(Self::Failure),
(other, _) => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_string()),
)),
}
}
}
impl TryFrom<&FiuuRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &FiuuRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_id = auth.merchant_id.peek().to_string();
let amount = item.amount.clone();
let txn_id = item.router_data.request.connector_transaction_id.clone();
let verify_key = auth.verify_key.peek().to_string();
let signature = calculate_signature(format!(
"{txn_id}{}{merchant_id}{verify_key}",
amount.get_amount_as_string()
))?;
Ok(Self {
domain: merchant_id,
tran_id: txn_id,
amount,
ref_id: item.router_data.connector_request_reference_id.clone(),
skey: signature,
})
}
}
fn capture_status_codes() -> HashMap<&'static str, &'static str> {
[
("00", "Capture successful"),
("11", "Capture failed"),
("12", "Invalid or unmatched security hash string"),
("13", "Not a credit card transaction"),
("15", "Requested day is on settlement day"),
("16", "Forbidden transaction"),
("17", "Transaction not found"),
("18", "Missing required parameter"),
("19", "Domain not found"),
("20", "Temporary out of service"),
("21", "Authorization expired"),
("23", "Partial capture not allowed"),
("24", "Transaction already captured"),
("25", "Requested amount exceeds available capture amount"),
("99", "General error (contact payment gateway support)"),
]
.into_iter()
.collect()
}
impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<PaymentCaptureResponse>,
) -> Result<Self, Self::Error> {
let status_code = item.response.stat_code;
let status = match status_code.as_str() {
"00" => Ok(enums::AttemptStatus::Charged),
"22" => Ok(enums::AttemptStatus::Pending),
"11" | "12" | "13" | "15" | "16" | "17" | "18" | "19" | "20" | "21" | "23" | "24"
| "25" | "99" => Ok(enums::AttemptStatus::Failure),
other => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_owned()),
)),
}?;
let capture_message_status = capture_status_codes();
let error_response = if status == enums::AttemptStatus::Failure {
let optional_message = capture_message_status
.get(status_code.as_str())
.copied()
.map(String::from);
Some(ErrorResponse {
status_code: item.http_code,
code: status_code.to_owned(),
message: optional_message
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: optional_message,
attempt_status: None,
connector_transaction_id: Some(item.response.tran_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.tran_id.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiuuPaymentCancelRequest {
#[serde(rename = "txnID")]
txn_id: String,
domain: String,
skey: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuPaymentCancelResponse {
#[serde(rename = "TranID")]
tran_id: String,
stat_code: String,
#[serde(rename = "miscellaneous")]
miscellaneous: Option<HashMap<String, Secret<String>>>,
}
impl TryFrom<&PaymentsCancelRouterData> for FiuuPaymentCancelRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.connector_auth_type)?;
let txn_id = item.request.connector_transaction_id.clone();
let merchant_id = auth.merchant_id.peek().to_string();
let secret_key = auth.secret_key.peek().to_string();
Ok(Self {
txn_id: txn_id.clone(),
domain: merchant_id.clone(),
skey: calculate_signature(format!("{txn_id}{merchant_id}{secret_key}"))?,
})
}
}
fn void_status_codes() -> HashMap<&'static str, &'static str> {
[
("00", "Success (will proceed the request)"),
("11", "Failure"),
("12", "Invalid or unmatched security hash string"),
("13", "Not a refundable transaction"),
("14", "Transaction date more than 180 days"),
("15", "Requested day is on settlement day"),
("16", "Forbidden transaction"),
("17", "Transaction not found"),
("18", "Duplicate partial refund request"),
("19", "Merchant not found"),
("20", "Missing required parameter"),
(
"21",
"Transaction must be in authorized/captured/settled status",
),
]
.into_iter()
.collect()
}
impl TryFrom<PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>>
for PaymentsCancelRouterData
{
type Error = Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>,
) -> Result<Self, Self::Error> {
let status_code = item.response.stat_code;
let status = match status_code.as_str() {
"00" => Ok(enums::AttemptStatus::Voided),
"11" | "12" | "13" | "14" | "15" | "16" | "17" | "18" | "19" | "20" | "21" => {
Ok(enums::AttemptStatus::VoidFailed)
}
other => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_owned()),
)),
}?;
let void_message_status = void_status_codes();
let error_response = if status == enums::AttemptStatus::VoidFailed {
let optional_message = void_message_status
.get(status_code.as_str())
.copied()
.map(String::from);
Some(ErrorResponse {
status_code: item.http_code,
code: status_code.to_owned(),
message: optional_message
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: optional_message,
attempt_status: None,
connector_transaction_id: Some(item.response.tran_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.tran_id.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuRefundSyncRequest {
#[serde(rename = "TxnID")]
txn_id: String,
#[serde(rename = "MerchantID")]
merchant_id: Secret<String>,
signature: Secret<String>,
}
impl TryFrom<&RefundSyncRouterData> for FiuuRefundSyncRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.connector_auth_type)?;
let (txn_id, merchant_id, verify_key) = (
item.request.connector_transaction_id.clone(),
auth.merchant_id.peek().to_string(),
auth.verify_key.peek().to_string(),
);
let signature = calculate_signature(format!("{txn_id}{merchant_id}{verify_key}"))?;
Ok(Self {
txn_id,
merchant_id: auth.merchant_id,
signature,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FiuuRefundSyncResponse {
Success(Vec<RefundData>),
Error(FiuuErrorResponse),
Webhook(FiuuWebhooksRefundResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundData {
#[serde(rename = "RefundID")]
refund_id: String,
status: RefundStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Success,
Pending,
Rejected,
Processing,
}
impl TryFrom<RefundsResponseRouterData<RSync, FiuuRefundSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, FiuuRefundSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
FiuuRefundSyncResponse::Error(error) => Ok(Self {
response: Err(ErrorResponse {
code: error.error_code.clone(),
message: error.error_desc.clone(),
reason: Some(error.error_desc),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
FiuuRefundSyncResponse::Success(refund_data) => {
let refund = refund_data
.iter()
.find(|refund| {
Some(refund.refund_id.clone()) == item.data.request.connector_refund_id
})
.ok_or_else(|| errors::ConnectorError::MissingConnectorRefundID)?;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund.refund_id.clone(),
refund_status: enums::RefundStatus::from(refund.status.clone()),
}),
..item.data
})
}
FiuuRefundSyncResponse::Webhook(fiuu_webhooks_refund_response) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: fiuu_webhooks_refund_response.refund_id,
refund_status: enums::RefundStatus::from(
fiuu_webhooks_refund_response.status.clone(),
),
}),
..item.data
}),
}
}
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Pending => Self::Pending,
RefundStatus::Success => Self::Success,
RefundStatus::Rejected => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
pub fn get_qr_metadata(
response: &DuitNowQrCodeResponse,
) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> {
let image_data = QrImage::new_colored_from_data(
response.txn_data.request_data.qr_data.peek().clone(),
constants::DUIT_NOW_BRAND_COLOR,
)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let image_data_url = Url::parse(image_data.data.clone().as_str()).ok();
let display_to_timestamp = None;
if let Some(color_image_data_url) = image_data_url {
let qr_code_info = payments::QrCodeInformation::QrColorDataUrl {
color_image_data_url,
display_to_timestamp,
display_text: Some(constants::DUIT_NOW_BRAND_TEXT.to_string()),
border_color: Some(constants::DUIT_NOW_BRAND_COLOR.to_string()),
};
Some(qr_code_info.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
} else {
Ok(None)
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum FiuuWebhooksResponse {
FiuuWebhookPaymentResponse(FiuuWebhooksPaymentResponse),
FiuuWebhookRefundResponse(FiuuWebhooksRefundResponse),
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct FiuuWebhooksPaymentResponse {
pub skey: Secret<String>,
pub status: FiuuPaymentWebhookStatus,
#[serde(rename = "orderid")]
pub order_id: String,
#[serde(rename = "tranID")]
pub tran_id: String,
pub nbcb: String,
pub amount: StringMajorUnit,
pub currency: String,
pub domain: Secret<String>,
pub appcode: Option<Secret<String>>,
pub paydate: String,
pub channel: String,
pub error_desc: Option<String>,
pub error_code: Option<String>,
#[serde(rename = "extraP")]
pub extra_parameters: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct FiuuPaymentRedirectResponse {
pub skey: Secret<String>,
#[serde(rename = "tranID")]
pub tran_id: String,
pub status: FiuuPaymentWebhookStatus,
pub appcode: Option<String>,
pub error_code: Option<String>,
pub error_desc: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuWebhooksRefundResponse {
pub refund_type: FiuuWebhooksRefundType,
#[serde(rename = "MerchantID")]
pub merchant_id: Secret<String>,
#[serde(rename = "RefID")]
pub ref_id: String,
#[serde(rename = "RefundID")]
pub refund_id: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub amount: StringMajorUnit,
pub status: FiuuRefundsWebhookStatus,
pub signature: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone, strum::Display)]
pub enum FiuuRefundsWebhookStatus {
#[strum(serialize = "00")]
#[serde(rename = "00")]
RefundSuccess,
#[strum(serialize = "11")]
#[serde(rename = "11")]
RefundFailure,
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| 8,191
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/core/customers.rs
Public functions: 8
use common_utils::{
crypto::Encryptable,
errors::ReportSwitchExt,
ext_traits::AsyncExt,
id_type, pii, type_name,
types::{
keymanager::{Identifier, KeyManagerState, ToEncryptable},
Description,
},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payment_methods as payment_methods_domain;
use masking::{ExposeInterface, Secret, SwitchStrategy};
use payment_methods::controller::PaymentMethodsController;
use router_env::{instrument, tracing};
#[cfg(feature = "v2")]
use crate::core::payment_methods::cards::create_encrypted_data;
#[cfg(feature = "v1")]
use crate::utils::CustomerAddress;
use crate::{
core::{
errors::{self, StorageErrorExt},
payment_methods::{cards, network_tokenization},
},
db::StorageInterface,
pii::PeekInterface,
routes::{metrics, SessionState},
services,
types::{
api::customers,
domain::{self, types},
storage::{self, enums},
transformers::ForeignFrom,
},
};
pub const REDACTED: &str = "Redacted";
#[instrument(skip(state))]
pub async fn create_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
customer_data: customers::CustomerRequest,
connector_customer_details: Option<Vec<payment_methods_domain::ConnectorCustomerDetails>>,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db: &dyn StorageInterface = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_reference_id = customer_data.get_merchant_reference_id();
let merchant_id = merchant_context.get_merchant_account().get_id();
let merchant_reference_id_customer = MerchantReferenceIdForCustomer {
merchant_reference_id: merchant_reference_id.as_ref(),
merchant_id,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
};
// We first need to validate whether the customer with the given customer id already exists
// this may seem like a redundant db call, as the insert_customer will anyway return this error
//
// Consider a scenario where the address is inserted and then when inserting the customer,
// it errors out, now the address that was inserted is not deleted
merchant_reference_id_customer
.verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(db)
.await?;
let domain_customer = customer_data
.create_domain_model_from_request(
&connector_customer_details,
db,
&merchant_reference_id,
&merchant_context,
key_manager_state,
&state,
)
.await?;
let customer = db
.insert_customer(
domain_customer,
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?;
customer_data.generate_response(&customer)
}
#[async_trait::async_trait]
trait CustomerCreateBridge {
async fn create_domain_model_from_request<'a>(
&'a self,
connector_customer_details: &'a Option<
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
merchant_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>;
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse>;
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl CustomerCreateBridge for customers::CustomerRequest {
async fn create_domain_model_from_request<'a>(
&'a self,
connector_customer_details: &'a Option<
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
merchant_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
// Setting default billing address to Db
let address = self.get_address();
let merchant_id = merchant_context.get_merchant_account().get_id();
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let customer_billing_address_struct = AddressStructForDbEntry {
address: address.as_ref(),
customer_data: self,
merchant_id,
customer_id: merchant_reference_id.as_ref(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
state,
};
let address_from_db = customer_billing_address_struct
.encrypt_customer_address_and_set_to_db(db)
.await?;
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: self.name.clone(),
email: self.email.clone().map(|a| a.expose().switch_strategy()),
phone: self.phone.clone(),
tax_registration_id: self.tax_registration_id.clone(),
},
),
),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.switch()
.attach_printable("Failed while encrypting Customer")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
let connector_customer = connector_customer_details.as_ref().map(|details_vec| {
let mut map = serde_json::Map::new();
for details in details_vec {
let merchant_connector_id =
details.merchant_connector_id.get_string_repr().to_string();
let connector_customer_id = details.connector_customer_id.clone();
map.insert(merchant_connector_id, connector_customer_id.into());
}
pii::SecretSerdeValue::new(serde_json::Value::Object(map))
});
Ok(domain::Customer {
customer_id: merchant_reference_id
.to_owned()
.ok_or(errors::CustomersErrorResponse::InternalServerError)?,
merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
description: self.description.clone(),
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
connector_customer,
address_id: address_from_db.clone().map(|addr| addr.address_id),
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
default_payment_method_id: None,
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
})
}
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let address = self.get_address();
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from((customer.clone(), address)),
))
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl CustomerCreateBridge for customers::CustomerRequest {
async fn create_domain_model_from_request<'a>(
&'a self,
connector_customer_details: &'a Option<
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
_db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
merchant_context: &'a domain::MerchantContext,
key_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
let default_customer_billing_address = self.get_default_customer_billing_address();
let encrypted_customer_billing_address = default_customer_billing_address
.async_map(|billing_address| {
create_encrypted_data(
key_state,
merchant_context.get_merchant_key_store(),
billing_address,
)
})
.await
.transpose()
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer billing address")?;
let default_customer_shipping_address = self.get_default_customer_shipping_address();
let encrypted_customer_shipping_address = default_customer_shipping_address
.async_map(|shipping_address| {
create_encrypted_data(
key_state,
merchant_context.get_merchant_key_store(),
shipping_address,
)
})
.await
.transpose()
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer shipping address")?;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let encrypted_data = types::crypto_operation(
key_state,
type_name!(domain::Customer),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: Some(self.name.clone()),
email: Some(self.email.clone().expose().switch_strategy()),
phone: self.phone.clone(),
tax_registration_id: self.tax_registration_id.clone(),
},
),
),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.switch()
.attach_printable("Failed while encrypting Customer")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
let connector_customer = connector_customer_details.as_ref().map(|details_vec| {
let map: std::collections::HashMap<_, _> = details_vec
.iter()
.map(|details| {
(
details.merchant_connector_id.clone(),
details.connector_customer_id.to_string(),
)
})
.collect();
common_types::customers::ConnectorCustomerMap::new(map)
});
Ok(domain::Customer {
id: id_type::GlobalCustomerId::generate(&state.conf.cell_information.id),
merchant_reference_id: merchant_reference_id.to_owned(),
merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
description: self.description.clone(),
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
connector_customer,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
default_payment_method_id: None,
updated_by: None,
default_billing_address: encrypted_customer_billing_address.map(Into::into),
default_shipping_address: encrypted_customer_shipping_address.map(Into::into),
version: common_types::consts::API_VERSION,
status: common_enums::DeleteStatus::Active,
tax_registration_id: encryptable_customer.tax_registration_id,
})
}
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse> {
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from(customer.clone()),
))
}
}
#[cfg(feature = "v1")]
struct AddressStructForDbEntry<'a> {
address: Option<&'a api_models::payments::AddressDetails>,
customer_data: &'a customers::CustomerRequest,
merchant_id: &'a id_type::MerchantId,
customer_id: Option<&'a id_type::CustomerId>,
storage_scheme: common_enums::MerchantStorageScheme,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
}
#[cfg(feature = "v1")]
impl AddressStructForDbEntry<'_> {
async fn encrypt_customer_address_and_set_to_db(
&self,
db: &dyn StorageInterface,
) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> {
let encrypted_customer_address = self
.address
.async_map(|addr| async {
self.customer_data
.get_domain_address(
self.state,
addr.clone(),
self.merchant_id,
self.customer_id
.ok_or(errors::CustomersErrorResponse::InternalServerError)?, // should we raise error since in v1 appilcation is supposed to have this id or generate it at this point.
self.key_store.key.get_inner().peek(),
self.storage_scheme,
)
.await
.switch()
.attach_printable("Failed while encrypting address")
})
.await
.transpose()?;
encrypted_customer_address
.async_map(|encrypt_add| async {
db.insert_address_for_customers(self.key_manager_state, encrypt_add, self.key_store)
.await
.switch()
.attach_printable("Failed while inserting new address")
})
.await
.transpose()
}
}
struct MerchantReferenceIdForCustomer<'a> {
merchant_reference_id: Option<&'a id_type::CustomerId>,
merchant_id: &'a id_type::MerchantId,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
}
#[cfg(feature = "v1")]
impl<'a> MerchantReferenceIdForCustomer<'a> {
async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(
&self,
db: &dyn StorageInterface,
) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> {
self.merchant_reference_id
.async_map(|cust| async {
self.verify_if_merchant_reference_not_present_by_merchant_reference_id(cust, db)
.await
})
.await
.transpose()
}
async fn verify_if_merchant_reference_not_present_by_merchant_reference_id(
&self,
cus: &'a id_type::CustomerId,
db: &dyn StorageInterface,
) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> {
match db
.find_customer_by_customer_id_merchant_id(
self.key_manager_state,
cus,
self.merchant_id,
self.key_store,
self.merchant_account.storage_scheme,
)
.await
{
Err(err) => {
if !err.current_context().is_db_not_found() {
Err(err).switch()
} else {
Ok(())
}
}
Ok(_) => Err(report!(
errors::CustomersErrorResponse::CustomerAlreadyExists
)),
}
}
}
#[cfg(feature = "v2")]
impl<'a> MerchantReferenceIdForCustomer<'a> {
async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(
&self,
db: &dyn StorageInterface,
) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> {
self.merchant_reference_id
.async_map(|merchant_ref| async {
self.verify_if_merchant_reference_not_present_by_merchant_reference(
merchant_ref,
db,
)
.await
})
.await
.transpose()
}
async fn verify_if_merchant_reference_not_present_by_merchant_reference(
&self,
merchant_ref: &'a id_type::CustomerId,
db: &dyn StorageInterface,
) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> {
match db
.find_customer_by_merchant_reference_id_merchant_id(
self.key_manager_state,
merchant_ref,
self.merchant_id,
self.key_store,
self.merchant_account.storage_scheme,
)
.await
{
Err(err) => {
if !err.current_context().is_db_not_found() {
Err(err).switch()
} else {
Ok(())
}
}
Ok(_) => Err(report!(
errors::CustomersErrorResponse::CustomerAlreadyExists
)),
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn retrieve_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
_profile_id: Option<id_type::ProfileId>,
customer_id: id_type::CustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let response = db
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
key_manager_state,
&customer_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?
.ok_or(errors::CustomersErrorResponse::CustomerNotFound)?;
let address = match &response.address_id {
Some(address_id) => Some(api_models::payments::AddressDetails::from(
db.find_address_by_address_id(
key_manager_state,
address_id,
merchant_context.get_merchant_key_store(),
)
.await
.switch()?,
)),
None => None,
};
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from((response, address)),
))
}
#[cfg(feature = "v2")]
#[instrument(skip(state))]
pub async fn retrieve_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
id: id_type::GlobalCustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let response = db
.find_customer_by_global_id(
key_manager_state,
&id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from(response),
))
}
#[instrument(skip(state))]
pub async fn list_customers(
state: SessionState,
merchant_id: id_type::MerchantId,
_profile_id_list: Option<Vec<id_type::ProfileId>>,
key_store: domain::MerchantKeyStore,
request: customers::CustomerListRequest,
) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> {
let db = state.store.as_ref();
let customer_list_constraints = crate::db::customers::CustomerListConstraints {
limit: request
.limit
.unwrap_or(crate::consts::DEFAULT_LIST_API_LIMIT),
offset: request.offset,
};
let domain_customers = db
.list_customers_by_merchant_id(
&(&state).into(),
&merchant_id,
&key_store,
customer_list_constraints,
)
.await
.switch()?;
#[cfg(feature = "v1")]
let customers = domain_customers
.into_iter()
.map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None)))
.collect();
#[cfg(feature = "v2")]
let customers = domain_customers
.into_iter()
.map(customers::CustomerResponse::foreign_from)
.collect();
Ok(services::ApplicationResponse::Json(customers))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
id: id_type::GlobalCustomerId,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
id.redact_customer_details_and_generate_response(
db,
&merchant_context,
key_manager_state,
&state,
)
.await
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl CustomerDeleteBridge for id_type::GlobalCustomerId {
async fn redact_customer_details_and_generate_response<'a>(
&'a self,
db: &'a dyn StorageInterface,
merchant_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let customer_orig = db
.find_customer_by_global_id(
key_manager_state,
self,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
let merchant_reference_id = customer_orig.merchant_reference_id.clone();
let customer_mandates = db.find_mandate_by_global_customer_id(self).await.switch()?;
for mandate in customer_mandates.into_iter() {
if mandate.mandate_status == enums::MandateStatus::Active {
Err(errors::CustomersErrorResponse::MandateActive)?
}
}
match db
.find_payment_method_list_by_global_customer_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
self,
None,
)
.await
{
// check this in review
Ok(customer_payment_methods) => {
for pm in customer_payment_methods.into_iter() {
if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
cards::delete_card_by_locker_id(
state,
self,
merchant_context.get_merchant_account().get_id(),
)
.await
.switch()?;
}
// No solution as of now, need to discuss this further with payment_method_v2
// db.delete_payment_method(
// key_manager_state,
// key_store,
// pm,
// )
// .await
// .switch()?;
}
}
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(())
} else {
Err(error)
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable(
"failed find_payment_method_by_customer_id_merchant_id_list",
)
}?
}
};
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let identifier = Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
);
let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation(
key_manager_state,
type_name!(storage::Address),
types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_operation())
.switch()?;
let redacted_encrypted_email = Encryptable::new(
redacted_encrypted_value
.clone()
.into_inner()
.switch_strategy(),
redacted_encrypted_value.clone().into_encrypted(),
);
let updated_customer =
storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate {
name: Some(redacted_encrypted_value.clone()),
email: Box::new(Some(redacted_encrypted_email)),
phone: Box::new(Some(redacted_encrypted_value.clone())),
description: Some(Description::from_str_unchecked(REDACTED)),
phone_country_code: Some(REDACTED.to_string()),
metadata: None,
connector_customer: Box::new(None),
default_billing_address: None,
default_shipping_address: None,
default_payment_method_id: None,
status: Some(common_enums::DeleteStatus::Redacted),
tax_registration_id: Some(redacted_encrypted_value),
}));
db.update_customer_by_global_id(
key_manager_state,
self,
customer_orig,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
let response = customers::CustomerDeleteResponse {
id: self.clone(),
merchant_reference_id,
customer_deleted: true,
address_deleted: true,
payment_methods_deleted: true,
};
metrics::CUSTOMER_REDACTED.add(1, &[]);
Ok(services::ApplicationResponse::Json(response))
}
}
#[async_trait::async_trait]
trait CustomerDeleteBridge {
async fn redact_customer_details_and_generate_response<'a>(
&'a self,
db: &'a dyn StorageInterface,
merchant_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse>;
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn delete_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
customer_id: id_type::CustomerId,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
customer_id
.redact_customer_details_and_generate_response(
db,
&merchant_context,
key_manager_state,
&state,
)
.await
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl CustomerDeleteBridge for id_type::CustomerId {
async fn redact_customer_details_and_generate_response<'a>(
&'a self,
db: &'a dyn StorageInterface,
merchant_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let customer_orig = db
.find_customer_by_customer_id_merchant_id(
key_manager_state,
self,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
let customer_mandates = db
.find_mandate_by_merchant_id_customer_id(
merchant_context.get_merchant_account().get_id(),
self,
)
.await
.switch()?;
for mandate in customer_mandates.into_iter() {
if mandate.mandate_status == enums::MandateStatus::Active {
Err(errors::CustomersErrorResponse::MandateActive)?
}
}
match db
.find_payment_method_by_customer_id_merchant_id_list(
key_manager_state,
merchant_context.get_merchant_key_store(),
self,
merchant_context.get_merchant_account().get_id(),
None,
)
.await
{
// check this in review
Ok(customer_payment_methods) => {
for pm in customer_payment_methods.into_iter() {
if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
cards::PmCards {
state,
merchant_context,
}
.delete_card_from_locker(
self,
merchant_context.get_merchant_account().get_id(),
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.switch()?;
if let Some(network_token_ref_id) = pm.network_token_requestor_reference_id
{
network_tokenization::delete_network_token_from_locker_and_token_service(
state,
self,
merchant_context.get_merchant_account().get_id(),
pm.payment_method_id.clone(),
pm.network_token_locker_id,
network_token_ref_id,
merchant_context,
)
.await
.switch()?;
}
}
db.delete_payment_method_by_merchant_id_payment_method_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().get_id(),
&pm.payment_method_id,
)
.await
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable(
"failed to delete payment method while redacting customer details",
)?;
}
}
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(())
} else {
Err(error)
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable(
"failed find_payment_method_by_customer_id_merchant_id_list",
)
}?
}
};
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let identifier = Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
);
let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation(
key_manager_state,
type_name!(storage::Address),
types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_operation())
.switch()?;
let redacted_encrypted_email = Encryptable::new(
redacted_encrypted_value
.clone()
.into_inner()
.switch_strategy(),
redacted_encrypted_value.clone().into_encrypted(),
);
let update_address = storage::AddressUpdate::Update {
city: Some(REDACTED.to_string()),
country: None,
line1: Some(redacted_encrypted_value.clone()),
line2: Some(redacted_encrypted_value.clone()),
line3: Some(redacted_encrypted_value.clone()),
state: Some(redacted_encrypted_value.clone()),
zip: Some(redacted_encrypted_value.clone()),
first_name: Some(redacted_encrypted_value.clone()),
last_name: Some(redacted_encrypted_value.clone()),
phone_number: Some(redacted_encrypted_value.clone()),
country_code: Some(REDACTED.to_string()),
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
email: Some(redacted_encrypted_email),
origin_zip: Some(redacted_encrypted_value.clone()),
};
match db
.update_address_by_merchant_id_customer_id(
key_manager_state,
self,
merchant_context.get_merchant_account().get_id(),
update_address,
merchant_context.get_merchant_key_store(),
)
.await
{
Ok(_) => Ok(()),
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(())
} else {
Err(error)
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("failed update_address_by_merchant_id_customer_id")
}
}
}?;
let updated_customer = storage::CustomerUpdate::Update {
name: Some(redacted_encrypted_value.clone()),
email: Some(
types::crypto_operation(
key_manager_state,
type_name!(storage::Customer),
types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier,
key,
)
.await
.and_then(|val| val.try_into_operation())
.switch()?,
),
phone: Box::new(Some(redacted_encrypted_value.clone())),
description: Some(Description::from_str_unchecked(REDACTED)),
phone_country_code: Some(REDACTED.to_string()),
metadata: Box::new(None),
connector_customer: Box::new(None),
address_id: None,
tax_registration_id: Some(redacted_encrypted_value.clone()),
};
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
self.clone(),
merchant_context.get_merchant_account().get_id().to_owned(),
customer_orig,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
let response = customers::CustomerDeleteResponse {
customer_id: self.clone(),
customer_deleted: true,
address_deleted: true,
payment_methods_deleted: true,
};
metrics::CUSTOMER_REDACTED.add(1, &[]);
Ok(services::ApplicationResponse::Json(response))
}
}
#[instrument(skip(state))]
pub async fn update_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
update_customer: customers::CustomerUpdateRequestInternal,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
//Add this in update call if customer can be updated anywhere else
#[cfg(feature = "v1")]
let verify_id_for_update_customer = VerifyIdForUpdateCustomer {
merchant_reference_id: &update_customer.customer_id,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
};
#[cfg(feature = "v2")]
let verify_id_for_update_customer = VerifyIdForUpdateCustomer {
id: &update_customer.id,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
};
let customer = verify_id_for_update_customer
.verify_id_and_get_customer_object(db)
.await?;
let updated_customer = update_customer
.request
.create_domain_model_from_request(
&None,
db,
&merchant_context,
key_manager_state,
&state,
&customer,
)
.await?;
update_customer.request.generate_response(&updated_customer)
}
#[async_trait::async_trait]
trait CustomerUpdateBridge {
async fn create_domain_model_from_request<'a>(
&'a self,
connector_customer_details: &'a Option<
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
db: &'a dyn StorageInterface,
merchant_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>;
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse>;
}
#[cfg(feature = "v1")]
struct AddressStructForDbUpdate<'a> {
update_customer: &'a customers::CustomerUpdateRequest,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
}
#[cfg(feature = "v1")]
impl AddressStructForDbUpdate<'_> {
async fn update_address_if_sent(
&self,
db: &dyn StorageInterface,
) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> {
let address = if let Some(addr) = &self.update_customer.address {
match self.domain_customer.address_id.clone() {
Some(address_id) => {
let customer_address: api_models::payments::AddressDetails = addr.clone();
let update_address = self
.update_customer
.get_address_update(
self.state,
customer_address,
self.key_store.key.get_inner().peek(),
self.merchant_account.storage_scheme,
self.merchant_account.get_id().clone(),
)
.await
.switch()
.attach_printable("Failed while encrypting Address while Update")?;
Some(
db.update_address(
self.key_manager_state,
address_id,
update_address,
self.key_store,
)
.await
.switch()
.attach_printable(format!(
"Failed while updating address: merchant_id: {:?}, customer_id: {:?}",
self.merchant_account.get_id(),
self.domain_customer.customer_id
))?,
)
}
None => {
let customer_address: api_models::payments::AddressDetails = addr.clone();
let address = self
.update_customer
.get_domain_address(
self.state,
customer_address,
self.merchant_account.get_id(),
&self.domain_customer.customer_id,
self.key_store.key.get_inner().peek(),
self.merchant_account.storage_scheme,
)
.await
.switch()
.attach_printable("Failed while encrypting address")?;
Some(
db.insert_address_for_customers(
self.key_manager_state,
address,
self.key_store,
)
.await
.switch()
.attach_printable("Failed while inserting new address")?,
)
}
}
} else {
|
crates/router/src/core/customers.rs#chunk0
|
router
|
chunk
| 8,191
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/analytics/src/payment_intents/accumulator.rs
Public functions: 1
Public structs: 8
use api_models::analytics::payment_intents::PaymentIntentMetricsBucketValue;
use bigdecimal::ToPrimitive;
use diesel_models::enums as storage_enums;
use super::metrics::PaymentIntentMetricRow;
#[derive(Debug, Default)]
pub struct PaymentIntentMetricsAccumulator {
pub successful_smart_retries: CountAccumulator,
pub total_smart_retries: CountAccumulator,
pub smart_retried_amount: SmartRetriedAmountAccumulator,
pub payment_intent_count: CountAccumulator,
pub payments_success_rate: PaymentsSuccessRateAccumulator,
pub payment_processed_amount: ProcessedAmountAccumulator,
pub payments_distribution: PaymentsDistributionAccumulator,
}
#[derive(Debug, Default)]
pub struct ErrorDistributionRow {
pub count: i64,
pub total: i64,
pub error_message: String,
}
#[derive(Debug, Default)]
pub struct ErrorDistributionAccumulator {
pub error_vec: Vec<ErrorDistributionRow>,
}
#[derive(Debug, Default)]
#[repr(transparent)]
pub struct CountAccumulator {
pub count: Option<i64>,
}
pub trait PaymentIntentMetricAccumulator {
type MetricOutput;
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow);
fn collect(self) -> Self::MetricOutput;
}
#[derive(Debug, Default)]
pub struct SmartRetriedAmountAccumulator {
pub amount: Option<i64>,
pub amount_without_retries: Option<i64>,
}
#[derive(Debug, Default)]
pub struct PaymentsSuccessRateAccumulator {
pub success: u32,
pub success_without_retries: u32,
pub total: u32,
}
#[derive(Debug, Default)]
pub struct ProcessedAmountAccumulator {
pub count_with_retries: Option<i64>,
pub total_with_retries: Option<i64>,
pub count_without_retries: Option<i64>,
pub total_without_retries: Option<i64>,
}
#[derive(Debug, Default)]
pub struct PaymentsDistributionAccumulator {
pub success_without_retries: u32,
pub failed_without_retries: u32,
pub total: u32,
}
impl PaymentIntentMetricAccumulator for CountAccumulator {
type MetricOutput = Option<u64>;
#[inline]
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
self.count = match (self.count, metrics.count) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
self.count.and_then(|i| u64::try_from(i).ok())
}
}
impl PaymentIntentMetricAccumulator for SmartRetriedAmountAccumulator {
type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>);
#[inline]
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
self.amount = match (
self.amount,
metrics.total.as_ref().and_then(ToPrimitive::to_i64),
) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
};
if metrics.first_attempt.unwrap_or(0) == 1 {
self.amount_without_retries = match (
self.amount_without_retries,
metrics.total.as_ref().and_then(ToPrimitive::to_i64),
) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
}
} else {
self.amount_without_retries = Some(0);
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
let with_retries = self.amount.and_then(|i| u64::try_from(i).ok()).or(Some(0));
let without_retries = self
.amount_without_retries
.and_then(|i| u64::try_from(i).ok())
.or(Some(0));
(with_retries, without_retries, Some(0), Some(0))
}
}
impl PaymentIntentMetricAccumulator for PaymentsSuccessRateAccumulator {
type MetricOutput = (
Option<u32>,
Option<u32>,
Option<u32>,
Option<f64>,
Option<f64>,
);
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
if let Some(ref status) = metrics.status {
if status.as_ref() == &storage_enums::IntentStatus::Succeeded {
if let Some(success) = metrics
.count
.and_then(|success| u32::try_from(success).ok())
{
self.success += success;
if metrics.first_attempt.unwrap_or(0) == 1 {
self.success_without_retries += success;
}
}
}
if status.as_ref() != &storage_enums::IntentStatus::RequiresCustomerAction
&& status.as_ref() != &storage_enums::IntentStatus::RequiresPaymentMethod
&& status.as_ref() != &storage_enums::IntentStatus::RequiresMerchantAction
&& status.as_ref() != &storage_enums::IntentStatus::RequiresConfirmation
{
if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) {
self.total += total;
}
}
}
}
fn collect(self) -> Self::MetricOutput {
if self.total == 0 {
(None, None, None, None, None)
} else {
let success = Some(self.success);
let success_without_retries = Some(self.success_without_retries);
let total = Some(self.total);
let success_rate = match (success, total) {
(Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
let success_without_retries_rate = match (success_without_retries, total) {
(Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
(
success,
success_without_retries,
total,
success_rate,
success_without_retries_rate,
)
}
}
}
impl PaymentIntentMetricAccumulator for ProcessedAmountAccumulator {
type MetricOutput = (
Option<u64>,
Option<u64>,
Option<u64>,
Option<u64>,
Option<u64>,
Option<u64>,
);
#[inline]
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
self.total_with_retries = match (
self.total_with_retries,
metrics.total.as_ref().and_then(ToPrimitive::to_i64),
) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
};
self.count_with_retries = match (self.count_with_retries, metrics.count) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
};
if metrics.first_attempt.unwrap_or(0) == 1 {
self.total_without_retries = match (
self.total_without_retries,
metrics.total.as_ref().and_then(ToPrimitive::to_i64),
) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
};
self.count_without_retries = match (self.count_without_retries, metrics.count) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
};
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
let total_with_retries = u64::try_from(self.total_with_retries.unwrap_or(0)).ok();
let count_with_retries = self.count_with_retries.and_then(|i| u64::try_from(i).ok());
let total_without_retries = u64::try_from(self.total_without_retries.unwrap_or(0)).ok();
let count_without_retries = self
.count_without_retries
.and_then(|i| u64::try_from(i).ok());
(
total_with_retries,
count_with_retries,
total_without_retries,
count_without_retries,
Some(0),
Some(0),
)
}
}
impl PaymentIntentMetricAccumulator for PaymentsDistributionAccumulator {
type MetricOutput = (Option<f64>, Option<f64>);
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
let first_attempt = metrics.first_attempt.unwrap_or(0);
if let Some(ref status) = metrics.status {
if status.as_ref() == &storage_enums::IntentStatus::Succeeded {
if let Some(success) = metrics
.count
.and_then(|success| u32::try_from(success).ok())
{
if first_attempt == 1 {
self.success_without_retries += success;
}
}
}
if let Some(failed) = metrics.count.and_then(|failed| u32::try_from(failed).ok()) {
if first_attempt == 0
|| (first_attempt == 1
&& status.as_ref() == &storage_enums::IntentStatus::Failed)
{
self.failed_without_retries += failed;
}
}
if status.as_ref() != &storage_enums::IntentStatus::RequiresCustomerAction
&& status.as_ref() != &storage_enums::IntentStatus::RequiresPaymentMethod
&& status.as_ref() != &storage_enums::IntentStatus::RequiresMerchantAction
&& status.as_ref() != &storage_enums::IntentStatus::RequiresConfirmation
{
if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) {
self.total += total;
}
}
}
}
fn collect(self) -> Self::MetricOutput {
if self.total == 0 {
(None, None)
} else {
let success_without_retries = Some(self.success_without_retries);
let failed_without_retries = Some(self.failed_without_retries);
let total = Some(self.total);
let success_rate_without_retries = match (success_without_retries, total) {
(Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
let failed_rate_without_retries = match (failed_without_retries, total) {
(Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
(success_rate_without_retries, failed_rate_without_retries)
}
}
}
impl PaymentIntentMetricsAccumulator {
pub fn collect(self) -> PaymentIntentMetricsBucketValue {
let (
successful_payments,
successful_payments_without_smart_retries,
total_payments,
payments_success_rate,
payments_success_rate_without_smart_retries,
) = self.payments_success_rate.collect();
let (
smart_retried_amount,
smart_retried_amount_without_smart_retries,
smart_retried_amount_in_usd,
smart_retried_amount_without_smart_retries_in_usd,
) = self.smart_retried_amount.collect();
let (
payment_processed_amount,
payment_processed_count,
payment_processed_amount_without_smart_retries,
payment_processed_count_without_smart_retries,
payment_processed_amount_in_usd,
payment_processed_amount_without_smart_retries_in_usd,
) = self.payment_processed_amount.collect();
let (
payments_success_rate_distribution_without_smart_retries,
payments_failure_rate_distribution_without_smart_retries,
) = self.payments_distribution.collect();
PaymentIntentMetricsBucketValue {
successful_smart_retries: self.successful_smart_retries.collect(),
total_smart_retries: self.total_smart_retries.collect(),
smart_retried_amount,
smart_retried_amount_in_usd,
smart_retried_amount_without_smart_retries,
smart_retried_amount_without_smart_retries_in_usd,
payment_intent_count: self.payment_intent_count.collect(),
successful_payments,
successful_payments_without_smart_retries,
total_payments,
payments_success_rate,
payments_success_rate_without_smart_retries,
payment_processed_amount,
payment_processed_count,
payment_processed_amount_without_smart_retries,
payment_processed_count_without_smart_retries,
payments_success_rate_distribution_without_smart_retries,
payments_failure_rate_distribution_without_smart_retries,
payment_processed_amount_in_usd,
payment_processed_amount_without_smart_retries_in_usd,
}
}
}
|
crates/analytics/src/payment_intents/accumulator.rs
|
analytics
|
full_file
| 3,000
| null | null | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.OpenBankingData
{
"oneOf": [
{
"type": "object",
"required": [
"open_banking_pis"
],
"properties": {
"open_banking_pis": {
"type": "object"
}
}
}
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 74
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"OpenBankingData"
] | null | null | null | null |
pub struct MandateCard {
type_selection_indicator: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 15
|
rust
|
MandateCard
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers.rs
#[cfg(feature = "frm")]
pub mod api;
pub mod auth;
#[cfg(feature = "frm")]
pub use self::api::*;
pub use self::auth::*;
|
crates/hyperswitch_connectors/src/connectors/signifyd/transformers.rs
|
hyperswitch_connectors
|
full_file
| 54
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn build(self) -> RecordMigrationStatus {
RecordMigrationStatus {
card_migrated: self.card_migrated,
network_token_migrated: self.network_token_migrated,
connector_mandate_details_migrated: self.connector_mandate_details_migrated,
network_transaction_migrated: self.network_transaction_migrated,
}
}
|
crates/payment_methods/src/core/migration.rs
|
payment_methods
|
function_signature
| 71
|
rust
| null | null | null | null |
build
| null | null | null | null | null | null | null |
File: crates/router/tests/connectors/hyperswitch_vault.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct HyperswitchVaultTest;
impl ConnectorActions for HyperswitchVaultTest {}
impl utils::Connector for HyperswitchVaultTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::HyperswitchVault;
utils::construct_connector_data_old(
Box::new(&HyperswitchVault),
types::Connector::HyperswitchVault,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.hyperswitch_vault
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"hyperswitch_vault".to_string()
}
}
static CONNECTOR: HyperswitchVaultTest = HyperswitchVaultTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/hyperswitch_vault.rs
|
router
|
full_file
| 2,952
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn fetch_producer_tasks(
db: &dyn SchedulerInterface,
conf: &SchedulerSettings,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> {
let upper = conf.producer.upper_fetch_limit;
let lower = conf.producer.lower_fetch_limit;
let now = common_utils::date_time::now();
// Add these to validations
let time_upper_limit = now.checked_add(Duration::seconds(upper)).ok_or_else(|| {
report!(errors::ProcessTrackerError::ConfigurationError)
.attach_printable("Error obtaining upper limit to fetch producer tasks")
})?;
let time_lower_limit = now.checked_sub(Duration::seconds(lower)).ok_or_else(|| {
report!(errors::ProcessTrackerError::ConfigurationError)
.attach_printable("Error obtaining lower limit to fetch producer tasks")
})?;
let mut new_tasks = db
.find_processes_by_time_status(
time_lower_limit,
time_upper_limit,
ProcessTrackerStatus::New,
None,
)
.await
.change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?;
let mut pending_tasks = db
.find_processes_by_time_status(
time_lower_limit,
time_upper_limit,
ProcessTrackerStatus::Pending,
None,
)
.await
.change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?;
if new_tasks.is_empty() {
warn!("No new tasks found for producer to schedule");
}
if pending_tasks.is_empty() {
warn!("No pending tasks found for producer to schedule");
}
new_tasks.append(&mut pending_tasks);
// Safety: Assuming we won't deal with more than `u64::MAX` tasks at once
#[allow(clippy::as_conversions)]
metrics::TASKS_PICKED_COUNT.add(new_tasks.len() as u64, &[]);
Ok(new_tasks)
}
|
crates/scheduler/src/producer.rs
|
scheduler
|
function_signature
| 405
|
rust
| null | null | null | null |
fetch_producer_tasks
| null | null | null | null | null | null | null |
pub async fn start_process_tracker<
T: SchedulerAppState + 'static,
U: SchedulerSessionState + 'static,
F,
>(
state: &T,
scheduler_flow: SchedulerFlow,
scheduler_settings: Arc<SchedulerSettings>,
channel: (mpsc::Sender<()
|
crates/scheduler/src/scheduler.rs
|
scheduler
|
function_signature
| 62
|
rust
| null | null | null | null |
start_process_tracker
| null | null | null | null | null | null | null |
pub async fn get_data_from_hyperswitch_ai_workflow(
state: SessionState,
user_from_token: auth::UserFromToken,
req: chat_api::ChatRequest,
session_id: Option<&str>,
) -> CustomResult<ApplicationResponse<chat_api::ChatResponse>, ChatErrors> {
let url = format!("{}/webhook", state.conf.chat.hyperswitch_ai_host);
let request_id = state.get_request_id();
let request_body = chat_domain::HyperswitchAiDataRequest {
query: chat_domain::GetDataMessage {
message: req.message,
},
org_id: user_from_token.org_id,
merchant_id: user_from_token.merchant_id,
profile_id: user_from_token.profile_id,
};
logger::info!("Request for AI service: {:?}", request_body);
let mut request_builder = RequestBuilder::new()
.method(Method::Post)
.url(&url)
.attach_default_headers()
.set_body(RequestContent::Json(Box::new(request_body.clone())));
if let Some(request_id) = request_id {
request_builder = request_builder.header(consts::X_REQUEST_ID, &request_id);
}
if let Some(session_id) = session_id {
request_builder = request_builder.header(consts::X_CHAT_SESSION_ID, session_id);
}
let request = request_builder.build();
let response = http_client::send_request(
&state.conf.proxy,
request,
Some(consts::REQUEST_TIME_OUT_FOR_AI_SERVICE),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when sending request to AI service")?
.json::<_>()
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when deserializing response from AI service")?;
Ok(ApplicationResponse::Json(response))
}
|
crates/router/src/core/chat.rs
|
router
|
function_signature
| 396
|
rust
| null | null | null | null |
get_data_from_hyperswitch_ai_workflow
| null | null | null | null | null | null | null |
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
pub time_range: Option<common_utils::types::TimeRange>,
/// The list of connectors to filter payments list
pub connector: Option<Vec<api_enums::Connector>>,
/// The list of currencies to filter payments list
pub currency: Option<Vec<enums::Currency>>,
/// The list of payment status to filter payments list
pub status: Option<Vec<enums::IntentStatus>>,
/// The list of payment methods to filter payments list
pub payment_method: Option<Vec<enums::PaymentMethod>>,
/// The list of payment method types to filter payments list
pub payment_method_type: Option<Vec<enums::PaymentMethodType>>,
/// The list of authentication types to filter payments list
pub authentication_type: Option<Vec<enums::AuthenticationType>>,
/// The list of merchant connector ids to filter payments list for selected label
pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
/// The order in which payments list should be sorted
#[serde(default)]
pub order: Order,
/// The List of all the card networks to filter payments list
pub card_network: Option<Vec<enums::CardNetwork>>,
/// The identifier for merchant order reference id
pub merchant_order_reference_id: Option<String>,
/// Indicates the method by which a card is discovered during a payment
pub card_discovery: Option<Vec<enums::CardDiscovery>>,
}
#[cfg(feature = "v1")]
impl PaymentListFilterConstraints {
pub fn has_no_attempt_filters(&self) -> bool {
self.connector.is_none()
&& self.payment_method.is_none()
&& self.payment_method_type.is_none()
&& self.authentication_type.is_none()
&& self.merchant_connector_id.is_none()
&& self.card_network.is_none()
&& self.card_discovery.is_none()
}
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentListFilters {
/// The list of available connector filters
pub connector: Vec<String>,
/// The list of available currency filters
pub currency: Vec<enums::Currency>,
/// The list of available payment status filters
pub status: Vec<enums::IntentStatus>,
/// The list of available payment method filters
pub payment_method: Vec<enums::PaymentMethod>,
/// The list of available payment method types
pub payment_method_type: Vec<enums::PaymentMethodType>,
/// The list of available authentication types
pub authentication_type: Vec<enums::AuthenticationType>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentListFiltersV2 {
/// The list of available connector filters
pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,
/// The list of available currency filters
pub currency: Vec<enums::Currency>,
/// The list of available payment status filters
pub status: Vec<enums::IntentStatus>,
/// The list payment method and their corresponding types
pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>,
/// The list of available authentication types
pub authentication_type: Vec<enums::AuthenticationType>,
/// The list of available card networks
pub card_network: Vec<enums::CardNetwork>,
/// The list of available Card discovery methods
pub card_discovery: Vec<enums::CardDiscovery>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentsAggregateResponse {
/// The list of intent status with their count
pub status_with_count: HashMap<enums::IntentStatus, i64>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct AmountFilter {
/// The start amount to filter list of transactions which are greater than or equal to the start amount
pub start_amount: Option<i64>,
/// The end amount to filter list of transactions which are less than or equal to the end amount
pub end_amount: Option<i64>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct Order {
/// The field to sort, such as Amount or Created etc.
pub on: SortOn,
/// The order in which to sort the items, either Ascending or Descending
pub by: SortBy,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum SortOn {
/// Sort by the amount field
Amount,
/// Sort by the created_at field
#[default]
Created,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum SortBy {
/// Sort in ascending order
Asc,
/// Sort in descending order
#[default]
Desc,
}
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)]
pub struct VerifyResponse {
pub verify_id: Option<id_type::PaymentId>,
pub merchant_id: Option<id_type::MerchantId>,
// pub status: enums::VerifyStatus,
pub client_secret: Option<Secret<String>>,
pub customer_id: Option<id_type::CustomerId>,
pub email: crypto::OptionalEncryptableEmail,
pub name: crypto::OptionalEncryptableName,
pub phone: crypto::OptionalEncryptablePhone,
pub mandate_id: Option<String>,
#[auth_based]
pub payment_method: Option<api_enums::PaymentMethod>,
#[auth_based]
pub payment_method_data: Option<PaymentMethodDataResponse>,
pub payment_token: Option<String>,
pub error_code: Option<String>,
pub error_message: Option<String>,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaymentsRedirectionResponse {
pub redirect_url: String,
}
pub struct MandateValidationFields {
pub recurring_details: Option<RecurringDetails>,
pub confirm: Option<bool>,
pub customer_id: Option<id_type::CustomerId>,
pub mandate_data: Option<MandateData>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub off_session: Option<bool>,
}
#[cfg(feature = "v1")]
impl From<&PaymentsRequest> for MandateValidationFields {
fn from(req: &PaymentsRequest) -> Self {
let recurring_details = req
.mandate_id
.clone()
.map(RecurringDetails::MandateId)
.or(req.recurring_details.clone());
Self {
recurring_details,
confirm: req.confirm,
customer_id: req
.customer
.as_ref()
.map(|customer_details| &customer_details.id)
.or(req.customer_id.as_ref())
.map(ToOwned::to_owned),
mandate_data: req.mandate_data.clone(),
setup_future_usage: req.setup_future_usage,
off_session: req.off_session,
}
}
}
impl From<&VerifyRequest> for MandateValidationFields {
fn from(req: &VerifyRequest) -> Self {
Self {
recurring_details: None,
confirm: Some(true),
customer_id: req.customer_id.clone(),
mandate_data: req.mandate_data.clone(),
off_session: req.off_session,
setup_future_usage: req.setup_future_usage,
}
}
}
// #[cfg(all(feature = "v2", feature = "payment_v2"))]
// impl From<PaymentsSessionRequest> for PaymentsSessionResponse {
// fn from(item: PaymentsSessionRequest) -> Self {
// let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret);
// Self {
// session_token: vec![],
// payment_id: item.payment_id,
// client_secret,
// }
// }
// }
#[cfg(feature = "v1")]
impl From<PaymentsSessionRequest> for PaymentsSessionResponse {
fn from(item: PaymentsSessionRequest) -> Self {
let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret);
Self {
session_token: vec![],
payment_id: item.payment_id,
client_secret,
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentsStartRequest> for PaymentsRequest {
fn from(item: PaymentsStartRequest) -> Self {
Self {
payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)),
merchant_id: Some(item.merchant_id),
..Default::default()
}
}
}
impl From<AdditionalCardInfo> for CardResponse {
fn from(card: AdditionalCardInfo) -> Self {
Self {
last4: card.last4,
card_type: card.card_type,
card_network: card.card_network,
card_issuer: card.card_issuer,
card_issuing_country: card.card_issuing_country,
card_isin: card.card_isin,
card_extended_bin: card.card_extended_bin,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_holder_name: card.card_holder_name,
payment_checks: card.payment_checks,
authentication_data: card.authentication_data,
}
}
}
impl From<KlarnaSdkPaymentMethod> for PaylaterResponse {
fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self {
Self {
klarna_sdk: Some(KlarnaSdkPaymentMethodResponse {
payment_type: klarna_sdk.payment_type,
}),
}
}
}
impl From<AdditionalPaymentData> for PaymentMethodDataResponse {
fn from(payment_method_data: AdditionalPaymentData) -> Self {
match payment_method_data {
AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))),
AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk {
Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))),
None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })),
},
AdditionalPaymentData::Wallet {
apple_pay,
google_pay,
samsung_pay,
} => match (apple_pay, google_pay, samsung_pay) {
(Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse {
details: Some(WalletResponseData::ApplePay(Box::new(
additional_info::WalletAdditionalDataForCard {
last4: apple_pay_pm
.display_name
.clone()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>(),
card_network: apple_pay_pm.network.clone(),
card_type: Some(apple_pay_pm.pm_type.clone()),
},
))),
})),
(_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse {
details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))),
})),
(_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse {
details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))),
})),
_ => Self::Wallet(Box::new(WalletResponse { details: None })),
},
AdditionalPaymentData::BankRedirect { bank_name, details } => {
Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details }))
}
AdditionalPaymentData::Crypto { details } => {
Self::Crypto(Box::new(CryptoResponse { details }))
}
AdditionalPaymentData::BankDebit { details } => {
Self::BankDebit(Box::new(BankDebitResponse { details }))
}
AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {},
AdditionalPaymentData::Reward {} => Self::Reward {},
AdditionalPaymentData::RealTimePayment { details } => {
Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details }))
}
AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })),
AdditionalPaymentData::BankTransfer { details } => {
Self::BankTransfer(Box::new(BankTransferResponse { details }))
}
AdditionalPaymentData::Voucher { details } => {
Self::Voucher(Box::new(VoucherResponse { details }))
}
AdditionalPaymentData::GiftCard { details } => {
Self::GiftCard(Box::new(GiftCardResponse { details }))
}
AdditionalPaymentData::CardRedirect { details } => {
Self::CardRedirect(Box::new(CardRedirectResponse { details }))
}
AdditionalPaymentData::CardToken { details } => {
Self::CardToken(Box::new(CardTokenResponse { details }))
}
AdditionalPaymentData::OpenBanking { details } => {
Self::OpenBanking(Box::new(OpenBankingResponse { details }))
}
AdditionalPaymentData::MobilePayment { details } => {
Self::MobilePayment(Box::new(MobilePaymentResponse { details }))
}
}
}
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PgRedirectResponse {
pub payment_id: id_type::PaymentId,
pub status: api_enums::IntentStatus,
pub gateway_id: String,
pub customer_id: Option<id_type::CustomerId>,
pub amount: Option<MinorUnit>,
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)]
pub struct RedirectionResponse {
pub return_url: String,
pub params: Vec<(String, String)>,
pub return_url_with_query_params: String,
pub http_method: String,
pub headers: Vec<(String, String)>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)]
pub struct RedirectionResponse {
pub return_url_with_query_params: String,
}
#[derive(Debug, serde::Deserialize)]
pub struct PaymentsResponseForm {
pub transaction_id: String,
// pub transaction_reference_id: String,
pub merchant_id: id_type::MerchantId,
pub order_id: String,
}
#[cfg(feature = "v1")]
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsRetrieveRequest {
/// The type of ID (ex: payment intent id, payment attempt id or connector txn id)
#[schema(value_type = String)]
pub resource_id: PaymentIdType,
/// The identifier for the Merchant Account.
#[schema(value_type = Option<String>)]
pub merchant_id: Option<id_type::MerchantId>,
/// Decider to enable or disable the connector call for retrieve request
pub force_sync: bool,
/// Optional query parameters that might be specific to a connector or flow, passed through during the retrieve operation. Use with caution and refer to specific connector documentation if applicable.
pub param: Option<String>,
/// Optionally specifies the connector to be used for a 'force_sync' retrieve operation. If provided, Hyperswitch will attempt to sync the payment status from this specific connector.
pub connector: Option<String>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorDetailsWrap>)]
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
pub client_secret: Option<String>,
/// If enabled provides list of captures linked to latest attempt
pub expand_captures: Option<bool>,
/// If enabled provides list of attempts linked to payment intent
pub expand_attempts: Option<bool>,
/// If enabled, provides whole connector response
pub all_keys_required: Option<bool>,
}
#[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct OrderDetailsWithAmount {
/// Name of the product that is being purchased
#[schema(max_length = 255, example = "shirt")]
pub product_name: String,
/// The quantity of the product to be purchased
#[schema(example = 1)]
pub quantity: u16,
/// the amount per quantity of product
#[schema(value_type = i64)]
pub amount: MinorUnit,
/// tax rate applicable to the product
pub tax_rate: Option<f64>,
/// total tax amount applicable to the product
#[schema(value_type = Option<i64>)]
pub total_tax_amount: Option<MinorUnit>,
// Does the order includes shipping
pub requires_shipping: Option<bool>,
/// The image URL of the product
pub product_img_link: Option<String>,
/// ID of the product that is being purchased
pub product_id: Option<String>,
/// Category of the product that is being purchased
pub category: Option<String>,
/// Sub category of the product that is being purchased
pub sub_category: Option<String>,
/// Brand of the product that is being purchased
pub brand: Option<String>,
/// Type of the product that is being purchased
pub product_type: Option<ProductType>,
/// The tax code for the product
pub product_tax_code: Option<String>,
/// Description for the item
pub description: Option<String>,
/// Stock Keeping Unit (SKU) or the item identifier for this item.
pub sku: Option<String>,
/// Universal Product Code for the item.
pub upc: Option<String>,
/// Code describing a commodity or a group of commodities pertaining to goods classification.
pub commodity_code: Option<String>,
/// Unit of measure used for the item quantity.
pub unit_of_measure: Option<String>,
/// Total amount for the item.
#[schema(value_type = Option<i64>)]
pub total_amount: Option<MinorUnit>, // total_amount,
/// Discount amount applied to this item.
#[schema(value_type = Option<i64>)]
pub unit_discount_amount: Option<MinorUnit>,
}
impl masking::SerializableSecret for OrderDetailsWithAmount {}
#[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct RedirectResponse {
#[schema(value_type = Option<String>)]
pub param: Option<Secret<String>>,
#[schema(value_type = Option<Object>)]
pub json_payload: Option<pii::SecretSerdeValue>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsSessionRequest {}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsSessionRequest {
/// The identifier for the payment
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
pub client_secret: String,
/// The list of the supported wallets
#[schema(value_type = Vec<PaymentMethodType>)]
pub wallets: Vec<api_enums::PaymentMethodType>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorDetailsWrap>)]
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentsUpdateMetadataRequest {
/// The unique identifier for the payment
#[serde(skip_deserializing)]
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Object, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: pii::SecretSerdeValue,
}
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsUpdateMetadataResponse {
/// The identifier for the payment
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsPostSessionTokensRequest {
/// The unique identifier for the payment
#[serde(skip_deserializing)]
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// It's a token used for client side verification.
#[schema(value_type = String)]
pub client_secret: Secret<String>,
/// Payment method type
#[schema(value_type = PaymentMethodType)]
pub payment_method_type: api_enums::PaymentMethodType,
/// The payment method that is to be used for the payment
#[schema(value_type = PaymentMethod, example = "card")]
pub payment_method: api_enums::PaymentMethod,
}
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsPostSessionTokensResponse {
/// The identifier for the payment
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// Additional information required for redirection
pub next_action: Option<NextActionData>,
#[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")]
pub status: api_enums::IntentStatus,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct PaymentsDynamicTaxCalculationRequest {
/// The unique identifier for the payment
#[serde(skip_deserializing)]
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// The shipping address for the payment
pub shipping: Address,
/// Client Secret
#[schema(value_type = String)]
pub client_secret: Secret<String>,
/// Payment method type
#[schema(value_type = PaymentMethodType)]
pub payment_method_type: api_enums::PaymentMethodType,
/// Session Id
pub session_id: Option<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct PaymentsDynamicTaxCalculationResponse {
/// The identifier for the payment
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// net amount = amount + order_tax_amount + shipping_cost
pub net_amount: MinorUnit,
/// order tax amount calculated by tax connectors
pub order_tax_amount: Option<MinorUnit>,
/// shipping cost for the order
pub shipping_cost: Option<MinorUnit>,
/// amount in Base Unit display format
pub display_amount: DisplayAmountOnSdk,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct DisplayAmountOnSdk {
/// net amount = amount + order_tax_amount + shipping_cost
#[schema(value_type = String)]
pub net_amount: StringMajorUnit,
/// order tax amount calculated by tax connectors
#[schema(value_type = String)]
pub order_tax_amount: Option<StringMajorUnit>,
/// shipping cost for the order
#[schema(value_type = String)]
pub shipping_cost: Option<StringMajorUnit>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayAllowedMethodsParameters {
/// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc)
pub allowed_auth_methods: Vec<String>,
/// The list of allowed card networks (ex: AMEX,JCB etc)
pub allowed_card_networks: Vec<String>,
/// Is billing address required
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address_required: Option<bool>,
/// Billing address parameters
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address_parameters: Option<GpayBillingAddressParameters>,
/// Whether assurance details are required
#[serde(skip_serializing_if = "Option::is_none")]
pub assurance_details_required: Option<bool>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayBillingAddressParameters {
/// Is billing phone number required
pub phone_number_required: bool,
/// Billing address format
pub format: GpayBillingAddressFormat,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub enum GpayBillingAddressFormat {
FULL,
MIN,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayTokenParameters {
/// The name of the connector
#[serde(skip_serializing_if = "Option::is_none")]
pub gateway: Option<String>,
/// The merchant ID registered in the connector associated
#[serde(skip_serializing_if = "Option::is_none")]
pub gateway_merchant_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")]
pub stripe_version: Option<String>,
#[serde(
skip_serializing_if = "Option::is_none",
rename = "stripe:publishableKey"
)]
pub stripe_publishable_key: Option<String>,
/// The protocol version for encryption
#[serde(skip_serializing_if = "Option::is_none")]
pub protocol_version: Option<String>,
/// The public key provided by the merchant
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<String>)]
pub public_key: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayTokenizationSpecification {
/// The token specification type(ex: PAYMENT_GATEWAY)
#[serde(rename = "type")]
pub token_specification_type: String,
/// The parameters for the token specification Google Pay
pub parameters: GpayTokenParameters,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayAllowedPaymentMethods {
/// The type of payment method
#[serde(rename = "type")]
pub payment_method_type: String,
/// The parameters Google Pay requires
pub parameters: GpayAllowedMethodsParameters,
/// The tokenization specification for Google Pay
pub tokenization_specification: GpayTokenizationSpecification,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayTransactionInfo {
/// The country code
#[schema(value_type = CountryAlpha2, example = "US")]
pub country_code: api_enums::CountryAlpha2,
/// The currency code
#[schema(value_type = Currency, example = "USD")]
pub currency_code: api_enums::Currency,
/// The total price status (ex: 'FINAL')
pub total_price_status: String,
/// The total price
#[schema(value_type = String, example = "38.02")]
pub total_price: StringMajorUnit,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayMerchantInfo {
/// The merchant Identifier that needs to be passed while invoking Gpay SDK
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_id: Option<String>,
/// The name of the merchant that needs to be displayed on Gpay PopUp
pub merchant_name: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GpayMetaData {
pub merchant_info: GpayMerchantInfo,
pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GpaySessionTokenData {
#[serde(rename = "google_pay")]
pub data: GpayMetaData,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PazeSessionTokenData {
#[serde(rename = "paze")]
pub data: PazeMetadata,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PazeMetadata {
pub client_id: String,
pub client_name: String,
pub client_profile_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SamsungPayCombinedMetadata {
// This is to support the Samsung Pay decryption flow with application credentials,
// where the private key, certificates, or any other information required for decryption
// will be obtained from the application configuration.
ApplicationCredentials(SamsungPayApplicationCredentials),
MerchantCredentials(SamsungPayMerchantCredentials),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SamsungPaySessionTokenData {
#[serde(rename = "samsung_pay")]
pub data: SamsungPayCombinedMetadata,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SamsungPayMerchantCredentials {
pub service_id: String,
pub merchant_display_name: String,
pub merchant_business_country: api_enums::CountryAlpha2,
pub allowed_brands: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SamsungPayApplicationCredentials {
pub merchant_display_name: String,
pub merchant_business_country: api_enums::CountryAlpha2,
pub allowed_brands: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaypalSdkMetaData {
pub client_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaypalSdkSessionTokenData {
#[serde(rename = "paypal_sdk")]
pub data: PaypalSdkMetaData,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplepaySessionRequest {
pub merchant_identifier: String,
pub display_name: String,
pub initiative: String,
pub initiative_context: String,
}
/// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ConnectorMetadata {
pub apple_pay: Option<ApplepayConnectorMetadataRequest>,
pub airwallex: Option<AirwallexData>,
pub noon: Option<NoonData>,
pub braintree: Option<BraintreeData>,
pub adyen: Option<AdyenConnectorMetadata>,
}
impl ConnectorMetadata {
pub fn from_value(
value: pii::SecretSerdeValue,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorMetadata")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"Metadata",
))
}
pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> {
self.apple_pay.and_then(|applepay_metadata| {
applepay_metadata
.session_token_data
.map(|session_token_data| {
let SessionTokenInfo {
certificate,
certificate_keys,
..
} = session_token_data;
(certificate, certificate_keys)
})
})
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct AirwallexData {
/// payload required by airwallex
payload: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct NoonData {
/// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard)
pub order_category: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct BraintreeData {
/// Information about the merchant_account_id that merchant wants to specify at connector level.
#[schema(value_type = String)]
pub merchant_account_id: Option<Secret<String>>,
/// Information about the merchant_config_currency that merchant wants to specify at connector level.
#[schema(value_type = String)]
pub merchant_config_currency: Option<api_enums::Currency>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct AdyenConnectorMetadata {
pub testing: AdyenTestingData,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct AdyenTestingData {
/// Holder name to be sent to Adyen for a card payment(CIT) or a generic payment(MIT). This value overrides the values for card.card_holder_name and applies during both CIT and MIT payment transactions.
#[schema(value_type = String)]
pub holder_name: Option<Secret<String>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ApplepayConnectorMetadataRequest {
pub session_token_data: Option<SessionTokenInfo>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ApplepaySessionTokenData {
pub apple_pay: ApplePayMetadata,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ApplepayCombinedSessionTokenData {
pub apple_pay_combined: ApplePayCombinedMetadata,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApplepaySessionTokenMetadata {
ApplePayCombined(ApplePayCombinedMetadata),
ApplePay(ApplePayMetadata),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ApplePayMetadata {
pub payment_request_data: PaymentRequestMetadata,
pub session_token_data: SessionTokenInfo,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApplePayCombinedMetadata {
Simplified {
payment_request_data: PaymentRequestMetadata,
session_token_data: SessionTokenForSimplifiedApplePay,
},
Manual {
payment_request_data: PaymentRequestMetadata,
session_token_data: SessionTokenInfo,
},
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentRequestMetadata {
pub supported_networks: Vec<String>,
pub merchant_capabilities: Vec<String>,
pub label: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct SessionTokenInfo {
#[schema(value_type = String)]
pub certificate: Secret<String>,
#[schema(value_type = String)]
pub certificate_keys: Secret<String>,
pub merchant_identifier: String,
pub display_name: String,
pub initiative: ApplepayInitiative,
pub initiative_context: Option<String>,
#[schema(value_type = Option<CountryAlpha2>)]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
#[serde(flatten)]
pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ApplepayInitiative {
Web,
Ios,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(tag = "payment_processing_details_at")]
pub enum PaymentProcessingDetailsAt {
Hyperswitch(PaymentProcessingDetails),
Connector,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]
pub struct PaymentProcessingDetails {
#[schema(value_type = String)]
pub payment_processing_certificate: Secret<String>,
#[schema(value_type = String)]
pub payment_processing_certificate_key: Secret<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct SessionTokenForSimplifiedApplePay {
pub initiative_context: String,
#[schema(value_type = Option<CountryAlpha2>)]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GooglePayWalletDetails {
pub google_pay: GooglePayDetails,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GooglePayDetails {
pub provider_details: GooglePayProviderDetails,
pub cards: GpayAllowedMethodsParameters,
}
// Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails
// GooglePayHyperSwitchDetails is not implemented yet
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum GooglePayProviderDetails {
GooglePayMerchantDetails(GooglePayMerchantDetails),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GooglePayMerchantDetails {
pub merchant_info: GooglePayMerchantInfo,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GooglePayMerchantInfo {
pub merchant_name: String,
pub merchant_id: Option<String>,
pub tokenization_specification: GooglePayTokenizationSpecification,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GooglePayTokenizationSpecification {
#[serde(rename = "type")]
pub tokenization_type: GooglePayTokenizationType,
pub parameters: GooglePayTokenizationParameters,
}
|
crates/api_models/src/payments.rs#chunk8
|
api_models
|
chunk
| 8,189
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentMethodBalance {
pub amount: MinorUnit,
pub currency: common_enums::enums::Currency,
}
|
crates/hyperswitch_domain_models/src/router_data.rs
|
hyperswitch_domain_models
|
struct_definition
| 26
|
rust
|
PaymentMethodBalance
| null | null | null | null | null | null | null | null | null | null | null |
pub struct SwitchOrganizationRequest {
pub org_id: id_type::OrganizationId,
}
|
crates/api_models/src/user.rs
|
api_models
|
struct_definition
| 18
|
rust
|
SwitchOrganizationRequest
| null | null | null | null | null | null | null | null | null | null | null |
/// Create a new Instance of IntermediateString using a string
pub fn new(inner: String) -> Self {
Self(inner)
}
|
crates/external_services/src/email.rs
|
external_services
|
function_signature
| 29
|
rust
| null | null | null | null |
new
| null | null | null | null | null | null | null |
pub async fn list_roles_with_info(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<role_api::ListRolesQueryParams>,
) -> HttpResponse {
let flow = Flow::ListRolesV2;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
query.into_inner(),
|state, user_from_token, request, _| {
role_core::list_roles_with_info(state, user_from_token, request)
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/user_role.rs
|
router
|
function_signature
| 144
|
rust
| null | null | null | null |
list_roles_with_info
| null | null | null | null | null | null | null |
pub async fn perform_contract_based_routing<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
_dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
if contract_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing contract_based_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::ContractRoutingClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.contract_based_client;
let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::ContractBasedRoutingConfig,
>(
state,
profile_id,
contract_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "contract_based_routing_algorithm_id".to_string(),
})
.attach_printable("contract_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("unable to fetch contract based dynamic routing configs")?;
let label_info = contract_based_routing_configs
.label_info
.clone()
.ok_or(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("Label information not found in contract routing configs")?;
let contract_based_connectors = routable_connectors
.clone()
.into_iter()
.filter(|conn| {
label_info
.iter()
.any(|info| Some(info.mca_id.clone()) == conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let mut other_connectors = routable_connectors
.into_iter()
.filter(|conn| {
label_info
.iter()
.all(|info| Some(info.mca_id.clone()) != conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let event_request = utils::CalContractScoreEventRequest {
id: profile_id.get_string_repr().to_string(),
params: "".to_string(),
labels: contract_based_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: Some(contract_based_routing_configs.clone()),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: PerformContractRouting".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let contract_based_connectors_result = client
.calculate_contract_score(
profile_id.get_string_repr().into(),
contract_based_routing_configs.clone(),
"".to_string(),
contract_based_connectors,
state.get_grpc_headers(),
)
.await
.attach_printable(
"unable to calculate/fetch contract score from dynamic routing service",
);
let contract_based_connectors = match contract_based_connectors_result {
Ok(resp) => Some(utils::CalContractScoreEventResponse::from(&resp)),
Err(err) => match err.current_context() {
DynamicRoutingError::ContractNotFound => {
client
.update_contracts(
profile_id.get_string_repr().into(),
label_info,
"".to_string(),
vec![],
u64::default(),
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::ContractScoreUpdationError)
.attach_printable(
"unable to update contract based routing window in dynamic routing service",
)?;
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into());
}
_ => {
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into())
}
},
};
Ok(contract_based_connectors)
};
let events_response = routing_events_wrapper
.construct_event_builder(
"ContractScoreCalculator.FetchContractScore".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let contract_based_connectors: utils::CalContractScoreEventResponse = events_response
.response
.ok_or(errors::RoutingError::ContractScoreCalculationError {
err: "CalContractScoreEventResponse not found".to_string(),
})?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::ContractBasedRouting,
));
let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());
for label_with_score in contract_based_connectors.labels_with_score {
let (connector, merchant_connector_id) = label_with_score.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
)?;
connectors.push(api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
});
}
connectors.append(&mut other_connectors);
logger::debug!(contract_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
routing_event.set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
|
crates/router/src/core/payments/routing.rs
|
router
|
function_signature
| 1,633
|
rust
| null | null | null | null |
perform_contract_based_routing
| null | null | null | null | null | null | null |
pub fn reverse_string(s: &str) -> String {
s.chars().rev().collect()
}
|
crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
|
hyperswitch_connectors
|
function_signature
| 21
|
rust
| null | null | null | null |
reverse_string
| null | null | null | null | null | null | null |
pub async fn find_user_scoped_dashboard_metadata(
conn: &PgPooledConn,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_types: Vec<enums::DashboardMetadata>,
) -> StorageResult<Vec<Self>> {
let predicate = dsl::user_id
.eq(user_id)
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::org_id.eq(org_id))
.and(dsl::data_key.eq_any(data_types));
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
predicate,
None,
None,
Some(dsl::last_modified_at.asc()),
)
.await
}
|
crates/diesel_models/src/query/dashboard_metadata.rs
|
diesel_models
|
function_signature
| 167
|
rust
| null | null | null | null |
find_user_scoped_dashboard_metadata
| null | null | null | null | null | null | null |
pub struct ProfileDefaultRoutingConfig {
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub connectors: Vec<RoutableConnectorChoice>,
}
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
| 41
|
rust
|
ProfileDefaultRoutingConfig
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/compatibility/stripe/setup_intents.rs
Public functions: 4
pub mod types;
#[cfg(feature = "v1")]
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(feature = "v1")]
use api_models::payments as payment_types;
#[cfg(feature = "v1")]
use error_stack::report;
#[cfg(feature = "v1")]
use router_env::{instrument, tracing, Flow};
#[cfg(feature = "v1")]
use crate::{
compatibility::{
stripe::{errors, payment_intents::types as stripe_payment_types},
wrap,
},
core::{api_locking, payments},
routes,
services::{api, authentication as auth},
types::{api as api_types, domain},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate))]
pub async fn setup_intents_create(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let payload: types::StripeSetupIntentRequest = match qs_config.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
let create_payment_req: payment_types::PaymentsRequest =
match payment_types::PaymentsRequest::try_from(payload) {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = Flow::PaymentsCreate;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeSetupIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
create_payment_req,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::SetupMandate,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::SetupMandate>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentCreate,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))]
pub async fn setup_intents_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
query_payload: web::Query<stripe_payment_types::StripePaymentRetrieveBody>,
) -> HttpResponse {
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()),
merchant_id: None,
force_sync: true,
connector: None,
param: None,
merchant_connector_details: None,
client_secret: query_payload.client_secret.clone(),
expand_attempts: None,
expand_captures: None,
all_keys_required: None,
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = Flow::PaymentsRetrieveForceSync;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeSetupIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, payload, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::PSync,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentStatus,
payload,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))]
pub async fn setup_intents_update(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let setup_id = path.into_inner();
let stripe_payload: types::StripeSetupIntentRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
let mut payload: payment_types::PaymentsRequest =
match payment_types::PaymentsRequest::try_from(stripe_payload) {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id));
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = Flow::PaymentsUpdate;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeSetupIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::SetupMandate,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::SetupMandate>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentUpdate,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm))]
pub async fn setup_intents_confirm(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let setup_id = path.into_inner();
let stripe_payload: types::StripeSetupIntentRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
let mut payload: payment_types::PaymentsRequest =
match payment_types::PaymentsRequest::try_from(stripe_payload) {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id));
payload.confirm = Some(true);
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = Flow::PaymentsConfirm;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeSetupIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::SetupMandate,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::SetupMandate>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentConfirm,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/compatibility/stripe/setup_intents.rs
|
router
|
full_file
| 2,229
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::RefundSync for Rapyd {}
|
crates/hyperswitch_connectors/src/connectors/rapyd.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
Rapyd
|
api::RefundSync for
|
impl api::RefundSync for for Rapyd
| null | null | null | null | null | null | null | null |
File: crates/masking/src/bytes.rs
Public functions: 1
Public structs: 1
//! Optional `Secret` wrapper type for the `bytes::BytesMut` crate.
use core::fmt;
use bytes::BytesMut;
#[cfg(all(feature = "bytes", feature = "serde"))]
use serde::de::{self, Deserialize};
use super::{PeekInterface, ZeroizableSecret};
/// Instance of [`BytesMut`] protected by a type that impls the [`ExposeInterface`]
/// trait like `Secret<T>`.
///
/// Because of the nature of how the `BytesMut` type works, it needs some special
/// care in order to have a proper zeroizing drop handler.
#[derive(Clone)]
#[cfg_attr(docsrs, cfg(feature = "bytes"))]
pub struct SecretBytesMut(BytesMut);
impl SecretBytesMut {
/// Wrap bytes in `SecretBytesMut`
pub fn new(bytes: impl Into<BytesMut>) -> Self {
Self(bytes.into())
}
}
impl PeekInterface<BytesMut> for SecretBytesMut {
fn peek(&self) -> &BytesMut {
&self.0
}
fn peek_mut(&mut self) -> &mut BytesMut {
&mut self.0
}
}
impl fmt::Debug for SecretBytesMut {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SecretBytesMut([REDACTED])")
}
}
impl From<BytesMut> for SecretBytesMut {
fn from(bytes: BytesMut) -> Self {
Self::new(bytes)
}
}
impl Drop for SecretBytesMut {
fn drop(&mut self) {
self.0.resize(self.0.capacity(), 0);
self.0.as_mut().zeroize();
debug_assert!(self.0.as_ref().iter().all(|b| *b == 0));
}
}
#[cfg(all(feature = "bytes", feature = "serde"))]
impl<'de> Deserialize<'de> for SecretBytesMut {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct SecretBytesVisitor;
impl<'de> de::Visitor<'de> for SecretBytesVisitor {
type Value = SecretBytesMut;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("byte array")
}
#[inline]
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
let mut bytes = BytesMut::with_capacity(v.len());
bytes.extend_from_slice(v);
Ok(SecretBytesMut(bytes))
}
#[inline]
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: de::SeqAccess<'de>,
{
// 4096 is cargo culted from upstream
let len = core::cmp::min(seq.size_hint().unwrap_or(0), 4096);
let mut bytes = BytesMut::with_capacity(len);
use bytes::BufMut;
while let Some(value) = seq.next_element()? {
bytes.put_u8(value);
}
Ok(SecretBytesMut(bytes))
}
}
deserializer.deserialize_bytes(SecretBytesVisitor)
}
}
|
crates/masking/src/bytes.rs
|
masking
|
full_file
| 733
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl SubscriptionNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Subscription> {
generics::generic_insert(conn, self).await
}
}
|
crates/diesel_models/src/query/subscription.rs
|
diesel_models
|
impl_block
| 40
|
rust
| null |
SubscriptionNew
| null |
impl SubscriptionNew
| null | null | null | null | null | null | null | null |
pub struct ZslPaymentsResponse {
process_type: ProcessType,
process_code: ProcessCode,
status: String,
mer_ref: String,
mer_id: String,
enctype: EncodingType,
txn_url: String,
signature: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 57
|
rust
|
ZslPaymentsResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct NovalnetRawCardDetails {
card_number: CardNumber,
card_expiry_month: Secret<String>,
card_expiry_year: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 33
|
rust
|
NovalnetRawCardDetails
| null | null | null | null | null | null | null | null | null | null | null |
impl api::Refund for Aci {}
|
crates/hyperswitch_connectors/src/connectors/aci.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Aci
|
api::Refund for
|
impl api::Refund for for Aci
| null | null | null | null | null | null | null | null |
pub struct AppState {
pub conf: Arc<Settings<RawSecret>>,
pub encryption_client: Arc<dyn EncryptionManagementInterface>,
}
|
crates/drainer/src/settings.rs
|
drainer
|
struct_definition
| 27
|
rust
|
AppState
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.AuthenticationConnectors
{
"type": "string",
"enum": [
"threedsecureio",
"netcetera",
"gpayments",
"ctp_mastercard",
"unified_authentication_service",
"juspaythreedsserver",
"ctp_visa"
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 76
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"AuthenticationConnectors"
] | null | null | null | null |
pub fn collect(self) -> RefundMetricsBucketValue {
let (successful_refunds, total_refunds, refund_success_rate) =
self.refund_success_rate.collect();
let (refund_processed_amount, refund_processed_count, refund_processed_amount_in_usd) =
self.processed_amount.collect();
RefundMetricsBucketValue {
successful_refunds,
total_refunds,
refund_success_rate,
refund_count: self.refund_count.collect(),
refund_success_count: self.refund_success.collect(),
refund_processed_amount,
refund_processed_amount_in_usd,
refund_processed_count,
refund_reason_distribution: self.refund_reason_distribution.collect(),
refund_error_message_distribution: self.refund_error_message_distribution.collect(),
refund_reason_count: self.refund_reason.collect(),
refund_error_message_count: self.refund_error_message.collect(),
}
}
|
crates/analytics/src/refunds/accumulator.rs
|
analytics
|
function_signature
| 177
|
rust
| null | null | null | null |
collect
| null | null | null | null | null | null | null |
Documentation: api-reference/v2/customers/customers--list.mdx
# Type: Doc File
---
openapi: get /v2/customers/list
---
|
api-reference/v2/customers/customers--list.mdx
| null |
doc_file
| 34
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub struct FiuuPaymentRequest {
#[serde(rename = "MerchantID")]
merchant_id: Secret<String>,
reference_no: String,
txn_type: TxnType,
txn_currency: Currency,
txn_amount: StringMajorUnit,
signature: Secret<String>,
#[serde(rename = "ReturnURL")]
return_url: Option<String>,
#[serde(rename = "NotificationURL")]
notification_url: Option<Url>,
#[serde(flatten)]
payment_method_data: FiuuPaymentMethodData,
}
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 110
|
rust
|
FiuuPaymentRequest
| null | null | null | null | null | null | null | null | null | null | null |
/// Set the private fields of merchant account
pub struct MerchantAccountSetter {
pub id: common_utils::id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: diesel_models::enums::ReconStatus,
pub is_platform_account: bool,
pub version: common_enums::ApiVersion,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
|
crates/hyperswitch_domain_models/src/merchant_account.rs
|
hyperswitch_domain_models
|
struct_definition
| 175
|
rust
|
MerchantAccountSetter
| null | null | null | null | null | null | null | null | null | null | null |
/// Trait to convert the raw data to the required format for encryption service request
pub trait ConvertRaw {
/// Return type of the convert_raw function
type Output: serde::Serialize;
/// Function to convert the raw data to the required format for encryption service request
fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError>;
}
|
crates/common_utils/src/keymanager.rs
|
common_utils
|
trait_definition
| 76
|
rust
| null | null |
ConvertRaw
| null | null | null | null | null | null | null | null | null |
/// Retains the connector name and payment method in every flattened element
pub fn from_payment_connectors_list(payment_connectors: Vec<MerchantConnectorAccount>) -> Self {
let payment_methods_enabled_flattened_with_connector = payment_connectors
.into_iter()
.map(|connector| {
(
connector
.payment_methods_enabled
.clone()
.unwrap_or_default(),
connector.connector_name,
connector.get_id(),
)
})
.flat_map(
|(payment_method_enabled, connector, merchant_connector_id)| {
payment_method_enabled
.into_iter()
.flat_map(move |payment_method| {
let request_payment_methods_enabled =
payment_method.payment_method_subtypes.unwrap_or_default();
let length = request_payment_methods_enabled.len();
request_payment_methods_enabled.into_iter().zip(
std::iter::repeat((
connector,
merchant_connector_id.clone(),
payment_method.payment_method_type,
))
.take(length),
)
})
},
)
.map(
|(request_payment_methods, (connector, merchant_connector_id, payment_method))| {
PaymentMethodsEnabledForConnector {
payment_methods_enabled: request_payment_methods,
connector,
payment_method,
merchant_connector_id,
}
},
)
.collect();
Self {
payment_methods_enabled: payment_methods_enabled_flattened_with_connector,
}
}
|
crates/hyperswitch_domain_models/src/merchant_connector_account.rs
|
hyperswitch_domain_models
|
function_signature
| 294
|
rust
| null | null | null | null |
from_payment_connectors_list
| null | null | null | null | null | null | null |
pub struct DwollaErrorResponse {
pub code: String,
pub message: String,
pub _embedded: Option<Vec<DwollaErrorDetails>>,
pub reason: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 39
|
rust
|
DwollaErrorResponse
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/core/payments/operations/payment_reject.rs
Public structs: 1
use std::marker::PhantomData;
use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest};
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentAddress, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "cancel")]
pub struct PaymentReject;
type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest>
for PaymentReject
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
_request: &PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>>
{
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::Cancelled,
enums::IntentStatus::Failed,
enums::IntentStatus::Succeeded,
enums::IntentStatus::Processing,
],
"reject",
)?;
let attempt_id = payment_intent.active_attempt.get_id().clone();
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
attempt_id.clone().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
let frm_response = if cfg!(feature = "frm") {
db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_context.get_merchant_account().get_id())
})
.ok()
} else {
None
};
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
token_data: None,
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: frm_response,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_should_decline_transaction: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate {
status: enums::IntentStatus::Failed,
merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()),
updated_by: storage_scheme.to_string(),
};
let (error_code, error_message) =
payment_data
.frm_message
.clone()
.map_or((None, None), |fraud_check| {
(
Some(Some(fraud_check.frm_status.to_string())),
Some(fraud_check.frm_reason.map(|reason| reason.to_string())),
)
});
let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate {
status: enums::AttemptStatus::Failure,
error_code,
error_message,
updated_by: storage_scheme.to_string(),
};
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
intent_status_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
attempt_status_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let error_code = payment_data.payment_attempt.error_code.clone();
let error_message = payment_data.payment_attempt.error_message.clone();
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentReject {
error_code,
error_message,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>>
for PaymentReject
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &PaymentsCancelRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
|
crates/router/src/core/payments/operations/payment_reject.rs
|
router
|
full_file
| 2,235
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn payment_method_retrieve_api() {}
|
crates/openapi/src/routes/payment_method.rs
|
openapi
|
function_signature
| 10
|
rust
| null | null | null | null |
payment_method_retrieve_api
| null | null | null | null | null | null | null |
**Full Changelog:** [`2024.08.02.0...2024.08.05.0`](https://github.com/juspay/hyperswitch/compare/2024.08.02.0...2024.08.05.0)
- - -
## 2024.08.02.0
### Features
- **auth:**
- Add support for partial-auth, by facilitating injection of authentication parameters in headers ([#4802](https://github.com/juspay/hyperswitch/pull/4802)) ([`1d4c87a`](https://github.com/juspay/hyperswitch/commit/1d4c87a9e37ab1fc05754208ba4fbbcf15ad895a))
- Add `profile_id` in `AuthenticationData` ([#5492](https://github.com/juspay/hyperswitch/pull/5492)) ([`b4eb601`](https://github.com/juspay/hyperswitch/commit/b4eb6016a4e696acf155732592a6571363c24e64))
- **business_profile:** Introduce domain models for business profile v1 and v2 APIs ([#5497](https://github.com/juspay/hyperswitch/pull/5497)) ([`537630f`](https://github.com/juspay/hyperswitch/commit/537630f00482939d4c0b49c643dee3763fe0e046))
- **connector:** [Paybox] add connector template code ([#5485](https://github.com/juspay/hyperswitch/pull/5485)) ([`5e1eb4a`](https://github.com/juspay/hyperswitch/commit/5e1eb4af863265c94299189de983e02a255e7e62))
- **core:** Accept business profile in core functions for payments, refund, payout and disputes ([#5498](https://github.com/juspay/hyperswitch/pull/5498)) ([`fb32b61`](https://github.com/juspay/hyperswitch/commit/fb32b61edfa2b4190a5717850aeca6b3b0d7db54))
- **cypress:** Add corner cases ([#5481](https://github.com/juspay/hyperswitch/pull/5481)) ([`c0f4577`](https://github.com/juspay/hyperswitch/commit/c0f45771b0b4d7d60918ae03aca9f14162ff3218))
- **opensearch:** Updated status filter field name to match index and added time-range based search ([#5468](https://github.com/juspay/hyperswitch/pull/5468)) ([`625f5ae`](https://github.com/juspay/hyperswitch/commit/625f5ae289ca93a1a6d469d6a0f71d7492f22bc5))
### Bug Fixes
- **open_payment_links:** Send displaySavedPaymentMethods as false explicitly for open payment links ([#5501](https://github.com/juspay/hyperswitch/pull/5501)) ([`b4e7717`](https://github.com/juspay/hyperswitch/commit/b4e77170559d5912758f18d2db46bf25eb5277b2))
### Refactors
- **role:** Determine level of role entity ([#5488](https://github.com/juspay/hyperswitch/pull/5488)) ([`c036fd7`](https://github.com/juspay/hyperswitch/commit/c036fd7f41a21eb481859671db672b0bcebdca97))
- **router:** Domain and diesel model changes for merchant_connector_account create v2 flow ([#5462](https://github.com/juspay/hyperswitch/pull/5462)) ([`85209d1`](https://github.com/juspay/hyperswitch/commit/85209d12ae3439b555983d62b2cc3bf764c1b441))
- **routing:** Api v2 for routing create and activate endpoints ([#5423](https://github.com/juspay/hyperswitch/pull/5423)) ([`6140cfe`](https://github.com/juspay/hyperswitch/commit/6140cfe04ea7b3f895f8989dbf2803a06b1a6dd2))
**Full Changelog:** [`2024.08.01.0...2024.08.02.0`](https://github.com/juspay/hyperswitch/compare/2024.08.01.0...2024.08.02.0)
- - -
## 2024.08.01.0
### Bug Fixes
- **payment_link:** Move redirection fn to global scope for open links ([#5494](https://github.com/juspay/hyperswitch/pull/5494)) ([`7ddfbf5`](https://github.com/juspay/hyperswitch/commit/7ddfbf51c3c3db99041e3d175a9100a60a339fe8))
### Documentation
- API-Ref changes for Payouts ([#5236](https://github.com/juspay/hyperswitch/pull/5236)) ([`540ef07`](https://github.com/juspay/hyperswitch/commit/540ef071cb238a56d52d06687226aab7fd0dfe68))
**Full Changelog:** [`2024.07.31.0...2024.08.01.0`](https://github.com/juspay/hyperswitch/compare/2024.07.31.0...2024.08.01.0)
- - -
## 2024.07.31.0
### Features
- **connector:** [BAMBORA, BITPAY, STAX] Move connector to hyperswitch_connectors ([#5450](https://github.com/juspay/hyperswitch/pull/5450)) ([`827fa07`](https://github.com/juspay/hyperswitch/commit/827fa07418b0514cbc5a43af2e4c7a88d1b7b4e7))
- **payment_link:** Add provision for secured payment links ([#5357](https://github.com/juspay/hyperswitch/pull/5357)) ([`043abb5`](https://github.com/juspay/hyperswitch/commit/043abb59b9291e18824d16363f60657f22bd33e1))
- Rename columns in organization for v2 ([#5424](https://github.com/juspay/hyperswitch/pull/5424)) ([`a791391`](https://github.com/juspay/hyperswitch/commit/a791391e2ac125ef7bb6a92de5f1419e673bdfe0))
### Bug Fixes
- **connector:** [Pix] convert data type of pix fields ([#5476](https://github.com/juspay/hyperswitch/pull/5476)) ([`be9347b`](https://github.com/juspay/hyperswitch/commit/be9347b8d56c0a6cf0d04cf51c75dd6426d3a21a))
### Refactors
- **configs:** Include env for cybersource in integration_test ([#5474](https://github.com/juspay/hyperswitch/pull/5474)) ([`b3b71b1`](https://github.com/juspay/hyperswitch/commit/b3b71b10c3627868420648e70913a0620dcb3b6e))
- **id_type:** Use macros for defining ID types and implementing common traits ([#5471](https://github.com/juspay/hyperswitch/pull/5471)) ([`1d4fb1d`](https://github.com/juspay/hyperswitch/commit/1d4fb1d2474190ea0a70810e416c61883fab34b8))
### Documentation
- Update postgreSQL database url ([#5482](https://github.com/juspay/hyperswitch/pull/5482)) ([`ef7fa0d`](https://github.com/juspay/hyperswitch/commit/ef7fa0d16ebe12bd86572c7ab80e7caa70d75578))
**Full Changelog:** [`2024.07.30.0...2024.07.31.0`](https://github.com/juspay/hyperswitch/compare/2024.07.30.0...2024.07.31.0)
- - -
## 2024.07.30.0
### Features
- Add env variable for enable key manager service ([#5442](https://github.com/juspay/hyperswitch/pull/5442)) ([`db26d32`](https://github.com/juspay/hyperswitch/commit/db26d32d8465e20cf3835fbfe6d0a19688078b8c))
### Refactors
- **router:** Remove `connector_account_details` and `connector_webhook_details` in merchant_connector_account list response ([#5457](https://github.com/juspay/hyperswitch/pull/5457)) ([`45a1494`](https://github.com/juspay/hyperswitch/commit/45a149418f1dad0cd27f975dc3dd56c68172b9dd))
**Full Changelog:** [`2024.07.29.0...2024.07.30.0`](https://github.com/juspay/hyperswitch/compare/2024.07.29.0...2024.07.30.0)
- - -
## 2024.07.29.0
### Features
- **connector:**
- [FISERV] Move connector to hyperswitch_connectors ([#5441](https://github.com/juspay/hyperswitch/pull/5441)) ([`2bee694`](https://github.com/juspay/hyperswitch/commit/2bee694d5bb7393c11817bbee26b459609f6dd8c))
- [Bambora APAC] add mandate flow ([#5376](https://github.com/juspay/hyperswitch/pull/5376)) ([`dbfa006`](https://github.com/juspay/hyperswitch/commit/dbfa006b475736bf415588680d7fc1a16bf16891))
- **payments:** Support sort criteria in payments list ([#5389](https://github.com/juspay/hyperswitch/pull/5389)) ([`043ea6d`](https://github.com/juspay/hyperswitch/commit/043ea6d8dc9fe8108e0b7eb8113217bc37fa488a))
### Bug Fixes
- Added created at and modified at keys in PaymentAttemptResponse ([#5412](https://github.com/juspay/hyperswitch/pull/5412)) ([`9795397`](https://github.com/juspay/hyperswitch/commit/979539702190363c67045d509be04498efd9a1fa))
### Refactors
- **connector:** Add amount conversion framework to placetopay ([#4988](https://github.com/juspay/hyperswitch/pull/4988)) ([`08334da`](https://github.com/juspay/hyperswitch/commit/08334dae82145e1fd699e0008fedcbd8bb7b23c7))
- **merchant_account_v2:** Recreate id for `merchant_account` v2 ([#5439](https://github.com/juspay/hyperswitch/pull/5439)) ([`93976db`](https://github.com/juspay/hyperswitch/commit/93976db30a91b3e67d854681fb4b9db8eea7e295))
- **opensearch:** Add Error Handling for Empty Query and Filters in Request ([#5432](https://github.com/juspay/hyperswitch/pull/5432)) ([`b60933e`](https://github.com/juspay/hyperswitch/commit/b60933e310abb4ee56355f28dfb56d9c60083f04))
### Miscellaneous Tasks
- Address Rust 1.80 clippy lints ([#5447](https://github.com/juspay/hyperswitch/pull/5447)) ([`074e90c`](https://github.com/juspay/hyperswitch/commit/074e90c9f9fbc26255ed27400a6a781aa6958339))
**Full Changelog:** [`2024.07.26.0...2024.07.29.0`](https://github.com/juspay/hyperswitch/compare/2024.07.26.0...2024.07.29.0)
- - -
## 2024.07.26.0
### Features
- **connector:** [HELCIM] Move connector to hyperswitch_connectors ([#5287](https://github.com/juspay/hyperswitch/pull/5287)) ([`0f89a0a`](https://github.com/juspay/hyperswitch/commit/0f89a0acbfc2d55f415e0daeb27e8d9022e6a862))
- **events:** Forward the tenant configuration as part of the kafka message ([#5224](https://github.com/juspay/hyperswitch/pull/5224)) ([`623cf4c`](https://github.com/juspay/hyperswitch/commit/623cf4c841847f109597ee50017d6cfc0b4d9982))
### Bug Fixes
- **cypress:** Fix cypress tests, failing due to error codes being recently changed ([#5425](https://github.com/juspay/hyperswitch/pull/5425)) ([`7228a87`](https://github.com/juspay/hyperswitch/commit/7228a874a3db43b89ae07941b04396215db394ef))
- **euclid:** Change the address taken in SessionFlowRouting from shipping to billing address ([#5435](https://github.com/juspay/hyperswitch/pull/5435)) ([`9ca9545`](https://github.com/juspay/hyperswitch/commit/9ca9545318d8e62d62b4dc58a09b90fcdeb58870))
### Refactors
- **connector:** Add amount conversion framework to payone ([#4981](https://github.com/juspay/hyperswitch/pull/4981)) ([`5eccffa`](https://github.com/juspay/hyperswitch/commit/5eccffac9d9f2b3e38ad07f6e12907e2c135b840))
- **user_roles:** Make org and merchant id nullable ([#5353](https://github.com/juspay/hyperswitch/pull/5353)) ([`0330aff`](https://github.com/juspay/hyperswitch/commit/0330aff958b80872fbd6a6fccc61ff1984c59511))
**Full Changelog:** [`2024.07.25.0...2024.07.26.0`](https://github.com/juspay/hyperswitch/compare/2024.07.25.0...2024.07.26.0)
- - -
## 2024.07.25.0
### Features
- **connector:** [Itaubank] Add refund and rsync flow ([#5420](https://github.com/juspay/hyperswitch/pull/5420)) ([`920b323`](https://github.com/juspay/hyperswitch/commit/920b3236ee132dac446fc73de82d24806c6b5148))
- **router:** Add merchant_connector_account create v2 api flow ([#5385](https://github.com/juspay/hyperswitch/pull/5385)) ([`98349a0`](https://github.com/juspay/hyperswitch/commit/98349a0c3bbc438e541a03e7fe1c005e5751e6e0))
- Add create retrieve and update api endpoints for organization resource ([#5361](https://github.com/juspay/hyperswitch/pull/5361)) ([`26b8783`](https://github.com/juspay/hyperswitch/commit/26b878308f7e493d6adb8c08b54a5498406eb28a))
- Create additional columns in organization table ([#5380](https://github.com/juspay/hyperswitch/pull/5380)) ([`65471da`](https://github.com/juspay/hyperswitch/commit/65471da57b19c8eb2922fba0350e06b37b53f45f))
### Bug Fixes
- **euclid:** Remove business_profile routing feature flag ([#5430](https://github.com/juspay/hyperswitch/pull/5430)) ([`e18ea7a`](https://github.com/juspay/hyperswitch/commit/e18ea7a7bab257a6082639e84da8d9e44f31168f))
### Refactors
- **connector:**
- Added amount conversion framework for billwerk ([#4972](https://github.com/juspay/hyperswitch/pull/4972)) ([`9d9dce9`](https://github.com/juspay/hyperswitch/commit/9d9dce90fc3dc2a51afa2b11035c4ae729329df4))
- Added amount conversion framework for bitpay ([#4973](https://github.com/juspay/hyperswitch/pull/4973)) ([`83dbb7a`](https://github.com/juspay/hyperswitch/commit/83dbb7a8daf44bdd3d8c0e98973bba4b90eb5861))
- **core:** Patch file for removal of id from schema ([#5398](https://github.com/juspay/hyperswitch/pull/5398)) ([`ff3b9a2`](https://github.com/juspay/hyperswitch/commit/ff3b9a2a12cd7f7e6c20f81777f6862b1f229bd4))
- **merchant_id:** Create domain type for `merchant_id` ([#5408](https://github.com/juspay/hyperswitch/pull/5408)) ([`7068fbf`](https://github.com/juspay/hyperswitch/commit/7068fbfbe2f561f71c2358d8d2a744d28672a892))
**Full Changelog:** [`2024.07.24.0...2024.07.25.0`](https://github.com/juspay/hyperswitch/compare/2024.07.24.0...2024.07.25.0)
- - -
## 2024.07.24.0
### Features
- **connector:** [WELLSFARGO] Add template code ([#5333](https://github.com/juspay/hyperswitch/pull/5333)) ([`94bb3e7`](https://github.com/juspay/hyperswitch/commit/94bb3e78fddf310d9ee3211f98a386e4f8261242))
- **customer:** Customer v2 refactor for customer create end point ([#5350](https://github.com/juspay/hyperswitch/pull/5350)) ([`aaf1f2b`](https://github.com/juspay/hyperswitch/commit/aaf1f2b1e5e1f473154a57af0d1b9402bd238ec4))
### Bug Fixes
- **connector:** [Datatrans] Handling for 4-Digit YYYY input and Correct 3DS Routing to no_3ds ([#5410](https://github.com/juspay/hyperswitch/pull/5410)) ([`3e16219`](https://github.com/juspay/hyperswitch/commit/3e1621944562a0fca3014a190393b744d235bc4c))
### Refactors
- **connector:**
- Add amount conversion framework to volt ([#4985](https://github.com/juspay/hyperswitch/pull/4985)) ([`e4b3982`](https://github.com/juspay/hyperswitch/commit/e4b3982c13cedf0f7feaec22df414761e22d98df))
- [Itaubank] add dynamic fields for pix ([#5419](https://github.com/juspay/hyperswitch/pull/5419)) ([`afae590`](https://github.com/juspay/hyperswitch/commit/afae5906a8d6ceab136393c7588bfc447e822ddc))
### Miscellaneous Tasks
- **users:** Email templates footer icon style enhance ([#5375](https://github.com/juspay/hyperswitch/pull/5375)) ([`876eeea`](https://github.com/juspay/hyperswitch/commit/876eeea0f426f63d0419021ba85372a016d46e27))
**Full Changelog:** [`2024.07.23.0...2024.07.24.0`](https://github.com/juspay/hyperswitch/compare/2024.07.23.0...2024.07.24.0)
- - -
## 2024.07.23.0
### Features
- **connector:** [Itau Bank] Add payment and sync flow for Pix ([#5342](https://github.com/juspay/hyperswitch/pull/5342)) ([`3fef96e`](https://github.com/juspay/hyperswitch/commit/3fef96e727ebb411d5699b8b37bdec30a2606da0))
### Bug Fixes
- **router:** Store `network_transaction_id` in stripe `authorize` flow ([#5399](https://github.com/juspay/hyperswitch/pull/5399)) ([`be78dfc`](https://github.com/juspay/hyperswitch/commit/be78dfc04eff671fb0b4e6037c84aee8ab367e70))
- Add offset and limit to key transfer API ([#5358](https://github.com/juspay/hyperswitch/pull/5358)) ([`b393803`](https://github.com/juspay/hyperswitch/commit/b393803a6199a12f86d7bbdc998e5a0d8366c000))
### Refactors
- **connector:** Add billing_country in klarna dynamic fields ([#5373](https://github.com/juspay/hyperswitch/pull/5373)) ([`4838a86`](https://github.com/juspay/hyperswitch/commit/4838a86ebcb5000e65293e0d095e5de95e3a64a0))
- **core:** Change primary keys in payment_methods table ([#5393](https://github.com/juspay/hyperswitch/pull/5393)) ([`ca749b3`](https://github.com/juspay/hyperswitch/commit/ca749b32591edcbf4676da4327f8b6ccbc839d4b))
- **dashboard_metadata:** Alter query for merchant scoped metadata ([#5397](https://github.com/juspay/hyperswitch/pull/5397)) ([`eaa391a`](https://github.com/juspay/hyperswitch/commit/eaa391a959076424399fb9331a78a16eaf790478))
- **router:** Make `original_payment_authorized_currency` and `original_payment_authorized_amount` mandatory fields for `Discover` cards and `Cybersource` connector during payment method migration. ([#5370](https://github.com/juspay/hyperswitch/pull/5370)) ([`06f1406`](https://github.com/juspay/hyperswitch/commit/06f1406cbc350a71f961a19dc2a6cfef2ceeb3a1))
### Miscellaneous Tasks
- Add missing logs for surcharge flow ([#5258](https://github.com/juspay/hyperswitch/pull/5258)) ([`bc19fca`](https://github.com/juspay/hyperswitch/commit/bc19fca1f4e76be6131e9c870b8aa1c709fef578))
- Add customer, shipping and billing details to payment_response for payment list api ([#5401](https://github.com/juspay/hyperswitch/pull/5401)) ([`fa6c63b`](https://github.com/juspay/hyperswitch/commit/fa6c63bd5409ec45f23ddf4616c5eb3cf399aa1b))
**Full Changelog:** [`2024.07.20.0...2024.07.23.0`](https://github.com/juspay/hyperswitch/compare/2024.07.20.0...2024.07.23.0)
- - -
## 2024.07.20.0
### Features
- **merchant_account_v2:** Add merchant_account_v2 domain and diesel models ([#5365](https://github.com/juspay/hyperswitch/pull/5365)) ([`5861c5a`](https://github.com/juspay/hyperswitch/commit/5861c5a63b3ab228d886888962e5734b9018eab9))
### Bug Fixes
- Use encrypt api for all encryption and decryption ([#5379](https://github.com/juspay/hyperswitch/pull/5379)) ([`83849a5`](https://github.com/juspay/hyperswitch/commit/83849a5f3cbb1843013535b0631e6e3d38d037b7))
### Refactors
- **core:** Change primary keys in user, user_roles and roles tables ([#5374](https://github.com/juspay/hyperswitch/pull/5374)) ([`b51c8e1`](https://github.com/juspay/hyperswitch/commit/b51c8e1d12c2f0012b8210a6c25c989f9dd89c3b))
**Full Changelog:** [`2024.07.19.1...2024.07.20.0`](https://github.com/juspay/hyperswitch/compare/2024.07.19.1...2024.07.20.0)
- - -
## 2024.07.19.1
### Features
- **connector:** Plaid connector Integration ([#3952](https://github.com/juspay/hyperswitch/pull/3952)) ([`eb01680`](https://github.com/juspay/hyperswitch/commit/eb01680284fea4d61ef95418878d49104885352e))
- Encryption service integration to support batch encryption and decryption ([#5164](https://github.com/juspay/hyperswitch/pull/5164)) ([`33298b3`](https://github.com/juspay/hyperswitch/commit/33298b38081c46fe4ee38f8ad6ddffd2b98a1d5c))
### Refactors
- **connector:** Make the `original_authorized_amount` optional for MITs with `connector_mandate_details` ([#5311](https://github.com/juspay/hyperswitch/pull/5311)) ([`a8e2f3e`](https://github.com/juspay/hyperswitch/commit/a8e2f3ebc9da60ef41459b080d8856d3cadf8c41))
- **core:** Change primary key of refund table ([#5367](https://github.com/juspay/hyperswitch/pull/5367)) ([`c698921`](https://github.com/juspay/hyperswitch/commit/c698921c417da4f6f74887224818ccb5d92b9fc3))
**Full Changelog:** [`2024.07.19.0...2024.07.19.1`](https://github.com/juspay/hyperswitch/compare/2024.07.19.0...2024.07.19.1)
- - -
## 2024.07.19.0
### Features
- **connector:** [Itau Bank] Template for payment flows ([#5304](https://github.com/juspay/hyperswitch/pull/5304)) ([`ef1418f`](https://github.com/juspay/hyperswitch/commit/ef1418f978835a8df149181bc5e19053775490f2))
### Bug Fixes
- **core:** [payouts] failure of payout retrieve when token is expired ([#5362](https://github.com/juspay/hyperswitch/pull/5362)) ([`817d06c`](https://github.com/juspay/hyperswitch/commit/817d06c7faa14493674931ba51ab6c32769602d1))
### Refactors
|
CHANGELOG.md#chunk26
| null |
doc_chunk
| 8,181
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn execute_payment(
state: &SessionState,
_merchant_id: &id_type::MerchantId,
payment_intent: &PaymentIntent,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata,
) -> RecoveryResult<Self> {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to deserialize the tracking data from process tracker")?;
let last_token_used = payment_intent
.feature_metadata
.as_ref()
.and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())
.map(|rr| {
rr.billing_connector_payment_details
.payment_processor_token
.clone()
});
let recovery_algorithm = tracking_data.revenue_recovery_retry;
let scheduled_token = match storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(
state,
&connector_customer_id,
recovery_algorithm,
last_token_used.as_deref(),
)
.await {
Ok(scheduled_token_opt) => scheduled_token_opt,
Err(e) => {
logger::error!(
error = ?e,
connector_customer_id = %connector_customer_id,
"Failed to get PSP token status"
);
None
}
};
match scheduled_token {
Some(scheduled_token) => {
let response = revenue_recovery_core::api::call_proxy_api(
state,
payment_intent,
revenue_recovery_payment_data,
revenue_recovery_metadata,
&scheduled_token
.payment_processor_token_details
.payment_processor_token,
)
.await;
let recovery_payment_intent =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(
payment_intent,
);
// handle proxy api's response
match response {
Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() {
RevenueRecoveryPaymentsAttemptStatus::Succeeded => {
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_data.payment_attempt,
);
let recovery_payment_tuple =
recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
let is_hard_decline = revenue_recovery::check_hard_decline(
state,
&payment_data.payment_attempt,
)
.await
.ok();
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
&is_hard_decline,
Some(&scheduled_token.payment_processor_token_details.payment_processor_token),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
Ok(Self::SuccessfulPayment(
payment_data.payment_attempt.clone(),
))
}
RevenueRecoveryPaymentsAttemptStatus::Failed => {
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_data.payment_attempt,
);
let recovery_payment_tuple =
recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
let error_code = payment_data
.payment_attempt
.clone()
.error
.map(|error| error.code);
let is_hard_decline = revenue_recovery::check_hard_decline(
state,
&payment_data.payment_attempt,
)
.await
.ok();
let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
Some(&scheduled_token
.payment_processor_token_details
.payment_processor_token)
,
)
.await;
// unlocking the token
let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
reopen_calculate_workflow_on_payment_failure(
state,
process,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
)
.await?;
// Return terminal failure to finish the current execute workflow
Ok(Self::TerminalFailure(payment_data.payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::Processing => {
Ok(Self::SyncPayment(payment_data.payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {
logger::info!(?action, "Invalid Payment Status For PCR Payment");
Ok(Self::ManualReviewAction)
}
},
Err(err) =>
// check for an active attempt being constructed or not
{
logger::error!(execute_payment_res=?err);
Ok(Self::ReviewPayment)
}
}
}
None => {
let response = revenue_recovery_core::api::call_psync_api(
state,
payment_intent.get_id(),
revenue_recovery_payment_data,
)
.await;
let payment_status_data = response
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = payment_status_data.payment_attempt;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"No token available, finishing CALCULATE_WORKFLOW"
);
state
.store
.as_scheduler()
.finish_process_with_business_status(
process.clone(),
business_status::CALCULATE_WORKFLOW_FINISH,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to finish CALCULATE_WORKFLOW")?;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"CALCULATE_WORKFLOW finished successfully"
);
Ok(Self::TerminalFailure(payment_attempt.clone()))
}
}
}
|
crates/router/src/core/revenue_recovery/types.rs
|
router
|
function_signature
| 1,639
|
rust
| null | null | null | null |
execute_payment
| null | null | null | null | null | null | null |
pub struct EnabledServices {
pub merchant_presented_qr: String,
}
|
crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 16
|
rust
|
EnabledServices
| null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentsCompleteAuthorize for Breadpay {}
|
crates/hyperswitch_connectors/src/connectors/breadpay.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Breadpay
|
api::PaymentsCompleteAuthorize for
|
impl api::PaymentsCompleteAuthorize for for Breadpay
| null | null | null | null | null | null | null | null |
pub async fn start_drainer(
stores: HashMap<id_type::TenantId, Arc<Store>>,
conf: DrainerSettings,
) -> errors::DrainerResult<()> {
let drainer_handler = handler::Handler::from_conf(conf, stores);
let (tx, rx) = mpsc::channel::<()>(1);
let signal = get_allowed_signals().change_context(errors::DrainerError::SignalError(
"Failed while getting allowed signals".to_string(),
))?;
let handle = signal.handle();
let task_handle =
tokio::spawn(common_utils::signals::signal_handler(signal, tx.clone()).in_current_span());
let handler_clone = drainer_handler.clone();
tokio::task::spawn(async move { handler_clone.shutdown_listener(rx).await });
drainer_handler.spawn_error_handlers(tx)?;
drainer_handler.spawn().await?;
handle.close();
let _ = task_handle
.await
.map_err(|err| logger::error!("Failed while joining signal handler: {:?}", err));
Ok(())
}
|
crates/drainer/src/lib.rs
|
drainer
|
function_signature
| 221
|
rust
| null | null | null | null |
start_drainer
| null | null | null | null | null | null | null |
File: crates/api_models/src/poll.rs
Public structs: 1
use common_utils::events::{ApiEventMetric, ApiEventsType};
use serde::Serialize;
use utoipa::ToSchema;
#[derive(Debug, ToSchema, Clone, Serialize)]
pub struct PollResponse {
/// The poll id
pub poll_id: String,
/// Status of the poll
pub status: PollStatus,
}
#[derive(Debug, strum::Display, strum::EnumString, Clone, serde::Serialize, ToSchema)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PollStatus {
Pending,
Completed,
NotFound,
}
impl ApiEventMetric for PollResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Poll {
poll_id: self.poll_id.clone(),
})
}
}
|
crates/api_models/src/poll.rs
|
api_models
|
full_file
| 193
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs
Public structs: 1
use error_stack;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
pub struct SignifydAuthType {
pub api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SignifydAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
|
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs
|
hyperswitch_connectors
|
full_file
| 176
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn do_auth_connector_call<F, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
router_data: RouterData<F, Req, Res>,
) -> RouterResult<RouterData<F, Req, Res>>
where
Req: std::fmt::Debug + Clone + 'static,
Res: std::fmt::Debug + Clone + 'static,
F: std::fmt::Debug + Clone + 'static,
dyn api::Connector + Sync: services::api::ConnectorIntegration<F, Req, Res>,
dyn api::ConnectorV2 + Sync: services::api::ConnectorIntegrationV2<F, UasFlowData, Req, Res>,
{
let connector_data =
api::AuthenticationConnectorData::get_connector_by_name(&authentication_connector_name)?;
let connector_integration: services::BoxedUnifiedAuthenticationServiceInterface<F, Req, Res> =
connector_data.connector.get_connector_integration();
let router_data = execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(router_data)
}
|
crates/router/src/core/unified_authentication_service/utils.rs
|
router
|
function_signature
| 251
|
rust
| null | null | null | null |
do_auth_connector_call
| null | null | null | null | null | null | null |
pub struct LinkTokenResponse {
pub link_token: String,
}
|
crates/pm_auth/src/types.rs
|
pm_auth
|
struct_definition
| 14
|
rust
|
LinkTokenResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct SurchargeDetails {
/// original_amount
pub original_amount: MinorUnit,
/// surcharge value
pub surcharge: common_utils::types::Surcharge,
/// tax on surcharge value
pub tax_on_surcharge:
Option<common_utils::types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>,
/// surcharge amount for this payment
pub surcharge_amount: MinorUnit,
/// tax on surcharge amount for this payment
pub tax_on_surcharge_amount: MinorUnit,
}
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
| 116
|
rust
|
SurchargeDetails
| null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentSuccessCount;
|
crates/api_models/src/analytics/payments.rs
|
api_models
|
struct_definition
| 6
|
rust
|
PaymentSuccessCount
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/types/storage/address.rs
pub use diesel_models::address::{Address, AddressNew, AddressUpdateInternal};
pub use crate::types::domain::AddressUpdate;
|
crates/router/src/types/storage/address.rs
|
router
|
full_file
| 37
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn enum_variant_value(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"enum_variant_value",
combinator::map(enum_value_string, ast::ValueType::EnumVariant),
)(input)
}
|
crates/euclid/src/frontend/ast/parser.rs
|
euclid
|
function_signature
| 53
|
rust
| null | null | null | null |
enum_variant_value
| null | null | null | null | null | null | null |
File: crates/router/tests/connectors/adyen.rs
use std::str::FromStr;
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails};
use masking::Secret;
use router::types::{self, storage::enums, PaymentAddress};
use crate::{
connector_auth,
utils::{self, ConnectorActions, PaymentInfo},
};
#[derive(Clone, Copy)]
struct AdyenTest;
impl ConnectorActions for AdyenTest {}
impl utils::Connector for AdyenTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Adyen;
utils::construct_connector_data_old(
Box::new(Adyen::new()),
types::Connector::Adyen,
types::api::GetToken::Connector,
None,
)
}
#[cfg(feature = "payouts")]
fn get_payout_data(&self) -> Option<types::api::ConnectorData> {
use router::connector::Adyen;
Some(utils::construct_connector_data_old(
Box::new(Adyen::new()),
types::Connector::Adyen,
types::api::GetToken::Connector,
None,
))
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.adyen_uk
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"adyen".to_string()
}
}
impl AdyenTest {
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
state: Some(Secret::new("California".to_string())),
city: Some("San Francisco".to_string()),
zip: Some(Secret::new("94122".to_string())),
line1: Some(Secret::new("1467".to_string())),
line2: Some(Secret::new("Harrison Street".to_string())),
line3: None,
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Dough".to_string())),
origin_zip: None,
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("9123456789".to_string())),
country_code: Some("+351".to_string()),
}),
email: None,
}),
None,
None,
)),
..Default::default()
})
}
#[cfg(feature = "payouts")]
fn get_payout_info(payout_type: enums::PayoutType) -> Option<PaymentInfo> {
use common_utils::pii::Email;
Some(PaymentInfo {
currency: Some(enums::Currency::EUR),
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
state: Some(Secret::new("California".to_string())),
city: Some("San Francisco".to_string()),
zip: Some(Secret::new("94122".to_string())),
line1: Some(Secret::new("1467".to_string())),
line2: Some(Secret::new("Harrison Street".to_string())),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
payout_method_data: match payout_type {
enums::PayoutType::Card => Some(types::api::PayoutMethodData::Card(
types::api::payouts::CardPayout {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
expiry_month: Secret::new("3".to_string()),
expiry_year: Secret::new("2030".to_string()),
card_holder_name: Some(Secret::new("John Doe".to_string())),
},
)),
enums::PayoutType::Bank => Some(types::api::PayoutMethodData::Bank(
types::api::payouts::BankPayout::Sepa(types::api::SepaBankTransfer {
iban: "NL46TEST0136169112".to_string().into(),
bic: Some("ABNANL2A".to_string().into()),
bank_name: Some("Deutsche Bank".to_string()),
bank_country_code: Some(enums::CountryAlpha2::NL),
bank_city: Some("Amsterdam".to_string()),
}),
)),
enums::PayoutType::Wallet => Some(types::api::PayoutMethodData::Wallet(
types::api::payouts::WalletPayout::Paypal(api_models::payouts::Paypal {
email: Email::from_str("[email protected]").ok(),
telephone_number: None,
paypal_id: None,
}),
)),
},
..Default::default()
})
}
fn get_payment_authorize_data(
card_number: &str,
card_exp_month: &str,
card_exp_year: &str,
card_cvc: &str,
capture_method: enums::CaptureMethod,
) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 3500,
currency: enums::Currency::USD,
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
co_badged_card_data: None,
}),
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
setup_future_usage: None,
mandate_id: None,
off_session: None,
setup_mandate_details: None,
capture_method: Some(capture_method),
browser_info: None,
order_details: None,
order_category: None,
email: None,
customer_name: None,
payment_experience: None,
payment_method_type: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
router_return_url: Some(String::from("http://localhost:8080")),
webhook_url: None,
complete_authorize_url: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: false,
metadata: None,
authentication_data: None,
customer_acceptance: None,
locale: None,
..utils::PaymentAuthorizeType::default().0
})
}
}
static CONNECTOR: AdyenTest = AdyenTest {};
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(
AdyenTest::get_payment_authorize_data(
"4111111111111111",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
AdyenTest::get_payment_info(),
)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
AdyenTest::get_payment_authorize_data(
"370000000000002",
"03",
"2030",
"7373",
enums::CaptureMethod::Manual,
),
None,
AdyenTest::get_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
AdyenTest::get_payment_authorize_data(
"4293189100000008",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
AdyenTest::get_payment_authorize_data(
"4293189100000008",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
AdyenTest::get_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
AdyenTest::get_payment_authorize_data(
"370000000000002",
"03",
"2030",
"7373",
enums::CaptureMethod::Manual,
),
None,
Some(types::RefundsData {
refund_amount: 1500,
reason: Some("CUSTOMER REQUEST".to_string()),
..utils::PaymentRefundType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
AdyenTest::get_payment_authorize_data(
"2222400070000005",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
None,
Some(types::RefundsData {
refund_amount: 1500,
reason: Some("CUSTOMER REQUEST".to_string()),
..utils::PaymentRefundType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(
AdyenTest::get_payment_authorize_data(
"2222400070000005",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(
AdyenTest::get_payment_authorize_data(
"2222400070000005",
"03",
"2030",
"737",
enums::CaptureMethod::Automatic,
),
Some(types::RefundsData {
refund_amount: 1000,
reason: Some("CUSTOMER REQUEST".to_string()),
..utils::PaymentRefundType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
AdyenTest::get_payment_authorize_data(
"4293189100000008",
"03",
"2030",
"737",
enums::CaptureMethod::Automatic,
),
Some(types::RefundsData {
refund_amount: 500,
reason: Some("CUSTOMER REQUEST".to_string()),
..utils::PaymentRefundType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
let payment_info = AdyenTest::get_payment_info();
//make a successful payment
let response = CONNECTOR
.make_payment(
AdyenTest::get_payment_authorize_data(
"2222400070000005",
"03",
"2030",
"737",
enums::CaptureMethod::Automatic,
),
payment_info.clone(),
)
.await
.unwrap();
//try refund for previous payment
let transaction_id = utils::get_connector_transaction_id(response.response).unwrap();
for _x in 0..2 {
let refund_response = CONNECTOR
.refund_payment(
transaction_id.clone(),
Some(types::RefundsData {
refund_amount: 100,
reason: Some("CUSTOMER REQUEST".to_string()),
..utils::PaymentRefundType::default().0
}),
payment_info.clone(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
}
// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
router_return_url: Some(String::from("http://localhost:8080")),
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str("4024007134364842").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(response.response.unwrap_err().message, "Refused");
}
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
router_return_url: Some(String::from("http://localhost:8080")),
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"CVC is not the right length",
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
router_return_url: Some(String::from("http://localhost:8080")),
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
let errors = ["The provided Expiry Date is not valid.: Expiry month should be between 1 and 12 inclusive: 20","Refused"];
assert!(errors.contains(&response.response.unwrap_err().message.as_str()))
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
router_return_url: Some(String::from("http://localhost:8080")),
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(response.response.unwrap_err().message, "Expired Card");
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, AdyenTest::get_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("Original pspReference required for this operation")
);
}
/******************** Payouts test cases ********************/
// Create SEPA payout
#[ignore]
#[cfg(feature = "payouts")]
#[actix_web::test]
async fn should_create_sepa_payout() {
let payout_type = enums::PayoutType::Bank;
let payout_info = AdyenTest::get_payout_info(payout_type);
let response = CONNECTOR
.create_payout(None, payout_type, payout_info)
.await
.expect("Payout bank creation response");
assert_eq!(
response.status.unwrap(),
enums::PayoutStatus::RequiresFulfillment
);
}
// Create and fulfill SEPA payout
#[ignore]
#[cfg(feature = "payouts")]
#[actix_web::test]
async fn should_create_and_fulfill_sepa_payout() {
let payout_type = enums::PayoutType::Bank;
let payout_info = AdyenTest::get_payout_info(payout_type);
let response = CONNECTOR
.create_and_fulfill_payout(None, payout_type, payout_info)
.await
.expect("Payout bank creation and fulfill response");
assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success);
}
// Verifies if card is eligible for payout
#[ignore]
#[cfg(feature = "payouts")]
#[actix_web::test]
async fn should_verify_payout_eligibility() {
let payout_type = enums::PayoutType::Card;
let payout_info = AdyenTest::get_payout_info(payout_type);
let response = CONNECTOR
.verify_payout_eligibility(payout_type, payout_info)
.await
.expect("Payout eligibility response");
assert_eq!(
response.status.unwrap(),
enums::PayoutStatus::RequiresFulfillment
);
}
// Fulfills card payout
#[ignore]
#[cfg(feature = "payouts")]
#[actix_web::test]
async fn should_fulfill_card_payout() {
let payout_type = enums::PayoutType::Card;
let payout_info: Option<PaymentInfo> = AdyenTest::get_payout_info(payout_type);
let response = CONNECTOR
.fulfill_payout(None, payout_type, payout_info)
.await
.expect("Payout fulfill response");
assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success);
}
// Cancels a created bank payout
#[ignore]
#[cfg(feature = "payouts")]
#[actix_web::test]
async fn should_create_and_cancel_created_payout() {
let payout_type = enums::PayoutType::Bank;
let payout_info = AdyenTest::get_payout_info(payout_type);
let response = CONNECTOR
.create_and_cancel_payout(None, payout_type, payout_info)
.await
.expect("Payout cancel response");
assert_eq!(response.status.unwrap(), enums::PayoutStatus::Cancelled);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/adyen.rs
|
router
|
full_file
| 4,955
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
zip: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
}
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 65
|
rust
|
BillTo
| null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorAccessToken for Plaid {}
|
crates/hyperswitch_connectors/src/connectors/plaid.rs
|
hyperswitch_connectors
|
impl_block
| 7
|
rust
| null |
Plaid
|
ConnectorAccessToken for
|
impl ConnectorAccessToken for for Plaid
| null | null | null | null | null | null | null | null |
impl ConnectorSpecifications for Recurly {}
|
crates/hyperswitch_connectors/src/connectors/recurly.rs
|
hyperswitch_connectors
|
impl_block
| 8
|
rust
| null |
Recurly
|
ConnectorSpecifications for
|
impl ConnectorSpecifications for for Recurly
| null | null | null | null | null | null | null | null |
pub async fn make_connector_decision(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
match connector_call_type {
api::ConnectorCallType::PreDetermined(routing_data) => {
Box::pin(call_connector_payout(
state,
merchant_context,
&routing_data.connector_data,
payout_data,
))
.await?;
#[cfg(feature = "payout_retry")]
{
let config_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_context.get_merchant_account().get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if config_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_single_connector_actions(
state,
routing_data.connector_data,
payout_data,
merchant_context,
))
.await?;
}
}
Ok(())
}
api::ConnectorCallType::Retryable(routing_data) => {
let mut routing_data = routing_data.into_iter();
let connector_data = get_next_connector(&mut routing_data)?.connector_data;
Box::pin(call_connector_payout(
state,
merchant_context,
&connector_data,
payout_data,
))
.await?;
#[cfg(feature = "payout_retry")]
{
let config_multiple_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_context.get_merchant_account().get_id(),
PayoutRetryType::MultiConnector,
)
.await;
if config_multiple_connector_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_multiple_connector_actions(
state,
routing_data,
connector_data.clone(),
payout_data,
merchant_context,
))
.await?;
}
let config_single_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_context.get_merchant_account().get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if config_single_connector_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_single_connector_actions(
state,
connector_data,
payout_data,
merchant_context,
))
.await?;
}
}
Ok(())
}
_ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable({
"only PreDetermined and Retryable ConnectorCallTypes are supported".to_string()
})?,
}
}
|
crates/router/src/core/payouts.rs
|
router
|
function_signature
| 562
|
rust
| null | null | null | null |
make_connector_decision
| null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.FrmPaymentMethod
{
"type": "object",
"description": "Details of FrmPaymentMethod are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table",
"required": [
"payment_method"
],
"properties": {
"payment_method": {
"$ref": "#/components/schemas/PaymentMethod"
},
"payment_method_types": {
"type": "array",
"items": {
"$ref": "#/components/schemas/FrmPaymentMethodType"
},
"description": "payment method types(credit, debit) that can be used in the payment. This field is deprecated. It has not been removed to provide backward compatibility.",
"nullable": true
},
"flow": {
"allOf": [
{
"$ref": "#/components/schemas/FrmPreferredFlowTypes"
}
],
"nullable": true
}
},
"additionalProperties": false
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 221
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"FrmPaymentMethod"
] | null | null | null | null |
impl api::UasAuthenticationConfirmation for UnifiedAuthenticationService {}
|
crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs
|
hyperswitch_connectors
|
impl_block
| 12
|
rust
| null |
UnifiedAuthenticationService
|
api::UasAuthenticationConfirmation for
|
impl api::UasAuthenticationConfirmation for for UnifiedAuthenticationService
| null | null | null | null | null | null | null | null |
pub struct WellsfargopayoutAuthType {
pub(super) api_key: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 21
|
rust
|
WellsfargopayoutAuthType
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.PaymentMethodDataResponseWithBilling
{
"allOf": [
{
"allOf": [
{
"$ref": "#/components/schemas/PaymentMethodDataResponse"
}
],
"nullable": true
},
{
"type": "object",
"properties": {
"billing": {
"allOf": [
{
"$ref": "#/components/schemas/Address"
}
],
"nullable": true
}
}
}
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 117
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"PaymentMethodDataResponseWithBilling"
] | null | null | null | null |
pub struct ErrorParameters {
pub(super) name: String,
pub(super) value: Option<String>,
pub(super) message: String,
}
|
crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 31
|
rust
|
ErrorParameters
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
(
"payment_method_type",
router_data
.request
.payment_method_type
.map(|inner| inner.to_string())
.unwrap_or("null".to_string()),
),
),
);
let mut authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response.clone(),
);
if connector.connector_name == api_models::enums::Connector::Airwallex {
authorize_router_data.reference_id = resp.reference_id;
} else if connector.connector_name == api_models::enums::Connector::Nuvei {
let (enrolled_for_3ds, related_transaction_id) = match &authorize_router_data.response {
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse {
enrolled_v2,
related_transaction_id,
}) => (*enrolled_v2, related_transaction_id.clone()),
_ => (false, None),
};
authorize_router_data.request.enrolled_for_3ds = enrolled_for_3ds;
authorize_router_data.request.related_transaction_id = related_transaction_id;
} else if connector.connector_name == api_models::enums::Connector::Shift4 {
if resp.request.enrolled_for_3ds {
authorize_router_data.response = resp.response;
authorize_router_data.status = resp.status;
} else {
authorize_router_data.request.enrolled_for_3ds = false;
}
}
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
|
crates/router/src/core/payments/flows/authorize_flow.rs
|
router
|
function_signature
| 643
|
rust
| null | null | null | null |
authorize_preprocessing_steps
| null | null | null | null | null | null | null |
pub struct RefundResponse {
id: String,
status: DummyRefundStatus,
currency: Currency,
created: String,
payment_amount: MinorUnit,
refund_amount: MinorUnit,
}
|
crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 44
|
rust
|
RefundResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_filters_for_disputes(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
) -> RouterResponse<api_models::disputes::DisputeListFilters> {
let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
super::admin::list_payment_connectors(
state,
merchant_context.get_merchant_account().get_id().to_owned(),
profile_id_list,
)
.await?
{
data
} else {
return Err(error_stack::report!(
errors::ApiErrorResponse::InternalServerError
))
.attach_printable(
"Failed to retrieve merchant connector accounts while fetching dispute list filters.",
);
};
let connector_map = merchant_connector_accounts
.into_iter()
.filter_map(|merchant_connector_account| {
merchant_connector_account
.connector_label
.clone()
.map(|label| {
let info = merchant_connector_account.to_merchant_connector_info(&label);
(merchant_connector_account.connector_name, info)
})
})
.fold(
HashMap::new(),
|mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| {
map.entry(connector_name).or_default().push(info);
map
},
);
Ok(services::ApplicationResponse::Json(
api_models::disputes::DisputeListFilters {
connector: connector_map,
currency: storage_enums::Currency::iter().collect(),
dispute_status: storage_enums::DisputeStatus::iter().collect(),
dispute_stage: storage_enums::DisputeStage::iter().collect(),
},
))
}
|
crates/router/src/core/disputes.rs
|
router
|
function_signature
| 369
|
rust
| null | null | null | null |
get_filters_for_disputes
| null | null | null | null | null | null | null |
pub async fn find_by_publishable_key(
conn: &PgPooledConn,
publishable_key: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::publishable_key.eq(publishable_key.to_owned()),
)
.await
}
|
crates/diesel_models/src/query/merchant_account.rs
|
diesel_models
|
function_signature
| 78
|
rust
| null | null | null | null |
find_by_publishable_key
| null | null | null | null | null | null | null |
Documentation: api-reference/v1/api-key/api-key--revoke.mdx
# Type: Doc File
---
openapi: delete /api_keys/{merchant_id}/{key_id}
---
|
api-reference/v1/api-key/api-key--revoke.mdx
| null |
doc_file
| 38
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn list_merchants_for_user_in_org(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::ListMerchantsForUserInOrg;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user_from_token, _, _| {
user_core::list_merchants_for_user_in_org(state, user_from_token)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| 125
|
rust
| null | null | null | null |
list_merchants_for_user_in_org
| null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/dummyconnector.rs
Public functions: 1
Public structs: 1
pub mod transformers;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType};
use common_utils::{
consts as common_consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session,
SetupMandate, Void,
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
ConnectorSpecifications, ConnectorValidation, MandateSetup, Payment, PaymentAuthorize,
PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund,
RefundExecute, RefundSync,
},
configs::Connectors,
errors::ConnectorError,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType,
RefundSyncType, Response,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask as _, Maskable};
use transformers as dummyconnector;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{construct_not_supported_error_report, convert_amount, RefundsRequestData as _},
};
#[derive(Clone)]
pub struct DummyConnector<const T: u8> {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl<const T: u8> DummyConnector<T> {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl<const T: u8> Payment for DummyConnector<T> {}
impl<const T: u8> PaymentSession for DummyConnector<T> {}
impl<const T: u8> ConnectorAccessToken for DummyConnector<T> {}
impl<const T: u8> MandateSetup for DummyConnector<T> {}
impl<const T: u8> PaymentAuthorize for DummyConnector<T> {}
impl<const T: u8> PaymentSync for DummyConnector<T> {}
impl<const T: u8> PaymentCapture for DummyConnector<T> {}
impl<const T: u8> PaymentVoid for DummyConnector<T> {}
impl<const T: u8> Refund for DummyConnector<T> {}
impl<const T: u8> RefundExecute for DummyConnector<T> {}
impl<const T: u8> RefundSync for DummyConnector<T> {}
impl<const T: u8> PaymentToken for DummyConnector<T> {}
impl<const T: u8>
ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for DummyConnector<T>
{
// Not Implemented (R)
}
impl<const T: u8, Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response>
for DummyConnector<T>
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
),
(
common_consts::TENANT_HEADER.to_string(),
req.tenant_id.get_string_repr().to_string().into(),
),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl<const T: u8> ConnectorCommon for DummyConnector<T> {
fn id(&self) -> &'static str {
Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id()
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.dummyconnector.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let auth = transformers::DummyConnectorAuthType::try_from(auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: transformers::DummyConnectorErrorResponse = res
.response
.parse_struct("DummyConnectorErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code,
message: response.error.message,
reason: response.error.reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl<const T: u8> ConnectorValidation for DummyConnector<T> {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<CaptureMethod>,
_payment_method: PaymentMethod,
_pmt: Option<PaymentMethodType>,
) -> CustomResult<(), ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
CaptureMethod::Automatic
| CaptureMethod::Manual
| CaptureMethod::SequentialAutomatic => Ok(()),
CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => Err(
construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
impl<const T: u8> ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>
for DummyConnector<T>
{
//TODO: implement sessions flow
}
impl<const T: u8> ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for DummyConnector<T>
{
}
impl<const T: u8> ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for DummyConnector<T>
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Err(
ConnectorError::NotImplemented("Setup Mandate flow for DummyConnector".to_string())
.into(),
)
}
}
impl<const T: u8> ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for DummyConnector<T>
{
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
match req.payment_method {
PaymentMethod::Card
| PaymentMethod::Upi
| PaymentMethod::Wallet
| PaymentMethod::PayLater => Ok(format!("{}/payment", self.base_url(connectors))),
_ => Err(error_stack::report!(ConnectorError::NotSupported {
message: format!("The payment method {} is not supported", req.payment_method),
connector: Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id(),
})),
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = dummyconnector::DummyConnectorRouterData::from((amount, req));
let connector_req =
transformers::DummyConnectorPaymentsRequest::<T>::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> {
let response: transformers::PaymentsResponse = res
.response
.parse_struct("DummyConnector PaymentsResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl<const T: u8> ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>
for DummyConnector<T>
{
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
match req
.request
.connector_transaction_id
.get_connector_transaction_id()
{
Ok(transaction_id) => Ok(format!(
"{}/payments/{}",
self.base_url(connectors),
transaction_id
)),
Err(_) => Err(error_stack::report!(
ConnectorError::MissingConnectorTransactionID
)),
}
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, ConnectorError> {
let response: transformers::PaymentsResponse = res
.response
.parse_struct("dummyconnector PaymentsSyncResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl<const T: u8> ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>
for DummyConnector<T>
{
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Err(ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
Err(ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, ConnectorError> {
let response: transformers::PaymentsResponse = res
.response
.parse_struct("transformers PaymentsCaptureResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl<const T: u8> ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>
for DummyConnector<T>
{
}
impl<const T: u8> ConnectorIntegration<Execute, RefundsData, RefundsResponseData>
for DummyConnector<T>
{
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}/{}/refund",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = dummyconnector::DummyConnectorRouterData::from((amount, req));
let connector_req =
transformers::DummyConnectorRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, ConnectorError> {
let response: transformers::RefundResponse = res
.response
.parse_struct("transformers RefundResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl<const T: u8> ConnectorIntegration<RSync, RefundsData, RefundsResponseData>
for DummyConnector<T>
{
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/refunds/{}",
self.base_url(connectors),
refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, ConnectorError> {
let response: transformers::RefundResponse = res
.response
.parse_struct("transformers RefundSyncResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl<const T: u8> IncomingWebhook for DummyConnector<T> {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
impl<const T: u8> ConnectorSpecifications for DummyConnector<T> {}
|
crates/hyperswitch_connectors/src/connectors/dummyconnector.rs
|
hyperswitch_connectors
|
full_file
| 4,793
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentSession for Wise {}
|
crates/hyperswitch_connectors/src/connectors/wise.rs
|
hyperswitch_connectors
|
impl_block
| 8
|
rust
| null |
Wise
|
api::PaymentSession for
|
impl api::PaymentSession for for Wise
| null | null | null | null | null | null | null | null |
pub struct ApiKeyAuth {
pub is_connected_allowed: bool,
pub is_platform_allowed: bool,
}
|
crates/router/src/services/authentication.rs
|
router
|
struct_definition
| 23
|
rust
|
ApiKeyAuth
| null | null | null | null | null | null | null | null | null | null | null |
pub struct GlobalPayRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
|
crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
| 25
|
rust
|
GlobalPayRouterData
| null | null | null | null | null | null | null | null | null | null | null |
pub struct BusinessPaymentLinkConfig {
/// Custom domain name to be used for hosting the link in your own domain
pub domain_name: Option<String>,
/// Default payment link config for all future payment link
#[serde(flatten)]
#[schema(value_type = PaymentLinkConfigRequest)]
pub default_config: Option<PaymentLinkConfigRequest>,
/// list of configs for multi theme setup
pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>,
/// A list of allowed domains (glob patterns) where this link can be embedded / opened from
#[schema(value_type = Option<HashSet<String>>)]
pub allowed_domains: Option<HashSet<String>>,
/// Toggle for HyperSwitch branding visibility
pub branding_visibility: Option<bool>,
}
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
| 159
|
rust
|
BusinessPaymentLinkConfig
| null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentVoid for Payload {}
|
crates/hyperswitch_connectors/src/connectors/payload.rs
|
hyperswitch_connectors
|
impl_block
| 8
|
rust
| null |
Payload
|
api::PaymentVoid for
|
impl api::PaymentVoid for for Payload
| null | null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.