text
stringlengths 65
57.3k
| file_path
stringlengths 22
92
| module
stringclasses 38
values | type
stringclasses 7
values | struct_name
stringlengths 3
60
⌀ | impl_count
int64 0
60
⌀ | traits
listlengths 0
59
⌀ | tokens
int64 16
8.19k
| function_name
stringlengths 3
85
⌀ | type_name
stringlengths 1
67
⌀ | trait_name
stringclasses 573
values | method_count
int64 0
31
⌀ | public_method_count
int64 0
19
⌀ | submodule_count
int64 0
56
⌀ | export_count
int64 0
9
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Struct: PaytmPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaytmPaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaytmPaymentsResponse
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Square
// File: crates/hyperswitch_connectors/src/connectors/square.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Square
|
crates/hyperswitch_connectors/src/connectors/square.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Square
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Implementation: impl Bluecode
// File: crates/hyperswitch_connectors/src/connectors/bluecode.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl Bluecode
|
crates/hyperswitch_connectors/src/connectors/bluecode.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 45
| null |
Bluecode
| null | 1
| 1
| null | null |
// Function: get_user_theme_using_theme_id
// File: crates/router/src/routes/user/theme.rs
// Module: router
pub fn get_user_theme_using_theme_id(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse
|
crates/router/src/routes/user/theme.rs
|
router
|
function_signature
| null | null | null | 60
|
get_user_theme_using_theme_id
| null | null | null | null | null | null |
// Function: find_resources
// File: crates/storage_impl/src/lib.rs
// Module: storage_impl
pub fn find_resources<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
execute_query: R,
) -> error_stack::Result<Vec<D>, StorageError>
where
D: Debug + Sync + Conversion,
R: futures::Future<
Output = error_stack::Result<Vec<M>, diesel_models::errors::DatabaseError>,
> + Send,
M: ReverseConversion<D>,
|
crates/storage_impl/src/lib.rs
|
storage_impl
|
function_signature
| null | null | null | 121
|
find_resources
| null | null | null | null | null | null |
// Struct: KlarnaSdkResponse
// File: crates/hyperswitch_domain_models/src/router_data.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct KlarnaSdkResponse
|
crates/hyperswitch_domain_models/src/router_data.rs
|
hyperswitch_domain_models
|
struct_definition
|
KlarnaSdkResponse
| 0
|
[] | 44
| null | null | null | null | null | null | null |
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 {
match &self.domain_customer.address_id {
Some(address_id) => Some(
db.find_address_by_address_id(
self.key_manager_state,
address_id,
self.key_store,
)
.await
.switch()?,
),
None => None,
}
};
Ok(address)
}
}
#[cfg(feature = "v1")]
#[derive(Debug)]
struct VerifyIdForUpdateCustomer<'a> {
merchant_reference_id: &'a id_type::CustomerId,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
}
#[cfg(feature = "v2")]
#[derive(Debug)]
struct VerifyIdForUpdateCustomer<'a> {
id: &'a id_type::GlobalCustomerId,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
}
#[cfg(feature = "v1")]
impl VerifyIdForUpdateCustomer<'_> {
async fn verify_id_and_get_customer_object(
&self,
db: &dyn StorageInterface,
) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> {
let customer = db
.find_customer_by_customer_id_merchant_id(
self.key_manager_state,
self.merchant_reference_id,
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
)
.await
.switch()?;
Ok(customer)
}
}
#[cfg(feature = "v2")]
impl VerifyIdForUpdateCustomer<'_> {
async fn verify_id_and_get_customer_object(
&self,
db: &dyn StorageInterface,
) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> {
let customer = db
.find_customer_by_global_id(
self.key_manager_state,
self.id,
self.key_store,
self.merchant_account.storage_scheme,
)
.await
.switch()?;
Ok(customer)
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
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> {
let update_address_for_update_customer = AddressStructForDbUpdate {
update_customer: self,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
state,
domain_customer,
};
let address = update_address_for_update_customer
.update_address_if_sent(db)
.await?;
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
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
.as_ref()
.map(|a| a.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()?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
let response = db
.update_customer_by_customer_id_merchant_id(
key_manager_state,
domain_customer.customer_id.to_owned(),
merchant_context.get_merchant_account().get_id().to_owned(),
domain_customer.to_owned(),
storage::CustomerUpdate::Update {
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: Box::new(encryptable_customer.phone),
tax_registration_id: encryptable_customer.tax_registration_id,
phone_country_code: self.phone_country_code.clone(),
metadata: Box::new(self.metadata.clone()),
description: self.description.clone(),
connector_customer: Box::new(None),
address_id: address.clone().map(|addr| addr.address_id),
},
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
Ok(response)
}
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 CustomerUpdateBridge for customers::CustomerUpdateRequest {
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> {
let default_billing_address = self.get_default_customer_billing_address();
let encrypted_customer_billing_address = default_billing_address
.async_map(|billing_address| {
create_encrypted_data(
key_manager_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_shipping_address = self.get_default_customer_shipping_address();
let encrypted_customer_shipping_address = default_shipping_address
.async_map(|shipping_address| {
create_encrypted_data(
key_manager_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 key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
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
.as_ref()
.map(|a| a.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()?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
let response = db
.update_customer_by_global_id(
key_manager_state,
&domain_customer.id,
domain_customer.to_owned(),
storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate {
name: encryptable_customer.name,
email: Box::new(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: Box::new(encryptable_customer.phone),
tax_registration_id: encryptable_customer.tax_registration_id,
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
description: self.description.clone(),
connector_customer: Box::new(None),
default_billing_address: encrypted_customer_billing_address.map(Into::into),
default_shipping_address: encrypted_customer_shipping_address.map(Into::into),
default_payment_method_id: Some(self.default_payment_method_id.clone()),
status: None,
})),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
Ok(response)
}
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse> {
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from(customer.clone()),
))
}
}
pub async fn migrate_customers(
state: SessionState,
customers_migration: Vec<payment_methods_domain::PaymentMethodCustomerMigrate>,
merchant_context: domain::MerchantContext,
) -> errors::CustomerResponse<()> {
for customer_migration in customers_migration {
match create_customer(
state.clone(),
merchant_context.clone(),
customer_migration.customer,
customer_migration.connector_customer_details,
)
.await
{
Ok(_) => (),
Err(e) => match e.current_context() {
errors::CustomersErrorResponse::CustomerAlreadyExists => (),
_ => return Err(e),
},
}
}
Ok(services::ApplicationResponse::Json(()))
}
|
crates/router/src/core/customers.rs#chunk1
|
router
|
chunk
| null | null | null | 2,355
| null | null | null | null | null | null | null |
// File: crates/openapi/src/routes/payment_method.rs
// Module: openapi
// Public functions: 23
/// PaymentMethods - Create
///
/// Creates and stores a payment method against a customer.
/// In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/payment_methods",
request_body (
content = PaymentMethodCreate,
examples (( "Save a card" =(
value =json!( {
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4242424242424242",
"card_exp_month": "11",
"card_exp_year": "25",
"card_holder_name": "John Doe"
},
"customer_id": "{{customer_id}}"
})
)))
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data")
),
tag = "Payment Methods",
operation_id = "Create a Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn create_payment_method_api() {}
/// List payment methods for a Merchant
///
/// Lists the applicable payment methods for a particular Merchant ID.
/// Use the client secret and publishable key authorization to list all relevant payment methods of the merchant for the payment corresponding to the client secret.
#[utoipa::path(
get,
path = "/account/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = PaymentMethodListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Merchant",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn list_payment_method_api() {}
/// List payment methods for a Customer
///
/// Lists all the applicable payment methods for a particular Customer ID.
#[utoipa::path(
get,
path = "/customers/{customer_id}/payment_methods",
params (
("customer_id" = String, Path, description = "The unique identifier for the customer account"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn list_customer_payment_method_api() {}
/// List customer saved payment methods for a Payment
///
/// Lists all the applicable payment methods for a particular payment tied to the `client_secret`.
#[utoipa::path(
get,
path = "/customers/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List Customer Payment Methods via Client Secret",
security(("publishable_key" = []))
)]
pub async fn list_customer_payment_method_api_client() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Retrieve a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
/// This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.
#[utoipa::path(
post,
path = "/payment_methods/{method_id}/update",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
request_body = PaymentMethodUpdate,
responses(
(status = 200, description = "Payment Method updated", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Update a Payment method",
security(("api_key" = []), ("publishable_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method deleted", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Delete a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Set Default Payment Method for Customer
///
/// Set the Payment Method as Default for the Customer.
#[utoipa::path(
post,
path = "/{customer_id}/payment_methods/{payment_method_id}/default",
params (
("customer_id" = String,Path, description ="The unique identifier for the Customer"),
("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
(status = 400, description = "Payment Method has already been set as default for that customer"),
(status = 404, description = "Payment Method not found for the customer")
),
tag = "Payment Methods",
operation_id = "Set the Payment Method as Default",
security(("ephemeral_key" = []))
)]
pub async fn default_payment_method_set_api() {}
/// Payment Method - Create Intent
///
/// Creates a payment method for customer with billing information and other metadata.
#[utoipa::path(
post,
path = "/v2/payment-methods/create-intent",
request_body(
content = PaymentMethodIntentCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_intent_api() {}
/// Payment Method - Confirm Intent
///
/// Update a payment method with customer's payment method related information.
#[utoipa::path(
post,
path = "/v2/payment-methods/{id}/confirm-intent",
request_body(
content = PaymentMethodIntentConfirm,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Confirmed", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Confirm Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn confirm_payment_method_intent_api() {}
/// Payment Method - Create
///
/// Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/v2/payment-methods",
request_body(
content = PaymentMethodCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_api() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Retrieve Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
#[utoipa::path(
patch,
path = "/v2/payment-methods/{id}/update-saved-payment-method",
request_body(
content = PaymentMethodUpdate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Update", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Update Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Delete Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_delete_api() {}
/// Payment Method - List Customer Saved Payment Methods
///
/// List the payment methods saved for a customer
#[utoipa::path(
get,
path = "/v2/customers/{id}/saved-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the customer"),
),
responses(
(status = 200, description = "Payment Methods Retrieved", body = CustomerPaymentMethodsListResponse),
(status = 404, description = "Customer Not Found"),
),
tag = "Payment Methods",
operation_id = "List Customer Saved Payment Methods",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn list_customer_payment_method_api() {}
/// Payment Method Session - Create
///
/// Create a payment method session for a customer
/// This is used to list the saved payment methods for the customer
/// The customer can also add a new payment method using this session
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/payment-method-sessions",
request_body(
content = PaymentMethodSessionRequest,
examples (( "Create a payment method session with customer_id" = (
value =json!( {
"customer_id": "12345_cus_abcdefghijklmnopqrstuvwxyz"
})
)))
),
responses(
(status = 200, description = "Create the payment method session", body = PaymentMethodSessionResponse),
(status = 400, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Create a payment method session",
security(("api_key" = []))
)]
pub fn payment_method_session_create() {}
/// Payment Method Session - Retrieve
///
/// Retrieve the payment method session
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodSessionResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Retrieve the payment method session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_retrieve() {}
/// Payment Method Session - List Payment Methods
///
/// List payment methods for the given payment method session.
/// This endpoint lists the enabled payment methods for the profile and the saved payment methods of the customer.
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}/list-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponseForSession),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "List Payment methods for a Payment Method Session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_list_payment_methods() {}
/// Payment Method Session - Update a saved payment method
///
/// Update a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/payment-method-sessions/{id}/update-saved-payment-method",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionUpdateSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
"payment_method_data": {
"card": {
"card_holder_name": "Narayan Bhat"
}
}
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Update a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_update_saved_payment_method() {}
/// Payment Method Session - Delete a saved payment method
///
/// Delete a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionDeleteSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodDeleteResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Delete a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_delete_saved_payment_method() {}
/// Card network tokenization - Create using raw card data
///
/// Create a card network token for a customer and store it as a payment method.
/// This API expects raw card details for creating a network token with the card networks.
#[utoipa::path(
post,
path = "/payment_methods/tokenize-card",
request_body = CardNetworkTokenizeRequest,
responses(
(status = 200, description = "Payment Method Created", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_api() {}
/// Card network tokenization - Create using existing payment method
///
/// Create a card network token for a customer for an existing payment method.
/// This API expects an existing payment method ID for a card.
#[utoipa::path(
post,
path = "/payment_methods/{id}/tokenize-card",
request_body = CardNetworkTokenizeRequest,
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Updated", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token using Payment Method ID",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_using_pm_api() {}
/// Payment Method Session - Confirm a payment method session
///
/// **Confirms a payment method session object with the payment method data**
#[utoipa::path(
post,
path = "/v2/payment-method-sessions/{id}/confirm",
params (("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentMethodSessionConfirmRequest,
examples(
(
"Confirm the payment method session with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment Method created", body = PaymentMethodResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payment Method Session",
operation_id = "Confirm the payment method session",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payment_method_session_confirm() {}
|
crates/openapi/src/routes/payment_method.rs
|
openapi
|
full_file
| null | null | null | 5,090
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Paystack
// File: crates/hyperswitch_connectors/src/connectors/paystack.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Paystack
|
crates/hyperswitch_connectors/src/connectors/paystack.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Paystack
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Function: from_store
// File: crates/storage_impl/src/kv_router_store.rs
// Module: storage_impl
pub fn from_store(
store: RouterStore<T>,
drainer_stream_name: String,
drainer_num_partitions: u8,
ttl_for_kv: u32,
soft_kill: Option<bool>,
) -> Self
|
crates/storage_impl/src/kv_router_store.rs
|
storage_impl
|
function_signature
| null | null | null | 74
|
from_store
| null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/payments.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// Function: call_to_vault
// File: crates/router/src/core/payment_methods/vault.rs
// Module: router
pub fn call_to_vault<V: pm_types::VaultingInterface>(
state: &routes::SessionState,
payload: Vec<u8>,
) -> CustomResult<String, errors::VaultError>
|
crates/router/src/core/payment_methods/vault.rs
|
router
|
function_signature
| null | null | null | 68
|
call_to_vault
| null | null | null | null | null | null |
// Implementation: impl Deref for for CardExpirationMonth
// File: crates/cards/src/lib.rs
// Module: cards
// Methods: 1 total (0 public)
impl Deref for for CardExpirationMonth
|
crates/cards/src/lib.rs
|
cards
|
impl_block
| null | null | null | 44
| null |
CardExpirationMonth
|
Deref for
| 1
| 0
| null | null |
// Implementation: impl RoutableConnectorChoiceWithStatus
// File: crates/api_models/src/routing.rs
// Module: api_models
// Methods: 1 total (1 public)
impl RoutableConnectorChoiceWithStatus
|
crates/api_models/src/routing.rs
|
api_models
|
impl_block
| null | null | null | 45
| null |
RoutableConnectorChoiceWithStatus
| null | 1
| 1
| null | null |
// Function: create_merchant_account
// File: crates/router/src/core/user.rs
// Module: router
pub fn create_merchant_account(
state: SessionState,
user_from_token: auth::UserFromToken,
req: user_api::UserMerchantCreate,
) -> UserResponse<user_api::UserMerchantAccountResponse>
|
crates/router/src/core/user.rs
|
router
|
function_signature
| null | null | null | 70
|
create_merchant_account
| null | null | null | null | null | null |
// Struct: HelcimInvoice
// File: crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct HelcimInvoice
|
crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
HelcimInvoice
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: retrieve_apple_pay_verified_domains
// File: crates/router/src/routes/verification.rs
// Module: router
pub fn retrieve_apple_pay_verified_domains(
state: web::Data<AppState>,
req: HttpRequest,
params: web::Query<verifications::ApplepayGetVerifiedDomainsParam>,
) -> impl Responder
|
crates/router/src/routes/verification.rs
|
router
|
function_signature
| null | null | null | 71
|
retrieve_apple_pay_verified_domains
| null | null | null | null | null | null |
// Struct: CeleroCard
// File: crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CeleroCard
|
crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CeleroCard
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Function: get_refund_metrics
// File: crates/analytics/src/lib.rs
// Module: analytics
pub fn get_refund_metrics(
&self,
metric: &RefundMetrics,
dimensions: &[RefundDimensions],
auth: &AuthInfo,
filters: &RefundFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
) -> types::MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>
|
crates/analytics/src/lib.rs
|
analytics
|
function_signature
| null | null | null | 102
|
get_refund_metrics
| null | null | null | null | null | null |
// Implementation: impl ConnectorAccessToken for for Signifyd
// File: crates/hyperswitch_connectors/src/connectors/signifyd.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorAccessToken for for Signifyd
|
crates/hyperswitch_connectors/src/connectors/signifyd.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 56
| null |
Signifyd
|
ConnectorAccessToken for
| 0
| 0
| null | null |
// Function: delete_conditional_config
// File: crates/router/src/core/conditional_config.rs
// Module: router
pub fn delete_conditional_config(
_state: SessionState,
_merchant_context: domain::MerchantContext,
) -> RouterResponse<()>
|
crates/router/src/core/conditional_config.rs
|
router
|
function_signature
| null | null | null | 54
|
delete_conditional_config
| null | null | null | null | null | null |
// Struct: Cards3DSRequest
// File: crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Cards3DSRequest
|
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Cards3DSRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: SubmitEvidenceRequest
// File: crates/api_models/src/disputes.rs
// Module: api_models
// Implementations: 0
pub struct SubmitEvidenceRequest
|
crates/api_models/src/disputes.rs
|
api_models
|
struct_definition
|
SubmitEvidenceRequest
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Struct: ResultInfo
// File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ResultInfo
|
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ResultInfo
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorValidation for for Flexiti
// File: crates/hyperswitch_connectors/src/connectors/flexiti.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl ConnectorValidation for for Flexiti
|
crates/hyperswitch_connectors/src/connectors/flexiti.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Flexiti
|
ConnectorValidation for
| 3
| 0
| null | null |
// File: crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs
// Module: hyperswitch_domain_models
// Public structs: 4
#[derive(Debug, Clone)]
pub struct SubscriptionCreate;
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlans;
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlanPrices;
#[derive(Debug, Clone)]
pub struct GetSubscriptionEstimate;
|
crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 82
| null | null | null | null | null | null | null |
// Struct: PaymentAttemptBatchNew
// File: crates/diesel_models/src/user/sample_data.rs
// Module: diesel_models
// Implementations: 2
pub struct PaymentAttemptBatchNew
|
crates/diesel_models/src/user/sample_data.rs
|
diesel_models
|
struct_definition
|
PaymentAttemptBatchNew
| 2
|
[] | 40
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Loonio
// File: crates/hyperswitch_connectors/src/connectors/loonio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Loonio
|
crates/hyperswitch_connectors/src/connectors/loonio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Loonio
|
api::PaymentSession for
| 0
| 0
| null | null |
// Struct: DenseMap
// File: crates/hyperswitch_constraint_graph/src/dense_map.rs
// Module: hyperswitch_constraint_graph
// Implementations: 5
// Traits: Default, fmt::Debug, IntoIterator
pub struct DenseMap<K, V>
|
crates/hyperswitch_constraint_graph/src/dense_map.rs
|
hyperswitch_constraint_graph
|
struct_definition
|
DenseMap
| 5
|
[
"Default",
"fmt::Debug",
"IntoIterator"
] | 57
| null | null | null | null | null | null | null |
// Implementation: impl PaymentSync for for Payone
// File: crates/hyperswitch_connectors/src/connectors/payone.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl PaymentSync for for Payone
|
crates/hyperswitch_connectors/src/connectors/payone.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Payone
|
PaymentSync for
| 0
| 0
| null | null |
// Implementation: impl RecoveryCodes
// File: crates/router/src/types/domain/user.rs
// Module: router
// Methods: 3 total (3 public)
impl RecoveryCodes
|
crates/router/src/types/domain/user.rs
|
router
|
impl_block
| null | null | null | 36
| null |
RecoveryCodes
| null | 3
| 3
| null | null |
// Implementation: impl ConnectorAuthType
// File: crates/hyperswitch_domain_models/src/router_data.rs
// Module: hyperswitch_domain_models
// Methods: 4 total (3 public)
impl ConnectorAuthType
|
crates/hyperswitch_domain_models/src/router_data.rs
|
hyperswitch_domain_models
|
impl_block
| null | null | null | 45
| null |
ConnectorAuthType
| null | 4
| 3
| null | null |
// Struct: VgsMetadata
// File: crates/external_services/src/grpc_client/unified_connector_service.rs
// Module: external_services
// Implementations: 0
pub struct VgsMetadata
|
crates/external_services/src/grpc_client/unified_connector_service.rs
|
external_services
|
struct_definition
|
VgsMetadata
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Struct: OnboardTransferMethodResponse
// File: crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct OnboardTransferMethodResponse
|
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
OnboardTransferMethodResponse
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// File: crates/common_utils/src/types.rs
// Module: common_utils
// Public functions: 26
// Public structs: 20
//! Types that can be used in other crates
pub mod keymanager;
/// Enum for Authentication Level
pub mod authentication;
/// User related types
pub mod user;
/// types that are wrappers around primitive types
pub mod primitive_wrappers;
use std::{
borrow::Cow,
fmt::Display,
iter::Sum,
num::NonZeroI64,
ops::{Add, Mul, Sub},
primitive::i64,
str::FromStr,
};
use common_enums::enums;
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
serialize::{Output, ToSql},
sql_types,
sql_types::Jsonb,
AsExpression, FromSqlRow, Queryable,
};
use error_stack::{report, ResultExt};
pub use primitive_wrappers::bool_wrappers::{
AlwaysRequestExtendedAuthorization, ExtendedAuthorizationAppliedBool,
RequestExtendedAuthorizationBool,
};
use rust_decimal::{
prelude::{FromPrimitive, ToPrimitive},
Decimal,
};
use semver::Version;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
use thiserror::Error;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{
consts::{
self, MAX_DESCRIPTION_LENGTH, MAX_STATEMENT_DESCRIPTOR_LENGTH, PUBLISHABLE_KEY_LENGTH,
},
errors::{CustomResult, ParsingError, PercentageError, ValidationError},
fp_utils::when,
impl_enum_str,
};
/// Represents Percentage Value between 0 and 100 both inclusive
#[derive(Clone, Default, Debug, PartialEq, Serialize)]
pub struct Percentage<const PRECISION: u8> {
// this value will range from 0 to 100, decimal length defined by precision macro
/// Percentage value ranging between 0 and 100
percentage: f32,
}
fn get_invalid_percentage_error_message(precision: u8) -> String {
format!(
"value should be a float between 0 to 100 and precise to only upto {precision} decimal digits",
)
}
impl<const PRECISION: u8> Percentage<PRECISION> {
/// construct percentage using a string representation of float value
pub fn from_string(value: String) -> CustomResult<Self, PercentageError> {
if Self::is_valid_string_value(&value)? {
Ok(Self {
percentage: value
.parse::<f32>()
.change_context(PercentageError::InvalidPercentageValue)?,
})
} else {
Err(report!(PercentageError::InvalidPercentageValue))
.attach_printable(get_invalid_percentage_error_message(PRECISION))
}
}
/// function to get percentage value
pub fn get_percentage(&self) -> f32 {
self.percentage
}
/// apply the percentage to amount and ceil the result
#[allow(clippy::as_conversions)]
pub fn apply_and_ceil_result(
&self,
amount: MinorUnit,
) -> CustomResult<MinorUnit, PercentageError> {
let max_amount = i64::MAX / 10000;
let amount = amount.0;
if amount > max_amount {
// value gets rounded off after i64::MAX/10000
Err(report!(PercentageError::UnableToApplyPercentage {
percentage: self.percentage,
amount: MinorUnit::new(amount),
}))
.attach_printable(format!(
"Cannot calculate percentage for amount greater than {max_amount}",
))
} else {
let percentage_f64 = f64::from(self.percentage);
let result = (amount as f64 * (percentage_f64 / 100.0)).ceil() as i64;
Ok(MinorUnit::new(result))
}
}
fn is_valid_string_value(value: &str) -> CustomResult<bool, PercentageError> {
let float_value = Self::is_valid_float_string(value)?;
Ok(Self::is_valid_range(float_value) && Self::is_valid_precision_length(value))
}
fn is_valid_float_string(value: &str) -> CustomResult<f32, PercentageError> {
value
.parse::<f32>()
.change_context(PercentageError::InvalidPercentageValue)
}
fn is_valid_range(value: f32) -> bool {
(0.0..=100.0).contains(&value)
}
fn is_valid_precision_length(value: &str) -> bool {
if value.contains('.') {
// if string has '.' then take the decimal part and verify precision length
match value.split('.').next_back() {
Some(decimal_part) => {
decimal_part.trim_end_matches('0').len() <= <u8 as Into<usize>>::into(PRECISION)
}
// will never be None
None => false,
}
} else {
// if there is no '.' then it is a whole number with no decimal part. So return true
true
}
}
}
// custom serde deserialization function
struct PercentageVisitor<const PRECISION: u8> {}
impl<'de, const PRECISION: u8> Visitor<'de> for PercentageVisitor<PRECISION> {
type Value = Percentage<PRECISION>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Percentage object")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut percentage_value = None;
while let Some(key) = map.next_key::<String>()? {
if key.eq("percentage") {
if percentage_value.is_some() {
return Err(serde::de::Error::duplicate_field("percentage"));
}
percentage_value = Some(map.next_value::<serde_json::Value>()?);
} else {
// Ignore unknown fields
let _: serde::de::IgnoredAny = map.next_value()?;
}
}
if let Some(value) = percentage_value {
let string_value = value.to_string();
Ok(Percentage::from_string(string_value.clone()).map_err(|_| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Other(&format!("percentage value {string_value}")),
&&*get_invalid_percentage_error_message(PRECISION),
)
})?)
} else {
Err(serde::de::Error::missing_field("percentage"))
}
}
}
impl<'de, const PRECISION: u8> Deserialize<'de> for Percentage<PRECISION> {
fn deserialize<D>(data: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
data.deserialize_map(PercentageVisitor::<PRECISION> {})
}
}
/// represents surcharge type and value
#[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum Surcharge {
/// Fixed Surcharge value
Fixed(MinorUnit),
/// Surcharge percentage
Rate(Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>),
}
/// This struct lets us represent a semantic version type
#[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, Ord, PartialOrd)]
#[diesel(sql_type = Jsonb)]
#[derive(Serialize, serde::Deserialize)]
pub struct SemanticVersion(#[serde(with = "Version")] Version);
impl SemanticVersion {
/// returns major version number
pub fn get_major(&self) -> u64 {
self.0.major
}
/// returns minor version number
pub fn get_minor(&self) -> u64 {
self.0.minor
}
/// Constructs new SemanticVersion instance
pub fn new(major: u64, minor: u64, patch: u64) -> Self {
Self(Version::new(major, minor, patch))
}
}
impl Display for SemanticVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for SemanticVersion {
type Err = error_stack::Report<ParsingError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(Version::from_str(s).change_context(
ParsingError::StructParseFailure("SemanticVersion"),
)?))
}
}
crate::impl_to_sql_from_sql_json!(SemanticVersion);
/// Amount convertor trait for connector
pub trait AmountConvertor: Send {
/// Output type for the connector
type Output;
/// helps in conversion of connector required amount type
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>>;
/// helps in converting back connector required amount type to core minor unit
fn convert_back(
&self,
amount: Self::Output,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>>;
}
/// Connector required amount type
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct StringMinorUnitForConnector;
impl AmountConvertor for StringMinorUnitForConnector {
type Output = StringMinorUnit;
fn convert(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_string()
}
fn convert_back(
&self,
amount: Self::Output,
_currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64()
}
}
/// Core required conversion type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct StringMajorUnitForCore;
impl AmountConvertor for StringMajorUnitForCore {
type Output = StringMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_string(currency)
}
fn convert_back(
&self,
amount: StringMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct StringMajorUnitForConnector;
impl AmountConvertor for StringMajorUnitForConnector {
type Output = StringMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_string(currency)
}
fn convert_back(
&self,
amount: StringMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct FloatMajorUnitForConnector;
impl AmountConvertor for FloatMajorUnitForConnector {
type Output = FloatMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_f64(currency)
}
fn convert_back(
&self,
amount: FloatMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct MinorUnitForConnector;
impl AmountConvertor for MinorUnitForConnector {
type Output = MinorUnit;
fn convert(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
Ok(amount)
}
fn convert_back(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
Ok(amount)
}
}
/// This Unit struct represents MinorUnit in which core amount works
#[derive(
Default,
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
Copy,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
#[diesel(sql_type = sql_types::BigInt)]
pub struct MinorUnit(i64);
impl MinorUnit {
/// gets amount as i64 value will be removed in future
pub fn get_amount_as_i64(self) -> i64 {
self.0
}
/// forms a new minor default unit i.e zero
pub fn zero() -> Self {
Self(0)
}
/// forms a new minor unit from amount
pub fn new(value: i64) -> Self {
Self(value)
}
/// checks if the amount is greater than the given value
pub fn is_greater_than(&self, value: i64) -> bool {
self.get_amount_as_i64() > value
}
/// Convert the amount to its major denomination based on Currency and return String
/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies.
/// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/
fn to_major_unit_as_string(
self,
currency: enums::Currency,
) -> Result<StringMajorUnit, error_stack::Report<ParsingError>> {
let amount_f64 = self.to_major_unit_as_f64(currency)?;
let amount_string = if currency.is_zero_decimal_currency() {
amount_f64.0.to_string()
} else if currency.is_three_decimal_currency() {
format!("{:.3}", amount_f64.0)
} else {
format!("{:.2}", amount_f64.0)
};
Ok(StringMajorUnit::new(amount_string))
}
/// Convert the amount to its major denomination based on Currency and return f64
fn to_major_unit_as_f64(
self,
currency: enums::Currency,
) -> Result<FloatMajorUnit, error_stack::Report<ParsingError>> {
let amount_decimal =
Decimal::from_i64(self.0).ok_or(ParsingError::I64ToDecimalConversionFailure)?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal / Decimal::from(1000)
} else {
amount_decimal / Decimal::from(100)
};
let amount_f64 = amount
.to_f64()
.ok_or(ParsingError::FloatToDecimalConversionFailure)?;
Ok(FloatMajorUnit::new(amount_f64))
}
///Convert minor unit to string minor unit
fn to_minor_unit_as_string(self) -> Result<StringMinorUnit, error_stack::Report<ParsingError>> {
Ok(StringMinorUnit::new(self.0.to_string()))
}
}
impl From<NonZeroI64> for MinorUnit {
fn from(val: NonZeroI64) -> Self {
Self::new(val.get())
}
}
impl Display for MinorUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl<DB> FromSql<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
i64: FromSql<sql_types::BigInt, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = i64::from_sql(value)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
i64: ToSql<sql_types::BigInt, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
Self: FromSql<sql_types::BigInt, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl Add for MinorUnit {
type Output = Self;
fn add(self, a2: Self) -> Self {
Self(self.0 + a2.0)
}
}
impl Sub for MinorUnit {
type Output = Self;
fn sub(self, a2: Self) -> Self {
Self(self.0 - a2.0)
}
}
impl Mul<u16> for MinorUnit {
type Output = Self;
fn mul(self, a2: u16) -> Self::Output {
Self(self.0 * i64::from(a2))
}
}
impl Sum for MinorUnit {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self(0), |a, b| a + b)
}
}
/// Connector specific types to send
#[derive(
Default,
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
#[diesel(sql_type = sql_types::Text)]
pub struct StringMinorUnit(String);
impl StringMinorUnit {
/// forms a new minor unit in string from amount
fn new(value: String) -> Self {
Self(value)
}
/// converts to minor unit i64 from minor unit string value
fn to_minor_unit_as_i64(&self) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_string = &self.0;
let amount_decimal = Decimal::from_str(amount_string).map_err(|e| {
ParsingError::StringToDecimalConversionFailure {
error: e.to_string(),
}
})?;
let amount_i64 = amount_decimal
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
}
impl Display for StringMinorUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl<DB> FromSql<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(value)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// Connector specific types to send
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct FloatMajorUnit(f64);
impl FloatMajorUnit {
/// forms a new major unit from amount
fn new(value: f64) -> Self {
Self(value)
}
/// forms a new major unit with zero amount
pub fn zero() -> Self {
Self(0.0)
}
/// converts to minor unit as i64 from FloatMajorUnit
fn to_minor_unit_as_i64(
self,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_decimal =
Decimal::from_f64(self.0).ok_or(ParsingError::FloatToDecimalConversionFailure)?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal * Decimal::from(1000)
} else {
amount_decimal * Decimal::from(100)
};
let amount_i64 = amount
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
}
/// Connector specific types to send
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
pub struct StringMajorUnit(String);
impl StringMajorUnit {
/// forms a new major unit from amount
fn new(value: String) -> Self {
Self(value)
}
/// Converts to minor unit as i64 from StringMajorUnit
fn to_minor_unit_as_i64(
&self,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_decimal = Decimal::from_str(&self.0).map_err(|e| {
ParsingError::StringToDecimalConversionFailure {
error: e.to_string(),
}
})?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal * Decimal::from(1000)
} else {
amount_decimal * Decimal::from(100)
};
let amount_i64 = amount
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
/// forms a new StringMajorUnit default unit i.e zero
pub fn zero() -> Self {
Self("0".to_string())
}
/// Get string amount from struct to be removed in future
pub fn get_amount_as_string(&self) -> String {
self.0.clone()
}
}
#[derive(
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
#[diesel(sql_type = sql_types::Text)]
/// This domain type can be used for any url
pub struct Url(url::Url);
impl Url {
/// Get string representation of the url
pub fn get_string_repr(&self) -> &str {
self.0.as_str()
}
/// wrap the url::Url in Url type
pub fn wrap(url: url::Url) -> Self {
Self(url)
}
/// Get the inner url
pub fn into_inner(self) -> url::Url {
self.0
}
/// Add query params to the url
pub fn add_query_params(mut self, (key, value): (&str, &str)) -> Self {
let url = self
.0
.query_pairs_mut()
.append_pair(key, value)
.finish()
.clone();
Self(url)
}
}
impl<DB> ToSql<sql_types::Text, DB> for Url
where
DB: Backend,
str: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
let url_string = self.0.as_str();
url_string.to_sql(out)
}
}
impl<DB> FromSql<sql_types::Text, DB> for Url
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(value)?;
let url = url::Url::parse(&val)?;
Ok(Self(url))
}
}
/// A type representing a range of time for filtering, including a mandatory start time and an optional end time.
#[derive(
Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
)]
pub struct TimeRange {
/// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed
#[serde(with = "crate::custom_serde::iso8601")]
#[serde(alias = "startTime")]
pub start_time: PrimitiveDateTime,
/// The end time to filter payments list or to get list of filters. If not passed the default time is now
#[serde(default, with = "crate::custom_serde::iso8601::option")]
#[serde(alias = "endTime")]
pub end_time: Option<PrimitiveDateTime>,
}
#[cfg(test)]
mod amount_conversion_tests {
#![allow(clippy::unwrap_used)]
use super::*;
const TWO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::USD;
const THREE_DECIMAL_CURRENCY: enums::Currency = enums::Currency::BHD;
const ZERO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::JPY;
#[test]
fn amount_conversion_to_float_major_unit() {
let request_amount = MinorUnit::new(999999999);
let required_conversion = FloatMajorUnitForConnector;
// Two decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 9999999.99);
let converted_back_amount = required_conversion
.convert_back(converted_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Three decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 999999.999);
let converted_back_amount = required_conversion
.convert_back(converted_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Zero decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 999999999.0);
let converted_back_amount = required_conversion
.convert_back(converted_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
#[test]
fn amount_conversion_to_string_major_unit() {
let request_amount = MinorUnit::new(999999999);
let required_conversion = StringMajorUnitForConnector;
// Two decimal currency conversions
let converted_amount_two_decimal_currency = required_conversion
.convert(request_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(
converted_amount_two_decimal_currency.0,
"9999999.99".to_string()
);
let converted_back_amount = required_conversion
.convert_back(converted_amount_two_decimal_currency, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Three decimal currency conversions
let converted_amount_three_decimal_currency = required_conversion
.convert(request_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(
converted_amount_three_decimal_currency.0,
"999999.999".to_string()
);
let converted_back_amount = required_conversion
.convert_back(
converted_amount_three_decimal_currency,
THREE_DECIMAL_CURRENCY,
)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Zero decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, "999999999".to_string());
let converted_back_amount = required_conversion
.convert_back(converted_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
#[test]
fn amount_conversion_to_string_minor_unit() {
let request_amount = MinorUnit::new(999999999);
let currency = TWO_DECIMAL_CURRENCY;
let required_conversion = StringMinorUnitForConnector;
let converted_amount = required_conversion
.convert(request_amount, currency)
.unwrap();
assert_eq!(converted_amount.0, "999999999".to_string());
let converted_back_amount = required_conversion
.convert_back(converted_amount, currency)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
}
// Charges structs
#[derive(
Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
/// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details.
pub struct ChargeRefunds {
/// Identifier for charge created for the payment
pub charge_id: String,
/// Toggle for reverting the application fee that was collected for the payment.
/// If set to false, the funds are pulled from the destination account.
pub revert_platform_fee: Option<bool>,
/// Toggle for reverting the transfer that was made during the charge.
/// If set to false, the funds are pulled from the main platform's account.
pub revert_transfer: Option<bool>,
}
crate::impl_to_sql_from_sql_json!(ChargeRefunds);
/// A common type of domain type that can be used for fields that contain a string with restriction of length
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub(crate) struct LengthString<const MAX_LENGTH: u16, const MIN_LENGTH: u16>(String);
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum LengthStringError {
#[error("the maximum allowed length for this field is {0}")]
/// Maximum length of string violated
MaxLengthViolated(u16),
#[error("the minimum required length for this field is {0}")]
/// Minimum length of string violated
MinLengthViolated(u16),
}
impl<const MAX_LENGTH: u16, const MIN_LENGTH: u16> LengthString<MAX_LENGTH, MIN_LENGTH> {
/// Generates new [MerchantReferenceId] from the given input string
pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthStringError> {
let trimmed_input_string = input_string.trim().to_string();
let length_of_input_string = u16::try_from(trimmed_input_string.len())
.map_err(|_| LengthStringError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthStringError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthStringError::MinLengthViolated(MIN_LENGTH))
})?;
Ok(Self(trimmed_input_string))
}
pub(crate) fn new_unchecked(input_string: String) -> Self {
Self(input_string)
}
}
impl<'de, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Deserialize<'de>
for LengthString<MAX_LENGTH, MIN_LENGTH>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> FromSql<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> ToSql<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Queryable<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// Domain type for description
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct Description(LengthString<MAX_DESCRIPTION_LENGTH, 1>);
impl Description {
/// Create a new Description Domain type without any length check from a static str
pub fn from_str_unchecked(input_str: &'static str) -> Self {
Self(LengthString::new_unchecked(input_str.to_owned()))
}
// TODO: Remove this function in future once description in router data is updated to domain type
/// Get the string representation of the description
pub fn get_string_repr(&self) -> &str {
&self.0 .0
}
}
/// Domain type for Statement Descriptor
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct StatementDescriptor(LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>);
impl<DB> Queryable<sql_types::Text, DB> for Description
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for Description
where
DB: Backend,
LengthString<MAX_DESCRIPTION_LENGTH, 1>: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = LengthString::<MAX_DESCRIPTION_LENGTH, 1>::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for Description
where
DB: Backend,
LengthString<MAX_DESCRIPTION_LENGTH, 1>: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::Text, DB> for StatementDescriptor
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for StatementDescriptor
where
DB: Backend,
LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
|
crates/common_utils/src/types.rs#chunk0
|
common_utils
|
chunk
| null | null | null | 8,189
| null | null | null | null | null | null | null |
// Implementation: impl AddressStructForDbUpdate
// File: crates/router/src/core/customers.rs
// Module: router
// Methods: 1 total (0 public)
impl AddressStructForDbUpdate
|
crates/router/src/core/customers.rs
|
router
|
impl_block
| null | null | null | 42
| null |
AddressStructForDbUpdate
| null | 1
| 0
| null | null |
// Struct: IndomaretVoucherData
// File: crates/hyperswitch_domain_models/src/payment_method_data.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct IndomaretVoucherData
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
|
IndomaretVoucherData
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Implementation: impl Paypal
// File: crates/hyperswitch_connectors/src/connectors/paypal.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl Paypal
|
crates/hyperswitch_connectors/src/connectors/paypal.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 43
| null |
Paypal
| null | 1
| 1
| null | null |
ds_response: DsResponse,
capture_method: Option<enums::CaptureMethod>,
) -> Result<enums::AttemptStatus, error_stack::Report<errors::ConnectorError>> {
// Redsys consistently provides a 4-digit response code, where numbers ranging from 0000 to 0099 indicate successful transactions
if ds_response.0.starts_with("00") {
match capture_method {
Some(enums::CaptureMethod::Automatic) | None => Ok(enums::AttemptStatus::Charged),
Some(enums::CaptureMethod::Manual) => Ok(enums::AttemptStatus::Authorized),
_ => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
} else {
match ds_response.0.as_str() {
"0900" => Ok(enums::AttemptStatus::Charged),
"0400" => Ok(enums::AttemptStatus::Voided),
"0950" => Ok(enums::AttemptStatus::VoidFailed),
"9998" => Ok(enums::AttemptStatus::AuthenticationPending),
"9256" | "9257" | "0184" => Ok(enums::AttemptStatus::AuthenticationFailed),
"0101" | "0102" | "0106" | "0125" | "0129" | "0172" | "0173" | "0174" | "0180"
| "0190" | "0191" | "0195" | "0202" | "0904" | "0909" | "0913" | "0944" | "9912"
| "0912" | "9064" | "9078" | "9093" | "9094" | "9104" | "9218" | "9253" | "9261"
| "9915" | "9997" | "9999" => Ok(enums::AttemptStatus::Failure),
error => Err(errors::ConnectorError::ResponseHandlingFailed)
.attach_printable(format!("Received Unknown Status:{error}"))?,
}
}
}
impl TryFrom<&RedsysRouterData<&PaymentsAuthorizeRouterData>> for RedsysTransaction {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RedsysRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if !item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "No-3DS cards".to_string(),
connector: "redsys",
})?
};
let auth = RedsysAuthType::try_from(&item.router_data.connector_auth_type)?;
let ds_merchant_transactiontype = if item.router_data.request.is_auto_capture()? {
RedsysTransactionType::Payment
} else {
RedsysTransactionType::Preauthorization
};
let card_data =
RedsysCardData::try_from(&Some(item.router_data.request.payment_method_data.clone()))?;
let (connector_meta_data, ds_merchant_order) = match &item.router_data.response {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(order_id),
connector_metadata,
..
}) => (connector_metadata.clone(), order_id.clone()),
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let threeds_meta_data =
connector_utils::to_connector_meta::<ThreeDsInvokeExempt>(connector_meta_data.clone())?;
let emv3ds_data = EmvThreedsData::new(RedsysThreeDsInfo::AuthenticationData)
.set_three_d_s_server_trans_i_d(threeds_meta_data.three_d_s_server_trans_i_d)
.set_protocol_version(threeds_meta_data.message_version)
.set_notification_u_r_l(item.router_data.request.get_complete_authorize_url()?)
.add_browser_data(item.router_data.request.get_browser_info()?)?
.set_three_d_s_comp_ind(ThreeDSCompInd::N)
.set_billing_data(item.router_data.get_optional_billing())?
.set_shipping_data(item.router_data.get_optional_shipping())?;
let payment_authorize_request = PaymentsRequest {
ds_merchant_emv3ds: Some(emv3ds_data),
ds_merchant_transactiontype,
ds_merchant_currency: item.currency.iso_4217().to_owned(),
ds_merchant_pan: card_data.card_number,
ds_merchant_merchantcode: auth.merchant_id.clone(),
ds_merchant_terminal: auth.terminal_id.clone(),
ds_merchant_order,
ds_merchant_amount: item.amount.clone(),
ds_merchant_expirydate: card_data.expiry_date,
ds_merchant_cvv2: card_data.cvv2,
};
Self::try_from((&payment_authorize_request, &auth))
}
}
fn build_threeds_form(ds_emv3ds: &RedsysEmv3DSData) -> Result<RedirectForm, Error> {
let creq = ds_emv3ds
.creq
.clone()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let endpoint = ds_emv3ds
.acs_u_r_l
.clone()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let mut form_fields = std::collections::HashMap::new();
form_fields.insert("creq".to_string(), creq);
Ok(RedirectForm::Form {
endpoint,
method: common_utils::request::Method::Post,
form_fields,
})
}
impl<F> TryFrom<ResponseRouterData<F, RedsysResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RedsysResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.clone() {
RedsysResponse::RedsysResponse(transaction_response) => {
let connector_metadata = match item.data.response {
Ok(PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) => connector_metadata,
_ => None,
};
let response_data: RedsysPaymentsResponse = to_connector_response_data(
&transaction_response.ds_merchant_parameters.clone().expose(),
)?;
get_payments_response(
response_data,
item.data.request.capture_method,
connector_metadata,
item.http_code,
)?
}
RedsysResponse::RedsysErrorResponse(response) => {
let response = Err(ErrorResponse {
code: response.error_code.clone(),
message: response.error_code.clone(),
reason: Some(response.error_code.clone()),
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,
});
(response, enums::AttemptStatus::Failure)
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreedsChallengeResponse {
cres: String,
}
impl TryFrom<&RedsysRouterData<&PaymentsCompleteAuthorizeRouterData>> for RedsysTransaction {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RedsysRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if !item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "PaymentsComplete flow for no-3ds cards".to_string(),
connector: "redsys",
})?
};
let card_data =
RedsysCardData::try_from(&item.router_data.request.payment_method_data.clone())?;
let auth = RedsysAuthType::try_from(&item.router_data.connector_auth_type)?;
let redirect_response = item
.router_data
.request
.get_redirect_response_payload()
.ok()
.clone()
.map(|payload_data| {
payload_data
.parse_value::<ThreedsChallengeResponse>("Redsys ThreedsChallengeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
})
.transpose()?;
let billing_data = item.router_data.get_optional_billing();
let shipping_data = item.router_data.get_optional_shipping();
let emv3ds_data = match redirect_response {
Some(payload) => {
if let Ok(threeds_invoke_meta_data) =
connector_utils::to_connector_meta::<RedsysThreeDsInvokeData>(
item.router_data.request.connector_meta.clone(),
)
{
EmvThreedsData::new(RedsysThreeDsInfo::ChallengeResponse)
.set_protocol_version(threeds_invoke_meta_data.message_version)
.set_three_d_s_cres(payload.cres)
.set_billing_data(billing_data)?
.set_shipping_data(shipping_data)?
} else if let Ok(threeds_meta_data) =
connector_utils::to_connector_meta::<ThreeDsInvokeExempt>(
item.router_data.request.connector_meta.clone(),
)
{
EmvThreedsData::new(RedsysThreeDsInfo::ChallengeResponse)
.set_protocol_version(threeds_meta_data.message_version)
.set_three_d_s_cres(payload.cres)
.set_billing_data(billing_data)?
.set_shipping_data(shipping_data)?
} else {
Err(errors::ConnectorError::RequestEncodingFailed)?
}
}
None => {
if let Ok(threeds_invoke_meta_data) =
connector_utils::to_connector_meta::<RedsysThreeDsInvokeData>(
item.router_data.request.connector_meta.clone(),
)
{
let three_d_s_comp_ind = ThreeDSCompInd::from(
item.router_data.request.get_threeds_method_comp_ind()?,
);
let browser_info = item.router_data.request.get_browser_info()?;
let complete_authorize_url =
item.router_data.request.get_complete_authorize_url()?;
EmvThreedsData::new(RedsysThreeDsInfo::AuthenticationData)
.set_three_d_s_server_trans_i_d(
threeds_invoke_meta_data.directory_server_id,
)
.set_protocol_version(threeds_invoke_meta_data.message_version)
.set_three_d_s_comp_ind(three_d_s_comp_ind)
.add_browser_data(browser_info)?
.set_notification_u_r_l(complete_authorize_url)
.set_billing_data(billing_data)?
.set_shipping_data(shipping_data)?
} else {
Err(errors::ConnectorError::NoConnectorMetaData)?
}
}
};
let ds_merchant_transactiontype = if item.router_data.request.is_auto_capture()? {
RedsysTransactionType::Payment
} else {
RedsysTransactionType::Preauthorization
};
let ds_merchant_order = item
.router_data
.request
.connector_transaction_id
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Missing connector_transaction_id")?;
let complete_authorize_response = PaymentsRequest {
ds_merchant_emv3ds: Some(emv3ds_data),
ds_merchant_transactiontype,
ds_merchant_currency: item.currency.iso_4217().to_owned(),
ds_merchant_pan: card_data.card_number,
ds_merchant_merchantcode: auth.merchant_id.clone(),
ds_merchant_terminal: auth.terminal_id.clone(),
ds_merchant_order,
ds_merchant_amount: item.amount.clone(),
ds_merchant_expirydate: card_data.expiry_date,
ds_merchant_cvv2: card_data.cvv2,
};
Self::try_from((&complete_authorize_response, &auth))
}
}
impl<F> TryFrom<ResponseRouterData<F, RedsysResponse, CompleteAuthorizeData, PaymentsResponseData>>
for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RedsysResponse, CompleteAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.clone() {
RedsysResponse::RedsysResponse(transaction_response) => {
let response_data: RedsysPaymentsResponse = to_connector_response_data(
&transaction_response.ds_merchant_parameters.clone().expose(),
)?;
get_payments_response(
response_data,
item.data.request.capture_method,
None,
item.http_code,
)?
}
RedsysResponse::RedsysErrorResponse(response) => {
let response = Err(ErrorResponse {
code: response.error_code.clone(),
message: response.error_code.clone(),
reason: Some(response.error_code.clone()),
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,
});
(response, enums::AttemptStatus::Failure)
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl From<api_models::payments::ThreeDsCompletionIndicator> for ThreeDSCompInd {
fn from(threeds_compl_flag: api_models::payments::ThreeDsCompletionIndicator) -> Self {
match threeds_compl_flag {
api_models::payments::ThreeDsCompletionIndicator::Success => Self::Y,
api_models::payments::ThreeDsCompletionIndicator::Failure
| api_models::payments::ThreeDsCompletionIndicator::NotAvailable => Self::N,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct RedsysOperationRequest {
ds_merchant_order: String,
ds_merchant_merchantcode: Secret<String>,
ds_merchant_terminal: Secret<String>,
ds_merchant_currency: String,
ds_merchant_transactiontype: RedsysTransactionType,
ds_merchant_amount: StringMinorUnit,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RedsysOperationsResponse {
#[serde(rename = "Ds_Order")]
ds_order: String,
#[serde(rename = "Ds_Response")]
ds_response: DsResponse,
#[serde(rename = "Ds_AuthorisationCode")]
ds_authorisation_code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum RedsysOperationResponse {
RedsysOperationResponse(RedsysTransaction),
RedsysOperationsErrorResponse(RedsysErrorResponse),
}
impl TryFrom<&RedsysRouterData<&PaymentsCaptureRouterData>> for RedsysTransaction {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RedsysRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = RedsysAuthType::try_from(&item.router_data.connector_auth_type)?;
let redys_capture_request = RedsysOperationRequest {
ds_merchant_order: item.router_data.request.connector_transaction_id.clone(),
ds_merchant_merchantcode: auth.merchant_id.clone(),
ds_merchant_terminal: auth.terminal_id.clone(),
ds_merchant_currency: item.router_data.request.currency.iso_4217().to_owned(),
ds_merchant_transactiontype: RedsysTransactionType::Confirmation,
ds_merchant_amount: item.amount.clone(),
};
Self::try_from((&redys_capture_request, &auth))
}
}
impl<F> TryFrom<ResponseRouterData<F, RedsysResponse, PaymentsCaptureData, PaymentsResponseData>>
for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RedsysResponse, PaymentsCaptureData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response {
RedsysResponse::RedsysResponse(redsys_transaction_response) => {
let response_data: RedsysOperationsResponse = to_connector_response_data(
&redsys_transaction_response
.ds_merchant_parameters
.clone()
.expose(),
)?;
let status = get_redsys_attempt_status(response_data.ds_response.clone(), None)?;
let response = if connector_utils::is_payment_failure(status) {
Err(ErrorResponse {
code: response_data.ds_response.0.clone(),
message: response_data.ds_response.0.clone(),
reason: Some(response_data.ds_response.0.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(response_data.ds_order.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response_data.ds_order.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response_data.ds_order.clone()),
incremental_authorization_allowed: None,
charges: None,
})
};
(response, status)
}
RedsysResponse::RedsysErrorResponse(error_response) => {
let response = Err(ErrorResponse {
code: error_response.error_code.clone(),
message: error_response.error_code.clone(),
reason: Some(error_response.error_code.clone()),
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,
});
(response, enums::AttemptStatus::Failure)
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<&RedsysRouterData<&PaymentsCancelRouterData>> for RedsysTransaction {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RedsysRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> {
let auth = RedsysAuthType::try_from(&item.router_data.connector_auth_type)?;
let redsys_cancel_request = RedsysOperationRequest {
ds_merchant_order: item.router_data.request.connector_transaction_id.clone(),
ds_merchant_merchantcode: auth.merchant_id.clone(),
ds_merchant_terminal: auth.terminal_id.clone(),
ds_merchant_currency: item.currency.iso_4217().to_owned(),
ds_merchant_transactiontype: RedsysTransactionType::Cancellation,
ds_merchant_amount: item.amount.clone(),
};
Self::try_from((&redsys_cancel_request, &auth))
}
}
impl<F> TryFrom<&RedsysRouterData<&RefundsRouterData<F>>> for RedsysTransaction {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RedsysRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth = RedsysAuthType::try_from(&item.router_data.connector_auth_type)?;
let redsys_refund_request = RedsysOperationRequest {
ds_merchant_order: item.router_data.request.connector_transaction_id.clone(),
ds_merchant_merchantcode: auth.merchant_id.clone(),
ds_merchant_terminal: auth.terminal_id.clone(),
ds_merchant_currency: item.currency.iso_4217().to_owned(),
ds_merchant_transactiontype: RedsysTransactionType::Refund,
ds_merchant_amount: item.amount.clone(),
};
Self::try_from((&redsys_refund_request, &auth))
}
}
impl<F> TryFrom<ResponseRouterData<F, RedsysResponse, PaymentsCancelData, PaymentsResponseData>>
for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RedsysResponse, PaymentsCancelData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response {
RedsysResponse::RedsysResponse(redsys_transaction_response) => {
let response_data: RedsysOperationsResponse = to_connector_response_data(
&redsys_transaction_response
.ds_merchant_parameters
.clone()
.expose(),
)?;
let status = get_redsys_attempt_status(response_data.ds_response.clone(), None)?;
let response = if connector_utils::is_payment_failure(status) {
Err(ErrorResponse {
code: response_data.ds_response.0.clone(),
message: response_data.ds_response.0.clone(),
reason: Some(response_data.ds_response.0.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(response_data.ds_order.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response_data.ds_order.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response_data.ds_order.clone()),
incremental_authorization_allowed: None,
charges: None,
})
};
(response, status)
}
RedsysResponse::RedsysErrorResponse(error_response) => {
let response = Err(ErrorResponse {
code: error_response.error_code.clone(),
message: error_response.error_code.clone(),
reason: Some(error_response.error_code.clone()),
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,
});
(response, enums::AttemptStatus::VoidFailed)
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<DsResponse> for enums::RefundStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(ds_response: DsResponse) -> Result<Self, Self::Error> {
match ds_response.0.as_str() {
"0900" => Ok(Self::Success),
"9999" => Ok(Self::Pending),
"0950" | "0172" | "174" => Ok(Self::Failure),
unknown_status => Err(errors::ConnectorError::ResponseHandlingFailed)
.attach_printable(format!("Received unknown status:{unknown_status}"))?,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RedsysResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RedsysResponse>,
) -> Result<Self, Self::Error> {
let response = match item.response {
RedsysResponse::RedsysResponse(redsys_transaction) => {
let response_data: RedsysOperationsResponse = to_connector_response_data(
&redsys_transaction.ds_merchant_parameters.clone().expose(),
)?;
let refund_status =
enums::RefundStatus::try_from(response_data.ds_response.clone())?;
if connector_utils::is_refund_failure(refund_status) {
Err(ErrorResponse {
code: response_data.ds_response.0.clone(),
message: response_data.ds_response.0.clone(),
reason: Some(response_data.ds_response.0.clone()),
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,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: response_data.ds_order,
refund_status,
})
}
}
RedsysResponse::RedsysErrorResponse(redsys_error_response) => Err(ErrorResponse {
code: redsys_error_response.error_code.clone(),
message: redsys_error_response.error_code.clone(),
reason: Some(redsys_error_response.error_code.clone()),
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,
}),
};
Ok(Self {
response,
..item.data
})
}
}
fn get_payments_response(
redsys_payments_response: RedsysPaymentsResponse,
capture_method: Option<enums::CaptureMethod>,
connector_metadata: Option<josekit::Value>,
http_code: u16,
) -> Result<
(
Result<PaymentsResponseData, ErrorResponse>,
enums::AttemptStatus,
),
Error,
> {
if let Some(ds_response) = redsys_payments_response.ds_response {
let status = get_redsys_attempt_status(ds_response.clone(), capture_method)?;
let response = if connector_utils::is_payment_failure(status) {
Err(ErrorResponse {
code: ds_response.0.clone(),
message: ds_response.0.clone(),
reason: Some(ds_response.0.clone()),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(redsys_payments_response.ds_order.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
redsys_payments_response.ds_order.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(redsys_payments_response.ds_order.clone()),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok((response, status))
} else {
let redirection_form = redsys_payments_response
.ds_emv3ds
.map(|ds_emv3ds| build_threeds_form(&ds_emv3ds))
.transpose()?;
let response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
redsys_payments_response.ds_order.clone(),
),
redirection_data: Box::new(redirection_form),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(redsys_payments_response.ds_order.clone()),
incremental_authorization_allowed: None,
charges: None,
});
Ok((response, enums::AttemptStatus::AuthenticationPending))
}
}
#[derive(Debug, Serialize)]
pub struct Messages {
#[serde(rename = "Version")]
version: VersionData,
#[serde(rename = "Signature")]
signature: String,
#[serde(rename = "SignatureVersion")]
signature_version: String,
}
#[derive(Debug, Serialize)]
#[serde(rename = "Version")]
pub struct VersionData {
#[serde(rename = "@Ds_Version")]
ds_version: String,
#[serde(rename = "Message")]
message: Message,
}
#[derive(Debug, Serialize)]
pub struct Message {
#[serde(rename = "Transaction")]
transaction: RedsysSyncRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename = "Transaction")]
pub struct RedsysSyncRequest {
#[serde(rename = "Ds_MerchantCode")]
ds_merchant_code: Secret<String>,
#[serde(rename = "Ds_Terminal")]
ds_terminal: Secret<String>,
#[serde(rename = "Ds_Order")]
ds_order: String,
#[serde(rename = "Ds_TransactionType")]
ds_transaction_type: String,
}
fn get_transaction_type(
status: enums::AttemptStatus,
capture_method: Option<enums::CaptureMethod>,
) -> Result<String, errors::ConnectorError> {
match status {
enums::AttemptStatus::AuthenticationPending
| enums::AttemptStatus::AuthenticationSuccessful
| enums::AttemptStatus::Started
| enums::AttemptStatus::Authorizing
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::DeviceDataCollectionPending => match capture_method {
Some(enums::CaptureMethod::Automatic) | None => {
Ok(transaction_type::PAYMENT.to_owned())
}
Some(enums::CaptureMethod::Manual) => Ok(transaction_type::PREAUTHORIZATION.to_owned()),
Some(capture_method) => Err(errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: "redsys",
}),
},
enums::AttemptStatus::VoidInitiated => Ok(transaction_type::CANCELLATION.to_owned()),
enums::AttemptStatus::PartialChargedAndChargeable
| enums::AttemptStatus::CaptureInitiated => Ok(transaction_type::CONFIRMATION.to_owned()),
enums::AttemptStatus::Pending => match capture_method {
Some(enums::CaptureMethod::Automatic) | None => {
Ok(transaction_type::PAYMENT.to_owned())
}
Some(enums::CaptureMethod::Manual) => Ok(transaction_type::CONFIRMATION.to_owned()),
Some(capture_method) => Err(errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: "redsys",
}),
},
other_attempt_status => Err(errors::ConnectorError::NotSupported {
message: format!("Payment sync after terminal status: {other_attempt_status} payment"),
connector: "redsys",
}),
}
}
fn construct_sync_request(
order_id: String,
transaction_type: String,
auth: RedsysAuthType,
) -> Result<Vec<u8>, Error> {
let transaction_data = RedsysSyncRequest {
ds_merchant_code: auth.merchant_id,
ds_terminal: auth.terminal_id,
ds_transaction_type: transaction_type,
ds_order: order_id.clone(),
};
let version = VersionData {
ds_version: DS_VERSION.to_owned(),
message: Message {
transaction: transaction_data,
},
};
let version_data = quick_xml::se::to_string(&version)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let signature = get_signature(&order_id, &version_data, auth.sha256_pwd.peek())?;
let messages = Messages {
version,
signature,
signature_version: SIGNATURE_VERSION.to_owned(),
};
let cdata = quick_xml::se::to_string(&messages)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let body = format!(
r#"<soapenv:Envelope xmlns:soapenv="{}" xmlns:web="{}"><soapenv:Header/><soapenv:Body><web:consultaOperaciones><cadenaXML><![CDATA[{}]]></cadenaXML></web:consultaOperaciones></soapenv:Body></soapenv:Envelope>"#,
common_utils::consts::SOAP_ENV_NAMESPACE,
XMLNS_WEB_URL,
cdata
);
Ok(body.as_bytes().to_vec())
}
pub fn build_payment_sync_request(item: &PaymentsSyncRouterData) -> Result<Vec<u8>, Error> {
let transaction_type = get_transaction_type(item.status, item.request.capture_method)?;
let auth = RedsysAuthType::try_from(&item.connector_auth_type)?;
let connector_transaction_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
construct_sync_request(connector_transaction_id, transaction_type, auth)
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename = "soapenv:envelope")]
pub struct RedsysSyncResponse {
#[serde(rename = "@xmlns:soapenv")]
xmlns_soapenv: String,
#[serde(rename = "@xmlns:soapenc")]
xmlns_soapenc: String,
#[serde(rename = "@xmlns:xsd")]
xmlns_xsd: String,
#[serde(rename = "@xmlns:xsi")]
xmlns_xsi: String,
#[serde(rename = "header")]
header: Option<SoapHeader>,
#[serde(rename = "body")]
body: SyncResponseBody,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SoapHeader {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub struct SyncResponseBody {
consultaoperacionesresponse: ConsultaOperacionesResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub struct ConsultaOperacionesResponse {
#[serde(rename = "@xmlns:p259")]
xmlns_p259: String,
consultaoperacionesreturn: ConsultaOperacionesReturn,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub struct ConsultaOperacionesReturn {
messages: MessagesResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub struct MessagesResponseData {
version: VersionResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub struct VersionResponseData {
#[serde(rename = "@ds_version")]
ds_version: String,
message: MessageResponseType,
}
// The response will contain either a sync transaction data or error data.
// Since the XML parser does not support enums for this case, we use Option to handle both scenarios.
// If both are present or both are absent, an error is thrown.
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageResponseType {
response: Option<RedsysSyncResponseData>,
errormsg: Option<SyncErrorCode>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SyncErrorCode {
ds_errorcode: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RedsysSyncResponseData {
ds_order: String,
ds_transactiontype: String,
ds_amount: Option<String>,
ds_currency: Option<String>,
ds_securepayment: Option<String>,
ds_state: Option<String>,
ds_response: Option<DsResponse>,
}
impl<F> TryFrom<ResponseRouterData<F, RedsysSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RedsysSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let message_data = item
.response
.body
.consultaoperacionesresponse
.consultaoperacionesreturn
.messages
.version
.message;
let (status, response) = match (message_data.response, message_data.errormsg) {
(Some(response), None) => {
if let Some(ds_response) = response.ds_response {
let status = get_redsys_attempt_status(
ds_response.clone(),
item.data.request.capture_method,
)?;
if connector_utils::is_payment_failure(status) {
let payment_response = Err(ErrorResponse {
status_code: item.http_code,
code: ds_response.0.clone(),
message: ds_response.0.clone(),
reason: Some(ds_response.0.clone()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
(status, payment_response)
} else {
let payment_response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.ds_order.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.ds_order.clone()),
incremental_authorization_allowed: None,
charges: None,
});
(status, payment_response)
}
} else {
// When the payment is in authentication or still processing
let payment_response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.ds_order.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.ds_order.clone()),
incremental_authorization_allowed: None,
charges: None,
});
(item.data.status, payment_response)
}
}
(None, Some(errormsg)) => {
let error_code = errormsg.ds_errorcode.clone();
let response = Err(ErrorResponse {
code: error_code.clone(),
message: error_code.clone(),
reason: Some(error_code),
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.status, response)
}
(Some(_), Some(_)) | (None, None) => {
Err(errors::ConnectorError::ResponseHandlingFailed)?
}
};
Ok(Self {
status,
response,
|
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,189
| null | null | null | null | null | null | null |
// Struct: Retrieve
// File: crates/hyperswitch_domain_models/src/router_flow_types/files.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct Retrieve
|
crates/hyperswitch_domain_models/src/router_flow_types/files.rs
|
hyperswitch_domain_models
|
struct_definition
|
Retrieve
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Function: insert
// File: crates/diesel_models/src/query/fraud_check.rs
// Module: diesel_models
pub fn insert(self, conn: &PgPooledConn) -> StorageResult<FraudCheck>
|
crates/diesel_models/src/query/fraud_check.rs
|
diesel_models
|
function_signature
| null | null | null | 45
|
insert
| null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Mollie
// File: crates/hyperswitch_connectors/src/connectors/mollie.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Mollie
|
crates/hyperswitch_connectors/src/connectors/mollie.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Mollie
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/datatrans.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/datatrans.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 39
| null | null | null | null | null | 1
| 0
|
// Implementation: impl api::RefundSync for for Bluesnap
// File: crates/hyperswitch_connectors/src/connectors/bluesnap.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Bluesnap
|
crates/hyperswitch_connectors/src/connectors/bluesnap.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Bluesnap
|
api::RefundSync for
| 0
| 0
| null | null |
// Struct: Response
// File: crates/hyperswitch_interfaces/src/types.rs
// Module: hyperswitch_interfaces
// Implementations: 0
pub struct Response
|
crates/hyperswitch_interfaces/src/types.rs
|
hyperswitch_interfaces
|
struct_definition
|
Response
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Function: log_refund_delete
// File: crates/router/src/services/kafka.rs
// Module: router
pub fn log_refund_delete(
&self,
delete_old_refund: &Refund,
tenant_id: TenantID,
) -> MQResult<()>
|
crates/router/src/services/kafka.rs
|
router
|
function_signature
| null | null | null | 58
|
log_refund_delete
| null | null | null | null | null | null |
// File: crates/connector_configs/src/lib.rs
// Module: connector_configs
pub mod common_config;
pub mod connector;
pub mod response_modifier;
pub mod transformer;
|
crates/connector_configs/src/lib.rs
|
connector_configs
|
full_file
| null | null | null | 35
| null | null | null | null | null | null | null |
// Function: get_org_auth_events_filters
// File: crates/router/src/analytics.rs
// Module: router
pub fn get_org_auth_events_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetAuthEventFilterRequest>,
) -> impl Responder
|
crates/router/src/analytics.rs
|
router
|
function_signature
| null | null | null | 70
|
get_org_auth_events_filters
| null | null | null | null | null | null |
// Struct: Celero
// File: crates/hyperswitch_connectors/src/connectors/celero.rs
// Module: hyperswitch_connectors
// Implementations: 17
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications
pub struct Celero
|
crates/hyperswitch_connectors/src/connectors/celero.rs
|
hyperswitch_connectors
|
struct_definition
|
Celero
| 17
|
[
"api::Payment",
"api::PaymentSession",
"api::ConnectorAccessToken",
"api::MandateSetup",
"api::PaymentAuthorize",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentVoid",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"api::PaymentToken",
"ConnectorCommon",
"ConnectorValidation",
"webhooks::IncomingWebhook",
"ConnectorSpecifications"
] | 126
| null | null | null | null | null | null | null |
// Struct: PayoutActionRequest
// File: crates/api_models/src/payouts.rs
// Module: api_models
// Implementations: 0
pub struct PayoutActionRequest
|
crates/api_models/src/payouts.rs
|
api_models
|
struct_definition
|
PayoutActionRequest
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Struct: SquareRefundResponseDetails
// File: crates/hyperswitch_connectors/src/connectors/square/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SquareRefundResponseDetails
|
crates/hyperswitch_connectors/src/connectors/square/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SquareRefundResponseDetails
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: Transaction
// File: crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct Transaction
|
crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
|
hyperswitch_domain_models
|
struct_definition
|
Transaction
| 0
|
[] | 42
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Braintree
// File: crates/hyperswitch_connectors/src/connectors/braintree.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Braintree
|
crates/hyperswitch_connectors/src/connectors/braintree.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Braintree
|
api::PaymentSync for
| 0
| 0
| null | null |
// File: crates/router/tests/connectors/adyenplatform.rs
// Module: router
|
crates/router/tests/connectors/adyenplatform.rs
|
router
|
full_file
| null | null | null | 19
| null | null | null | null | null | null | null |
// Struct: PaymentAttemptListData
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct PaymentAttemptListData<F>
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
struct_definition
|
PaymentAttemptListData
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Struct: DeutschebankTransactionInfo
// File: crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DeutschebankTransactionInfo
|
crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DeutschebankTransactionInfo
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: TransientDecryptDataRequest
// File: crates/common_utils/src/types/keymanager.rs
// Module: common_utils
// Implementations: 0
pub struct TransientDecryptDataRequest
|
crates/common_utils/src/types/keymanager.rs
|
common_utils
|
struct_definition
|
TransientDecryptDataRequest
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Function: from_option_secret_value
// File: crates/hyperswitch_domain_models/src/router_data.rs
// Module: hyperswitch_domain_models
pub fn from_option_secret_value(
value: Option<common_utils::pii::SecretSerdeValue>,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError>
|
crates/hyperswitch_domain_models/src/router_data.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 73
|
from_option_secret_value
| null | null | null | null | null | null |
// Struct: ProxyRequest
// File: crates/api_models/src/proxy.rs
// Module: api_models
// Implementations: 1
// Traits: common_utils::events::ApiEventMetric
pub struct ProxyRequest
|
crates/api_models/src/proxy.rs
|
api_models
|
struct_definition
|
ProxyRequest
| 1
|
[
"common_utils::events::ApiEventMetric"
] | 46
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_domain_models/src/merchant_account.rs
// Module: hyperswitch_domain_models
// Public functions: 7
// Public structs: 4
use common_utils::{
crypto::{OptionalEncryptableName, OptionalEncryptableValue},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
pii, type_name,
types::keymanager::{self},
};
use diesel_models::{
enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal,
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use router_env::logger;
use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: diesel_models::enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v1")]
#[derive(Clone)]
/// Set the private fields of merchant account
pub struct MerchantAccountSetter {
pub merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: diesel_models::enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
merchant_id: item.merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item.merchant_name,
merchant_details: item.merchant_details,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key: item.publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
primary_business_details: item.primary_business_details,
frm_routing_algorithm: item.frm_routing_algorithm,
created_at: item.created_at,
modified_at: item.modified_at,
intent_fulfillment_time: item.intent_fulfillment_time,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
/// 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,
}
#[cfg(feature = "v2")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
let MerchantAccountSetter {
id,
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
created_at,
modified_at,
organization_id,
recon_status,
is_platform_account,
version,
product_type,
merchant_account_type,
} = item;
Self {
id,
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
created_at,
modified_at,
organization_id,
recon_status,
is_platform_account,
version,
product_type,
merchant_account_type,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
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,
}
impl MerchantAccount {
#[cfg(feature = "v1")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.merchant_id
}
#[cfg(feature = "v2")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.id
}
/// Get the organization_id from MerchantAccount
pub fn get_org_id(&self) -> &common_utils::id_type::OrganizationId {
&self.organization_id
}
/// Get the merchant_details from MerchantAccount
pub fn get_merchant_details(&self) -> &OptionalEncryptableValue {
&self.merchant_details
}
/// Extract merchant_tax_registration_id from merchant_details
pub fn get_merchant_tax_registration_id(&self) -> Option<Secret<String>> {
self.merchant_details.as_ref().and_then(|details| {
details
.get_inner()
.peek()
.get("merchant_tax_registration_id")
.and_then(|id| id.as_str().map(|s| Secret::new(s.to_string())))
})
}
/// Check whether the merchant account is a platform account
pub fn is_platform_account(&self) -> bool {
matches!(
self.merchant_account_type,
common_enums::MerchantAccountType::Platform
)
}
}
#[cfg(feature = "v1")]
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum MerchantAccountUpdate {
Update {
merchant_name: OptionalEncryptableName,
merchant_details: OptionalEncryptableValue,
return_url: Option<String>,
webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
sub_merchants_enabled: Option<bool>,
parent_merchant_id: Option<common_utils::id_type::MerchantId>,
enable_payment_response_hash: Option<bool>,
payment_response_hash_key: Option<String>,
redirect_to_merchant_with_http_post: Option<bool>,
publishable_key: Option<String>,
locker_id: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
routing_algorithm: Option<serde_json::Value>,
primary_business_details: Option<serde_json::Value>,
intent_fulfillment_time: Option<i64>,
frm_routing_algorithm: Option<serde_json::Value>,
payout_routing_algorithm: Option<serde_json::Value>,
default_profile: Option<Option<common_utils::id_type::ProfileId>>,
payment_link_config: Option<serde_json::Value>,
pm_collect_link_config: Option<serde_json::Value>,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
},
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
UnsetDefaultProfile,
ModifiedAtUpdate,
ToPlatformAccount,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub enum MerchantAccountUpdate {
Update {
merchant_name: OptionalEncryptableName,
merchant_details: OptionalEncryptableValue,
publishable_key: Option<String>,
metadata: Option<Box<pii::SecretSerdeValue>>,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
},
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
ModifiedAtUpdate,
ToPlatformAccount,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
fn from(merchant_account_update: MerchantAccountUpdate) -> Self {
let now = date_time::now();
match merchant_account_update {
MerchantAccountUpdate::Update {
merchant_name,
merchant_details,
webhook_details,
return_url,
routing_algorithm,
sub_merchants_enabled,
parent_merchant_id,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
locker_id,
metadata,
primary_business_details,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
default_profile,
payment_link_config,
pm_collect_link_config,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
frm_routing_algorithm,
webhook_details,
routing_algorithm,
sub_merchants_enabled,
parent_merchant_id,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
locker_id,
metadata,
primary_business_details,
modified_at: now,
intent_fulfillment_time,
payout_routing_algorithm,
default_profile,
payment_link_config,
pm_collect_link_config,
storage_scheme: None,
organization_id: None,
is_recon_enabled: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::UnsetDefaultProfile => Self {
default_profile: Some(None),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ToPlatformAccount => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: Some(true),
product_type: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
fn from(merchant_account_update: MerchantAccountUpdate) -> Self {
let now = date_time::now();
match merchant_account_update {
MerchantAccountUpdate::Update {
merchant_name,
merchant_details,
publishable_key,
metadata,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
publishable_key,
metadata: metadata.map(|metadata| *metadata),
modified_at: now,
storage_scheme: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ToPlatformAccount => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: Some(true),
product_type: None,
},
}
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let id = self.get_id().to_owned();
let setter = diesel_models::merchant_account::MerchantAccountSetter {
id,
merchant_name: self.merchant_name.map(|name| name.into()),
merchant_details: self.merchant_details.map(|details| details.into()),
publishable_key: Some(self.publishable_key),
storage_scheme: self.storage_scheme,
metadata: self.metadata,
created_at: self.created_at,
modified_at: self.modified_at,
organization_id: self.organization_id,
recon_status: self.recon_status,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self.product_type,
merchant_account_type: self.merchant_account_type,
};
Ok(diesel_models::MerchantAccount::from(setter))
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let id = item.get_id().to_owned();
let publishable_key =
item.publishable_key
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
id,
merchant_name: item
.merchant_name
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
publishable_key,
storage_scheme: item.storage_scheme,
metadata: item.metadata,
created_at: item.created_at,
modified_at: item.modified_at,
organization_id: item.organization_id,
recon_status: item.recon_status,
is_platform_account: item.is_platform_account,
version: item.version,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type.unwrap_or_default(),
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting merchant data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::merchant_account::MerchantAccountNew {
id: self.id,
merchant_name: self.merchant_name.map(Encryption::from),
merchant_details: self.merchant_details.map(Encryption::from),
publishable_key: Some(self.publishable_key),
metadata: self.metadata,
created_at: now,
modified_at: now,
organization_id: self.organization_id,
recon_status: self.recon_status,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self
.product_type
.or(Some(common_enums::MerchantProductType::Orchestration)),
merchant_account_type: self.merchant_account_type,
})
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let setter = diesel_models::merchant_account::MerchantAccountSetter {
merchant_id: self.merchant_id,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
merchant_name: self.merchant_name.map(|name| name.into()),
merchant_details: self.merchant_details.map(|details| details.into()),
webhook_details: self.webhook_details,
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id: self.parent_merchant_id,
publishable_key: Some(self.publishable_key),
storage_scheme: self.storage_scheme,
locker_id: self.locker_id,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
primary_business_details: self.primary_business_details,
created_at: self.created_at,
modified_at: self.modified_at,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
organization_id: self.organization_id,
is_recon_enabled: self.is_recon_enabled,
default_profile: self.default_profile,
recon_status: self.recon_status,
payment_link_config: self.payment_link_config,
pm_collect_link_config: self.pm_collect_link_config,
version: self.version,
is_platform_account: self.is_platform_account,
product_type: self.product_type,
merchant_account_type: self.merchant_account_type,
};
Ok(diesel_models::MerchantAccount::from(setter))
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let merchant_id = item.get_id().to_owned();
let publishable_key =
item.publishable_key
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item
.merchant_name
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
frm_routing_algorithm: item.frm_routing_algorithm,
primary_business_details: item.primary_business_details,
created_at: item.created_at,
modified_at: item.modified_at,
intent_fulfillment_time: item.intent_fulfillment_time,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type.unwrap_or_default(),
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting merchant data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::merchant_account::MerchantAccountNew {
id: Some(self.merchant_id.clone()),
merchant_id: self.merchant_id,
merchant_name: self.merchant_name.map(Encryption::from),
merchant_details: self.merchant_details.map(Encryption::from),
return_url: self.return_url,
webhook_details: self.webhook_details,
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id: self.parent_merchant_id,
enable_payment_response_hash: Some(self.enable_payment_response_hash),
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: Some(self.redirect_to_merchant_with_http_post),
publishable_key: Some(self.publishable_key),
locker_id: self.locker_id,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
primary_business_details: self.primary_business_details,
created_at: now,
modified_at: now,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
organization_id: self.organization_id,
is_recon_enabled: self.is_recon_enabled,
default_profile: self.default_profile,
recon_status: self.recon_status,
payment_link_config: self.payment_link_config,
pm_collect_link_config: self.pm_collect_link_config,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self
.product_type
.or(Some(common_enums::MerchantProductType::Orchestration)),
merchant_account_type: self.merchant_account_type,
})
}
}
impl MerchantAccount {
pub fn get_compatible_connector(&self) -> Option<api_models::enums::Connector> {
let metadata: Option<api_models::admin::MerchantAccountMetadata> =
self.metadata.as_ref().and_then(|meta| {
meta.clone()
.parse_value("MerchantAccountMetadata")
.map_err(|err| logger::error!("Failed to deserialize {:?}", err))
.ok()
});
metadata.and_then(|a| a.compatible_connector)
}
}
|
crates/hyperswitch_domain_models/src/merchant_account.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 6,765
| null | null | null | null | null | null | null |
// Function: get_default_customer_billing_address
// File: crates/api_models/src/customers.rs
// Module: api_models
pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails>
|
crates/api_models/src/customers.rs
|
api_models
|
function_signature
| null | null | null | 45
|
get_default_customer_billing_address
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
// Module: hyperswitch_connectors
// Public functions: 3
// Public structs: 12
use std::collections::HashMap;
use api_models::admin::{AdditionalMerchantData, MerchantAccountData, MerchantRecipientData};
use common_enums::enums;
use common_utils::{id_type::MerchantId, request::Method, types::StringMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self},
};
//TODO: Fill the struct with respective fields
pub struct TokenioRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for TokenioRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenioPaymentsRequest {
pub initiation: PaymentInitiation,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInitiation {
pub ref_id: String,
pub remittance_information_primary: MerchantId,
pub amount: Amount,
pub local_instrument: LocalInstrument,
pub creditor: Creditor,
pub callback_url: Option<String>,
pub flow_type: FlowType,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
pub value: StringMajorUnit,
pub currency: enums::Currency,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LocalInstrument {
Sepa,
SepaInstant,
FasterPayments,
Elixir,
Bankgiro,
Plusgiro,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Creditor {
FasterPayments {
#[serde(rename = "sortCode")]
sort_code: Secret<String>,
#[serde(rename = "accountNumber")]
account_number: Secret<String>,
name: Secret<String>,
},
Sepa {
iban: Secret<String>,
name: Secret<String>,
},
SepaInstant {
iban: Secret<String>,
name: Secret<String>,
},
ElixirIban {
iban: Secret<String>,
name: Secret<String>,
},
ElixirAccount {
#[serde(rename = "accountNumber")]
account_number: Secret<String>,
name: Secret<String>,
},
Bankgiro {
#[serde(rename = "bankgiroNumber")]
bankgiro_number: Secret<String>,
name: Secret<String>,
},
Plusgiro {
#[serde(rename = "plusgiroNumber")]
plusgiro_number: Secret<String>,
name: Secret<String>,
},
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FlowType {
ApiOnly,
FullHostedPages,
EmbeddedHostedPages,
}
impl TryFrom<&TokenioRouterData<&PaymentsAuthorizeRouterData>> for TokenioPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &TokenioRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::OpenBanking(_) => {
let (local_instrument, creditor) = match item
.router_data
.additional_merchant_data
.as_ref()
.and_then(|data| match data {
AdditionalMerchantData::OpenBankingRecipientData(recipient_data) => {
match recipient_data {
MerchantRecipientData::AccountData(account_data) => {
Some(account_data)
}
_ => None,
}
}
}) {
Some(MerchantAccountData::FasterPayments {
account_number,
sort_code,
name,
..
}) => (
LocalInstrument::FasterPayments,
Creditor::FasterPayments {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::SepaInstant { iban, name, .. }) => (
LocalInstrument::SepaInstant,
Creditor::SepaInstant {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Sepa { iban, name, .. }) => (
LocalInstrument::Sepa,
Creditor::Sepa {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Iban { iban, name, .. }) => (
LocalInstrument::Sepa, // Assuming IBAN defaults to SEPA
Creditor::Sepa {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Elixir {
account_number,
iban,
name,
..
}) => {
if !iban.peek().is_empty() {
(
LocalInstrument::Elixir,
Creditor::ElixirIban {
iban: iban.clone(),
name: name.clone().into(),
},
)
} else {
(
LocalInstrument::Elixir,
Creditor::ElixirAccount {
account_number: account_number.clone(),
name: name.clone().into(),
},
)
}
}
Some(MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
}) => (
LocalInstrument::FasterPayments,
Creditor::FasterPayments {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Bankgiro { number, name, .. }) => (
LocalInstrument::Bankgiro,
Creditor::Bankgiro {
bankgiro_number: number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Plusgiro { number, name, .. }) => (
LocalInstrument::Plusgiro,
Creditor::Plusgiro {
plusgiro_number: number.clone(),
name: name.clone().into(),
},
),
None => {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "No valid payment method found in additional merchant data",
}
.into())
}
};
Ok(Self {
initiation: PaymentInitiation {
ref_id: utils::generate_12_digit_number().to_string(),
remittance_information_primary: item.router_data.merchant_id.clone(),
amount: Amount {
value: item.amount.clone(),
currency: item.router_data.request.currency,
},
local_instrument,
creditor,
callback_url: item.router_data.request.router_return_url.clone(),
flow_type: FlowType::FullHostedPages,
},
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct TokenioAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) private_key: Secret<String>,
pub(super) key_id: Secret<String>,
pub(super) key_algorithm: CryptoAlgorithm,
}
#[derive(Debug, Deserialize, PartialEq)]
pub enum CryptoAlgorithm {
RS256,
ES256,
#[serde(rename = "EdDSA")]
EDDSA,
}
impl TryFrom<&str> for CryptoAlgorithm {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s.to_uppercase().as_str() {
"RS256" | "rs256" => Ok(Self::RS256),
"ES256" | "es256" => Ok(Self::ES256),
"EDDSA" | "eddsa" | "EdDSA" => Ok(Self::EDDSA),
_ => Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Unsupported key algorithm. Select from RS256, ES256, EdDSA",
}
.into()),
}
}
}
impl TryFrom<&ConnectorAuthType> for TokenioAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
merchant_id: key1.to_owned(),
private_key: api_secret.to_owned(),
key_id: api_key.to_owned(),
key_algorithm: CryptoAlgorithm::try_from(key2.clone().expose().as_str())?,
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenioApiWrapper {
pub payment: PaymentResponse,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum TokenioPaymentsResponse {
Success(TokenioApiWrapper),
Error(TokenioErrorResponse),
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentResponse {
pub id: String,
pub status: PaymentStatus,
pub status_reason_information: Option<String>,
pub authentication: Option<Authentication>,
pub error_info: Option<ErrorInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
InitiationPending,
InitiationPendingRedirectAuth,
InitiationPendingRedirectAuthVerification,
InitiationPendingRedirectHp,
InitiationPendingRedemption,
InitiationPendingRedemptionVerification,
InitiationProcessing,
InitiationCompleted,
InitiationRejected,
InitiationRejectedInsufficientFunds,
InitiationFailed,
InitiationDeclined,
InitiationExpired,
InitiationNoFinalStatusAvailable,
SettlementInProgress,
SettlementCompleted,
SettlementIncomplete,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum Authentication {
RedirectUrl {
#[serde(rename = "redirectUrl")]
redirect_url: String,
},
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorInfo {
pub http_error_code: i32,
pub message: Option<String>,
pub token_external_error: Option<bool>,
pub token_trace_id: Option<String>,
}
impl From<TokenioPaymentsResponse> for common_enums::AttemptStatus {
fn from(response: TokenioPaymentsResponse) -> Self {
match response {
TokenioPaymentsResponse::Success(wrapper) => match wrapper.payment.status {
// Pending statuses - payment is still in progress
PaymentStatus::InitiationPending
| PaymentStatus::InitiationPendingRedirectAuth
| PaymentStatus::InitiationPendingRedirectAuthVerification
| PaymentStatus::InitiationPendingRedirectHp
| PaymentStatus::InitiationPendingRedemption
| PaymentStatus::InitiationPendingRedemptionVerification => {
Self::AuthenticationPending
}
// Success statuses
PaymentStatus::SettlementCompleted => Self::Charged,
// Settlement in progress - could map to different status based on business logic
PaymentStatus::SettlementInProgress => Self::Pending,
// Failure statuses
PaymentStatus::InitiationRejected
| PaymentStatus::InitiationFailed
| PaymentStatus::InitiationExpired
| PaymentStatus::InitiationRejectedInsufficientFunds
| PaymentStatus::InitiationDeclined => Self::Failure,
// Uncertain status
PaymentStatus::InitiationCompleted
| PaymentStatus::InitiationProcessing
| PaymentStatus::InitiationNoFinalStatusAvailable
| PaymentStatus::SettlementIncomplete => Self::Pending,
},
TokenioPaymentsResponse::Error(_) => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.clone());
let response = match item.response {
TokenioPaymentsResponse::Success(wrapper) => {
let payment = wrapper.payment;
if let common_enums::AttemptStatus::Failure = status {
Err(ErrorResponse {
code: payment
.error_info
.as_ref()
.map(|ei| ei.http_error_code.to_string())
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: payment
.error_info
.as_ref()
.and_then(|ei| ei.message.clone())
.or_else(|| payment.status_reason_information.clone())
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
payment
.error_info
.as_ref()
.and_then(|ei| ei.message.clone())
.or_else(|| payment.status_reason_information.clone())
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment.id.clone()),
redirection_data: Box::new(payment.authentication.as_ref().map(|auth| {
match auth {
Authentication::RedirectUrl { redirect_url } => {
RedirectForm::Form {
endpoint: redirect_url.to_string(),
method: Method::Get,
form_fields: HashMap::new(),
}
}
}
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
}
TokenioPaymentsResponse::Error(error_response) => Err(ErrorResponse {
code: error_response.get_error_code(),
message: error_response.get_message(),
reason: Some(error_response.get_message()),
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,
}),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct TokenioRefundRequest {
pub amount: StringMajorUnit,
}
impl<F> TryFrom<&TokenioRouterData<&RefundsRouterData<F>>> for TokenioRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenioRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum TokenioErrorResponse {
Json {
#[serde(rename = "errorCode")]
error_code: Option<String>,
message: Option<String>,
},
Text(String),
}
impl TokenioErrorResponse {
pub fn from_bytes(bytes: &[u8]) -> Self {
// First try to parse as JSON
if let Ok(json_response) = serde_json::from_slice::<Self>(bytes) {
json_response
} else {
// If JSON parsing fails, treat as plain text
let text = String::from_utf8_lossy(bytes).to_string();
Self::Text(text)
}
}
pub fn get_message(&self) -> String {
match self {
Self::Json {
message,
error_code,
} => message
.as_deref()
.or(error_code.as_deref())
.unwrap_or(NO_ERROR_MESSAGE)
.to_string(),
Self::Text(text) => text.clone(),
}
}
pub fn get_error_code(&self) -> String {
match self {
Self::Json { error_code, .. } => {
error_code.as_deref().unwrap_or(NO_ERROR_CODE).to_string()
}
Self::Text(_) => NO_ERROR_CODE.to_string(),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioWebhookEventType {
PaymentStatusChanged,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioWebhookPaymentStatus {
InitiationCompleted,
PaymentCompleted,
PaymentFailed,
PaymentCancelled,
InitiationRejected,
InitiationProcessing,
#[serde(other)]
Unknown,
}
// Base webhook payload structure
#[derive(Debug, Deserialize, Serialize)]
pub struct TokenioWebhookPayload {
#[serde(rename = "eventType", skip_serializing_if = "Option::is_none")]
pub event_type: Option<String>,
pub id: String,
#[serde(flatten)]
pub event_data: TokenioWebhookEventData,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TokenioWebhookEventData {
PaymentV2 { payment: TokenioPaymentObjectV2 },
}
// Payment v2 structures
#[derive(Debug, Deserialize, Serialize)]
pub struct TokenioPaymentObjectV2 {
pub id: String,
pub status: TokenioPaymentStatus,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioPaymentStatus {
InitiationCompleted,
PaymentCompleted,
PaymentFailed,
PaymentCancelled,
InitiationRejected,
InitiationProcessing,
InitiationPendingRedirectHp,
#[serde(other)]
Other,
}
|
crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,531
| null | null | null | null | null | null | null |
// Struct: PartnerConfigOverride
// File: crates/router/src/types/api/connector_onboarding/paypal.rs
// Module: router
// Implementations: 0
pub struct PartnerConfigOverride
|
crates/router/src/types/api/connector_onboarding/paypal.rs
|
router
|
struct_definition
|
PartnerConfigOverride
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Function: get_payment_attempt_from_object_reference_id
// File: crates/router/src/core/webhooks/incoming.rs
// Module: router
pub fn get_payment_attempt_from_object_reference_id(
state: &SessionState,
object_reference_id: webhooks::ObjectReferenceId,
merchant_context: &domain::MerchantContext,
) -> CustomResult<PaymentAttempt, errors::ApiErrorResponse>
|
crates/router/src/core/webhooks/incoming.rs
|
router
|
function_signature
| null | null | null | 81
|
get_payment_attempt_from_object_reference_id
| null | null | null | null | null | null |
// Function: delete_network_token_from_locker_and_token_service
// File: crates/router/src/core/payment_methods/network_tokenization.rs
// Module: router
pub fn delete_network_token_from_locker_and_token_service(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
payment_method_id: String,
network_token_locker_id: Option<String>,
network_token_requestor_reference_id: String,
merchant_context: &domain::MerchantContext,
) -> errors::RouterResult<DeleteCardResp>
|
crates/router/src/core/payment_methods/network_tokenization.rs
|
router
|
function_signature
| null | null | null | 122
|
delete_network_token_from_locker_and_token_service
| null | null | null | null | null | null |
// Function: recon_merchant_account_update
// File: crates/router/src/core/recon.rs
// Module: router
pub fn recon_merchant_account_update(
state: SessionState,
auth: authentication::AuthenticationData,
req: recon_api::ReconUpdateMerchantRequest,
) -> RouterResponse<api_types::MerchantAccountResponse>
|
crates/router/src/core/recon.rs
|
router
|
function_signature
| null | null | null | 71
|
recon_merchant_account_update
| null | null | null | null | null | null |
// Struct: GenerateReportRequest
// File: crates/api_models/src/analytics.rs
// Module: api_models
// Implementations: 0
pub struct GenerateReportRequest
|
crates/api_models/src/analytics.rs
|
api_models
|
struct_definition
|
GenerateReportRequest
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Struct: PaymentCreate
// File: crates/router/src/core/payments/operations/payment_create.rs
// Module: router
// Implementations: 1
pub struct PaymentCreate
|
crates/router/src/core/payments/operations/payment_create.rs
|
router
|
struct_definition
|
PaymentCreate
| 1
|
[] | 37
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 13
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{self, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, BrowserInformationData, PaymentsAuthorizeRequestData,
RouterData as _,
},
};
pub struct FlexitiRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for FlexitiRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct FlexitiPaymentsRequest {
merchant_order_id: Option<String>,
lang: String,
flow: FlexitiFlow,
amount_requested: FloatMajorUnit,
email: Option<Email>,
fname: Secret<String>,
billing_information: BillingInformation,
shipping_information: ShippingInformation,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FlexitiFlow {
#[serde(rename = "apply/buy")]
ApplyAndBuy,
Apply,
Buy,
}
#[derive(Debug, Serialize)]
pub struct BillingInformation {
first_name: Secret<String>,
last_name: Secret<String>,
address_1: Secret<String>,
address_2: Secret<String>,
city: Secret<String>,
postal_code: Secret<String>,
province: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ShippingInformation {
first_name: Secret<String>,
last_name: Secret<String>,
address_1: Secret<String>,
address_2: Secret<String>,
city: Secret<String>,
postal_code: Secret<String>,
province: Secret<String>,
}
impl TryFrom<&FlexitiRouterData<&PaymentsAuthorizeRouterData>> for FlexitiPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FlexitiRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
hyperswitch_domain_models::payment_method_data::PayLaterData::FlexitiRedirect { } => {
let shipping_address = item.router_data.get_shipping_address()?;
let shipping_information = ShippingInformation {
first_name: shipping_address.get_first_name()?.to_owned(),
last_name: shipping_address.get_last_name()?.to_owned(),
address_1: shipping_address.get_line1()?.to_owned(),
address_2: shipping_address.get_line2()?.to_owned(),
city: shipping_address.get_city()?.to_owned().into(),
postal_code: shipping_address.get_zip()?.to_owned(),
province: shipping_address.to_state_code()?,
};
let billing_information = BillingInformation {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
address_1: item.router_data.get_billing_line1()?,
address_2: item.router_data.get_billing_line2()?,
city: item.router_data.get_billing_city()?.into(),
postal_code: item.router_data.get_billing_zip()?,
province: item.router_data.get_billing_state_code()?,
};
Ok(Self {
merchant_order_id: item.router_data.request.merchant_order_reference_id.to_owned(),
lang: item.router_data.request.get_browser_info()?.get_language()?,
flow: FlexitiFlow::ApplyAndBuy,
amount_requested: item.amount.to_owned(),
email: item.router_data.get_optional_billing_email(),
fname: item.router_data.get_billing_first_name()?,
billing_information,
shipping_information,
})
},
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaSdk { .. } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AffirmRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::BreadpayRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AfterpayClearpayRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::PayBrightRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::WalleyRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AlmaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AtomeRedirect { } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("flexiti"),
))
}?,
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct FlexitiAccessTokenRequest {
client_id: Secret<String>,
client_secret: Secret<String>,
grant_type: FlexitiGranttype,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FlexitiGranttype {
Password,
RefreshToken,
ClientCredentials,
}
impl TryFrom<&types::RefreshTokenRouterData> for FlexitiAccessTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth_details = FlexitiAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
client_id: auth_details.client_id,
client_secret: auth_details.client_secret,
grant_type: FlexitiGranttype::ClientCredentials,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
// Auth Struct
pub struct FlexitiAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FlexitiAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_id: api_key.to_owned(),
client_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FlexitiAccessTokenResponse {
access_token: Secret<String>,
expires_in: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiPaymentsResponse {
redirection_url: url::Url,
online_order_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiSyncResponse {
transaction_id: String,
purchase: FlexitiPurchase,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiPurchase {
status: FlexitiPurchaseStatus,
}
// Since this is an alpha integration, we don't have access to all the status mapping. This needs to be updated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FlexitiPurchaseStatus {
Success,
Failed,
}
// Since this is an alpha integration, we don't have access to all the status mapping. This needs to be updated.
impl From<FlexitiPurchaseStatus> for common_enums::AttemptStatus {
fn from(item: FlexitiPurchaseStatus) -> Self {
match item {
FlexitiPurchaseStatus::Success => Self::Authorized,
FlexitiPurchaseStatus::Failed => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.purchase.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_owned(),
),
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,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.online_order_id.to_owned(),
),
redirection_data: Box::new(Some(RedirectForm::from((
item.response.redirection_url,
Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct FlexitiRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&FlexitiRouterData<&RefundsRouterData<F>>> for FlexitiRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &FlexitiRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FlexitiErrorResponse {
pub message: String,
pub error: String,
}
|
crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 2,921
| null | null | null | null | null | null | null |
// Struct: RevenueRecoveryRetriggerRequest
// File: crates/api_models/src/process_tracker/revenue_recovery.rs
// Module: api_models
// Implementations: 0
pub struct RevenueRecoveryRetriggerRequest
|
crates/api_models/src/process_tracker/revenue_recovery.rs
|
api_models
|
struct_definition
|
RevenueRecoveryRetriggerRequest
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Struct: PaymentMethodUpdateMems
// File: crates/diesel_models/src/kv.rs
// Module: diesel_models
// Implementations: 0
pub struct PaymentMethodUpdateMems
|
crates/diesel_models/src/kv.rs
|
diesel_models
|
struct_definition
|
PaymentMethodUpdateMems
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Function: update_feature
// File: crates/api_models/src/routing.rs
// Module: api_models
pub fn update_feature(
&mut self,
enabled_feature: DynamicRoutingFeatures,
dynamic_routing_type: DynamicRoutingType,
)
|
crates/api_models/src/routing.rs
|
api_models
|
function_signature
| null | null | null | 52
|
update_feature
| null | null | null | null | null | null |
// Function: get_optional_card_and_cvc
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router
pub fn get_optional_card_and_cvc(
&self,
) -> (Option<domain::CardDetail>, Option<masking::Secret<String>>)
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
function_signature
| null | null | null | 62
|
get_optional_card_and_cvc
| null | null | null | null | null | null |
// Function: get_resource_name
// File: crates/router/src/services/authorization/permissions.rs
// Module: router
pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> Option<&'static str>
|
crates/router/src/services/authorization/permissions.rs
|
router
|
function_signature
| null | null | null | 46
|
get_resource_name
| null | null | null | null | null | null |
// Implementation: impl NetworkTokenizationBuilder
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router
// Methods: 2 total (2 public)
impl NetworkTokenizationBuilder
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
impl_block
| null | null | null | 44
| null |
NetworkTokenizationBuilder
| null | 2
| 2
| null | null |
// Struct: ThreeDSRequestChallenge
// File: crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ThreeDSRequestChallenge
|
crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
|
ThreeDSRequestChallenge
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// File: crates/router/src/types/domain/types.rs
// Module: router
use ::payment_methods::state as pm_state;
use common_utils::types::keymanager::KeyManagerState;
pub use hyperswitch_domain_models::type_encryption::{
crypto_operation, AsyncLift, CryptoOperation, Lift, OptionalEncryptableJsonType,
};
use crate::routes::app;
impl From<&app::SessionState> for KeyManagerState {
fn from(state: &app::SessionState) -> Self {
let conf = state.conf.key_manager.get_inner();
Self {
global_tenant_id: state.conf.multitenancy.global_tenant.tenant_id.clone(),
tenant_id: state.tenant.tenant_id.clone(),
enabled: conf.enabled,
url: conf.url.clone(),
client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout,
#[cfg(feature = "km_forward_x_request_id")]
request_id: state.request_id,
#[cfg(feature = "keymanager_mtls")]
cert: conf.cert.clone(),
#[cfg(feature = "keymanager_mtls")]
ca: conf.ca.clone(),
infra_values: app::AppState::process_env_mappings(state.conf.infra_values.clone()),
}
}
}
impl From<&app::SessionState> for pm_state::PaymentMethodsState {
fn from(state: &app::SessionState) -> Self {
Self {
store: state.store.get_payment_methods_store(),
key_store: None,
key_manager_state: state.into(),
}
}
}
|
crates/router/src/types/domain/types.rs
|
router
|
full_file
| null | null | null | 317
| null | null | null | null | null | null | null |
// Struct: EliminationEventResponse
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
// Implementations: 0
pub struct EliminationEventResponse
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
|
EliminationEventResponse
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Function: get_connector_auth
// File: crates/router/src/utils/connector_onboarding.rs
// Module: router
pub fn get_connector_auth(
connector: enums::Connector,
connector_data: &settings::ConnectorOnboarding,
) -> RouterResult<types::ConnectorAuthType>
|
crates/router/src/utils/connector_onboarding.rs
|
router
|
function_signature
| null | null | null | 60
|
get_connector_auth
| null | null | null | null | null | null |
// Struct: AnalyticsMetadata
// File: crates/api_models/src/analytics.rs
// Module: api_models
// Implementations: 0
pub struct AnalyticsMetadata
|
crates/api_models/src/analytics.rs
|
api_models
|
struct_definition
|
AnalyticsMetadata
| 0
|
[] | 34
| null | null | null | null | null | null | null |
// File: crates/api_models/src/analytics/search.rs
// Module: api_models
// Public functions: 1
// Public structs: 12
use common_utils::{hashing::HashedString, types::TimeRange};
use masking::WithType;
use serde_json::Value;
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SearchFilters {
pub payment_method: Option<Vec<String>>,
pub currency: Option<Vec<String>>,
pub status: Option<Vec<String>>,
pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>,
pub search_tags: Option<Vec<HashedString<WithType>>>,
pub connector: Option<Vec<String>>,
pub payment_method_type: Option<Vec<String>>,
pub card_network: Option<Vec<String>>,
pub card_last_4: Option<Vec<String>>,
pub payment_id: Option<Vec<String>>,
pub amount: Option<Vec<u64>>,
pub customer_id: Option<Vec<String>>,
}
impl SearchFilters {
pub fn is_all_none(&self) -> bool {
self.payment_method.is_none()
&& self.currency.is_none()
&& self.status.is_none()
&& self.customer_email.is_none()
&& self.search_tags.is_none()
&& self.connector.is_none()
&& self.payment_method_type.is_none()
&& self.card_network.is_none()
&& self.card_last_4.is_none()
&& self.payment_id.is_none()
&& self.amount.is_none()
&& self.customer_id.is_none()
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetGlobalSearchRequest {
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
#[serde(default)]
pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchRequest {
pub offset: i64,
pub count: i64,
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
#[serde(default)]
pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchRequestWithIndex {
pub index: SearchIndex,
pub search_req: GetSearchRequest,
}
#[derive(
Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy, Eq, PartialEq,
)]
#[serde(rename_all = "snake_case")]
pub enum SearchIndex {
PaymentAttempts,
PaymentIntents,
Refunds,
Disputes,
SessionizerPaymentAttempts,
SessionizerPaymentIntents,
SessionizerRefunds,
SessionizerDisputes,
}
#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)]
pub enum SearchStatus {
Success,
Failure,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchResponse {
pub count: u64,
pub index: SearchIndex,
pub hits: Vec<Value>,
pub status: SearchStatus,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpenMsearchOutput {
#[serde(default)]
pub responses: Vec<OpensearchOutput>,
pub error: Option<OpensearchErrorDetails>,
}
#[derive(Debug, serde::Deserialize)]
#[serde(untagged)]
pub enum OpensearchOutput {
Success(OpensearchSuccess),
Error(OpensearchError),
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchError {
pub error: OpensearchErrorDetails,
pub status: u16,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchErrorDetails {
#[serde(rename = "type")]
pub error_type: String,
pub reason: String,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchSuccess {
pub hits: OpensearchHits,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchHits {
pub total: OpensearchResultsTotal,
pub hits: Vec<OpensearchHit>,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchResultsTotal {
pub value: u64,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchHit {
#[serde(rename = "_source")]
pub source: Value,
}
|
crates/api_models/src/analytics/search.rs
|
api_models
|
full_file
| null | null | null | 967
| null | null | null | null | null | null | null |
// Implementation: impl PaymentMetricsAccumulator
// File: crates/analytics/src/payments/accumulator.rs
// Module: analytics
// Methods: 1 total (1 public)
impl PaymentMetricsAccumulator
|
crates/analytics/src/payments/accumulator.rs
|
analytics
|
impl_block
| null | null | null | 44
| null |
PaymentMetricsAccumulator
| null | 1
| 1
| null | null |
// Function: refunds_retrieve_with_body
// File: crates/openapi/src/routes/refunds.rs
// Module: openapi
pub fn refunds_retrieve_with_body()
|
crates/openapi/src/routes/refunds.rs
|
openapi
|
function_signature
| null | null | null | 35
|
refunds_retrieve_with_body
| null | null | null | null | null | null |
// Function: server
// File: crates/router/src/routes/app.rs
// Module: router
pub fn server(state: AppState) -> Scope
|
crates/router/src/routes/app.rs
|
router
|
function_signature
| null | null | null | 29
|
server
| null | null | null | null | null | null |
// Struct: AcceptDisputeResponse
// File: crates/hyperswitch_domain_models/src/router_response_types/disputes.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct AcceptDisputeResponse
|
crates/hyperswitch_domain_models/src/router_response_types/disputes.rs
|
hyperswitch_domain_models
|
struct_definition
|
AcceptDisputeResponse
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Function: build_unified_connector_service_payment_method
// File: crates/router/src/core/unified_connector_service.rs
// Module: router
pub fn build_unified_connector_service_payment_method(
payment_method_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData,
payment_method_type: PaymentMethodType,
) -> CustomResult<payments_grpc::PaymentMethod, UnifiedConnectorServiceError>
|
crates/router/src/core/unified_connector_service.rs
|
router
|
function_signature
| null | null | null | 84
|
build_unified_connector_service_payment_method
| null | null | null | null | null | null |
// Struct: PayoutVendorAccountDetails
// File: crates/api_models/src/payouts.rs
// Module: api_models
// Implementations: 0
pub struct PayoutVendorAccountDetails
|
crates/api_models/src/payouts.rs
|
api_models
|
struct_definition
|
PayoutVendorAccountDetails
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Implementation: impl quote::ToTokens for for SchemaMeta
// File: crates/router_derive/src/macros/generate_schema.rs
// Module: router_derive
// Methods: 1 total (0 public)
impl quote::ToTokens for for SchemaMeta
|
crates/router_derive/src/macros/generate_schema.rs
|
router_derive
|
impl_block
| null | null | null | 54
| null |
SchemaMeta
|
quote::ToTokens for
| 1
| 0
| null | null |
// Implementation: impl ConnectorCommon for for Amazonpay
// File: crates/hyperswitch_connectors/src/connectors/amazonpay.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)
impl ConnectorCommon for for Amazonpay
|
crates/hyperswitch_connectors/src/connectors/amazonpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Amazonpay
|
ConnectorCommon for
| 5
| 0
| null | null |
// Function: new
// File: crates/hyperswitch_domain_models/src/relay.rs
// Module: hyperswitch_domain_models
pub fn new(
relay_request: &api_models::relay::RelayRequest,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> Self
|
crates/hyperswitch_domain_models/src/relay.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 72
|
new
| null | null | null | null | null | null |
// Struct: DisputeResponseData
// File: crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DisputeResponseData
|
crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DisputeResponseData
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: LineageIds
// File: crates/external_services/src/grpc_client.rs
// Module: external_services
// Implementations: 1
pub struct LineageIds
|
crates/external_services/src/grpc_client.rs
|
external_services
|
struct_definition
|
LineageIds
| 1
|
[] | 37
| null | null | null | null | null | null | null |
// Module Structure
// File: crates/hyperswitch_domain_models/src/router_response_types.rs
// Module: hyperswitch_domain_models
// Public submodules:
pub mod disputes;
pub mod fraud_check;
pub mod revenue_recovery;
pub mod subscriptions;
// Public exports:
pub use disputes::{
AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse,
SubmitEvidenceResponse,
};
|
crates/hyperswitch_domain_models/src/router_response_types.rs
|
hyperswitch_domain_models
|
module_structure
| null | null | null | 88
| null | null | null | null | null | 4
| 1
|
// Implementation: impl SerializableSecret for for i32
// File: crates/masking/src/serde.rs
// Module: masking
// Methods: 0 total (0 public)
impl SerializableSecret for for i32
|
crates/masking/src/serde.rs
|
masking
|
impl_block
| null | null | null | 46
| null |
i32
|
SerializableSecret for
| 0
| 0
| null | null |
// Implementation: impl Billwerk
// File: crates/hyperswitch_connectors/src/connectors/billwerk.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl Billwerk
|
crates/hyperswitch_connectors/src/connectors/billwerk.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 46
| null |
Billwerk
| null | 1
| 1
| null | null |
// Function: toggle_elimination_routing
// File: crates/router/src/routes/routing.rs
// Module: router
pub fn toggle_elimination_routing(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>,
path: web::Path<routing_types::ToggleDynamicRoutingPath>,
) -> impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| null | null | null | 82
|
toggle_elimination_routing
| null | null | null | null | null | null |
// Struct: CheckoutResponse
// File: crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CheckoutResponse
|
crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CheckoutResponse
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// File: crates/masking/src/lib.rs
// Module: masking
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))]
#![cfg_attr(docsrs, doc(cfg_hide(doc)))]
#![warn(missing_docs)]
//! Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped.
//! Secret-keeping library inspired by secrecy.
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
pub use zeroize::{self, DefaultIsZeroes, Zeroize as ZeroizableSecret};
mod strategy;
pub use strategy::{Strategy, WithType, WithoutType};
mod abs;
pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface, SwitchStrategy};
mod secret;
mod strong_secret;
#[cfg(feature = "serde")]
pub use secret::JsonMaskStrategy;
pub use secret::Secret;
pub use strong_secret::StrongSecret;
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
mod boxed;
#[cfg(feature = "bytes")]
mod bytes;
#[cfg(feature = "bytes")]
pub use self::bytes::SecretBytesMut;
#[cfg(feature = "alloc")]
mod string;
#[cfg(feature = "alloc")]
mod vec;
#[cfg(feature = "serde")]
mod serde;
#[cfg(feature = "serde")]
pub use crate::serde::{
masked_serialize, Deserialize, ErasedMaskSerialize, SerializableSecret, Serialize,
};
/// This module should be included with asterisk.
///
/// `use masking::prelude::*;`
pub mod prelude {
pub use super::{ExposeInterface, ExposeOptionInterface, PeekInterface};
}
#[cfg(feature = "diesel")]
mod diesel;
#[cfg(feature = "cassandra")]
mod cassandra;
pub mod maskable;
pub use maskable::*;
|
crates/masking/src/lib.rs
|
masking
|
full_file
| null | null | null | 402
| null | null | null | null | null | null | null |
// Function: get_payment_intent_metrics_info
// File: crates/analytics/src/utils.rs
// Module: analytics
pub fn get_payment_intent_metrics_info() -> Vec<NameDescription>
|
crates/analytics/src/utils.rs
|
analytics
|
function_signature
| null | null | null | 38
|
get_payment_intent_metrics_info
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/tokenio.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use std::{
sync::LazyLock,
time::{SystemTime, UNIX_EPOCH},
};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use common_enums::{enums, FeatureStatus, PaymentMethodType};
use common_utils::{
crypto::{self, VerifySignature},
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::Response,
webhooks,
};
use masking::{ExposeInterface, Mask, Secret};
use openssl::{ec::EcKey, hash::MessageDigest, pkey::PKey, rsa::Rsa, sign::Signer};
use transformers::{self as tokenio, TokenioPaymentStatus};
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Tokenio {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Tokenio {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
fn create_jwt_token(
&self,
auth: &tokenio::TokenioAuthType,
method: &str,
path: &str,
body: &RequestContent,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
// Create JWT header
let exp_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.as_millis()
+ 600_000; // 10 minutes
let header = serde_json::json!({
"alg": match auth.key_algorithm {
tokenio::CryptoAlgorithm::RS256 => "RS256",
tokenio::CryptoAlgorithm::ES256 => "ES256",
tokenio::CryptoAlgorithm::EDDSA => "EdDSA",
},
"exp": exp_time.to_string(), // Convert to string as Token.io expects
"mid": auth.merchant_id.clone().expose(),
"kid": auth.key_id.clone().expose(),
"method": method.to_uppercase(),
"host": connectors.tokenio.base_url.trim_start_matches("https://").trim_end_matches("/"),
"path": path,
"typ": "JWT",
});
// For GET requests, use detached JWT (no payload)
// For POST/PUT requests, include the request body as payload
let is_get_request = method.to_uppercase() == "GET";
let payload = if is_get_request {
None // No payload for GET requests (detached JWT)
} else {
// For non-GET requests, include the request body
match body {
RequestContent::Json(json_body) => Some(
serde_json::to_value(json_body)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
_ => Some(serde_json::json!({})),
}
};
// Use compact JSON serialization (no extra whitespace)
let encoded_header = self.base64url_encode(
serde_json::to_string(&header)
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.as_bytes(),
)?;
let (encoded_payload, signing_input) = match payload {
Some(p) => {
// Standard JWT with payload
let encoded_payload = self.base64url_encode(
serde_json::to_string(&p)
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.as_bytes(),
)?;
let signing_input = format!("{encoded_header}.{encoded_payload}");
(encoded_payload, signing_input)
}
None => {
// Detached JWT (GET requests) - sign only the header with a dot
let signing_input = format!("{encoded_header}.");
(String::new(), signing_input) // Empty payload for detached JWT
}
};
// Sign the JWT based on algorithm
let signature = match auth.key_algorithm {
tokenio::CryptoAlgorithm::RS256 => {
self.sign_rsa(&auth.private_key.clone().expose(), &signing_input)?
}
tokenio::CryptoAlgorithm::ES256 => {
self.sign_ecdsa(&auth.private_key.clone().expose(), &signing_input)?
}
tokenio::CryptoAlgorithm::EDDSA => {
self.sign_eddsa(&auth.private_key.clone().expose(), &signing_input)?
}
};
let encoded_signature = self.base64url_encode(&signature)?;
// Assemble JWT - for detached JWT, middle part is empty
Ok(format!(
"{encoded_header}.{encoded_payload}.{encoded_signature}",
))
}
fn base64url_encode(&self, data: &[u8]) -> CustomResult<String, errors::ConnectorError> {
Ok(URL_SAFE_NO_PAD.encode(data))
}
fn sign_rsa(
&self,
private_key_pem: &str,
data: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let rsa = Rsa::private_key_from_pem(private_key_pem.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let pkey =
PKey::from_rsa(rsa).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let mut signer = Signer::new(MessageDigest::sha256(), &pkey)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
signer
.update(data.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let signature = signer
.sign_to_vec()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(signature)
}
fn sign_ecdsa(
&self,
private_key_pem: &str,
data: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let ec_key = EcKey::private_key_from_pem(private_key_pem.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let pkey = PKey::from_ec_key(ec_key)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let mut signer = Signer::new(MessageDigest::sha256(), &pkey)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
signer
.update(data.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let signature = signer
.sign_to_vec()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(signature)
}
fn sign_eddsa(
&self,
private_key_pem: &str,
data: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let pkey = PKey::private_key_from_pem(private_key_pem.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let mut signer = Signer::new_without_digest(&pkey)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
signer
.update(data.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let signature = signer
.sign_to_vec()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(signature)
}
}
impl api::Payment for Tokenio {}
impl api::PaymentSession for Tokenio {}
impl api::ConnectorAccessToken for Tokenio {}
impl api::MandateSetup for Tokenio {}
impl api::PaymentAuthorize for Tokenio {}
impl api::PaymentSync for Tokenio {}
impl api::PaymentCapture for Tokenio {}
impl api::PaymentVoid for Tokenio {}
impl api::Refund for Tokenio {}
impl api::RefundExecute for Tokenio {}
impl api::RefundSync for Tokenio {}
impl api::PaymentToken for Tokenio {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Tokenio
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Tokenio
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
// Basic headers - JWT will be added in individual build_request methods
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
Ok(header)
}
}
impl ConnectorCommon for Tokenio {
fn id(&self) -> &'static str {
"tokenio"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.tokenio.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: tokenio::TokenioErrorResponse = res
.response
.parse_struct("TokenioErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.get_error_code(),
message: response.get_message(),
reason: Some(response.get_message()),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Tokenio {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Tokenio {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Tokenio {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Tokenio {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Tokenio {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = self.base_url(connectors);
Ok(format!("{base_url}/v2/payments"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = tokenio::TokenioRouterData::from((amount, req));
let connector_req = tokenio::TokenioPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth = tokenio::TokenioAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let url = self.get_url(req, connectors)?;
let body = self.get_request_body(req, connectors)?;
// Create JWT for authentication
let jwt = self.create_jwt_token(&auth, "POST", "/v2/payments", &body, connectors)?;
// Build headers with JWT authorization
let headers = vec![
(
headers::CONTENT_TYPE.to_string(),
"application/json".to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {jwt}").into_masked(),
),
];
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&url)
.attach_default_headers()
.headers(headers)
.set_body(body)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: tokenio::TokenioPaymentsResponse = res
.response
.parse_struct("Tokenio PaymentsAuthorizeResponse")
.change_context(errors::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,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tokenio {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
// For GET requests, we need JWT with detached format (no body)
let auth = tokenio::TokenioAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
// Use empty RequestContent for GET requests - the create_jwt_token method
// will handle this properly by creating detached JWT
let empty_body = RequestContent::Json(Box::new(serde_json::json!({})));
let path = format!(
"/v2/payments/{}",
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
);
let jwt = self.create_jwt_token(&auth, "GET", &path, &empty_body, connectors)?;
let headers = vec![
(
headers::CONTENT_TYPE.to_string(),
"application/json".to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {jwt}").into_masked(),
),
];
Ok(headers)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let base_url = self.base_url(connectors);
Ok(format!("{base_url}/v2/payments/{connector_payment_id}"))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&self.get_url(req, connectors)?)
.attach_default_headers()
.headers(self.get_headers(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: tokenio::TokenioPaymentsResponse = res
.response
.parse_struct("tokenio TokenioPaymentsResponse")
.change_context(errors::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,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Tokenio {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Tokenio".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Tokenio {
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "Tokenio".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tokenio {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "Tokenio".to_string(),
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Tokenio {
fn build_request(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund Sync".to_string(),
connector: "Tokenio".to_string(),
}
.into())
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Tokenio {
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_payload: tokenio::TokenioWebhookPayload = request
.body
.parse_struct("TokenioWebhookPayload")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match &webhook_payload.event_data {
tokenio::TokenioWebhookEventData::PaymentV2 { payment } => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(payment.id.clone()),
))
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
// Check token-event header first
let event_type = if let Some(header_value) = request.headers.get("token-event") {
header_value
.to_str()
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?
.to_string()
} else {
// Fallback to parsing body for eventType field
let webhook_payload: tokenio::TokenioWebhookPayload = request
.body
.parse_struct("TokenioWebhookPayload")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
webhook_payload
.event_type
.ok_or(errors::ConnectorError::WebhookEventTypeNotFound)?
};
match event_type.as_str() {
"PAYMENT_STATUS_CHANGED" => {
let webhook_payload: tokenio::TokenioWebhookPayload = request
.body
.parse_struct("TokenioWebhookPayload")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let tokenio::TokenioWebhookEventData::PaymentV2 { payment } =
&webhook_payload.event_data;
match payment.status {
TokenioPaymentStatus::InitiationCompleted => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
TokenioPaymentStatus::PaymentCompleted => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
TokenioPaymentStatus::PaymentFailed => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
TokenioPaymentStatus::PaymentCancelled => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentCancelled)
}
TokenioPaymentStatus::InitiationRejected => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
TokenioPaymentStatus::InitiationProcessing => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
TokenioPaymentStatus::InitiationPendingRedirectHp => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
TokenioPaymentStatus::Other => {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
_ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook_payload: tokenio::TokenioWebhookPayload = request
.body
.parse_struct("TokenioWebhookPayload")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(webhook_payload))
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await?;
// Convert UTF-8 bytes back to base64url string
let base64url_string = String::from_utf8(connector_webhook_secrets.secret)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed to convert public key bytes to base64url string")?;
// Decode base64url string to actual ED25519 key bytes
let public_key_bytes = URL_SAFE_NO_PAD
.decode(&base64url_string)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed to decode base64url public key to ED25519 bytes")?;
// Extract the signature from token-signature header
let signature_header = request
.headers
.get("token-signature")
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?
.to_str()
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
.attach_printable("Failed to convert token-signature header to string")?;
// Decode the base64url signature to bytes
let signature_bytes = URL_SAFE_NO_PAD
.decode(signature_header)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
.attach_printable("Failed to decode base64url signature")?;
// Get the raw message body (this is what Token.io signed)
let message_bytes = request.body;
// Use ED25519 to verify the signature
let ed25519 = crypto::Ed25519;
let is_valid = ed25519
.verify_signature(
&public_key_bytes,
&signature_bytes, // ED25519 signature (64 bytes)
message_bytes, // Raw webhook body
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("ED25519 signature verification failed")?;
Ok(is_valid)
}
}
static TOKENIO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut tokenio_supported_payment_methods = SupportedPaymentMethods::new();
// Open Banking - SEPA
tokenio_supported_payment_methods.add(
enums::PaymentMethod::OpenBanking,
PaymentMethodType::OpenBankingPIS,
PaymentMethodDetails {
mandates: FeatureStatus::NotSupported,
refunds: FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
tokenio_supported_payment_methods
});
static TOKENIO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Token.io",
description: "Token.io is a financial technology company that provides Open Banking and real-time payment solutions across Europe. They enable secure bank-to-bank transfers using various payment rails including SEPA, Faster Payments, and other regional payment systems.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static TOKENIO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Tokenio {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&TOKENIO_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*TOKENIO_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&TOKENIO_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/tokenio.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 6,277
| 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.