text string | file_path string | module string | type string | tokens int64 | language string | struct_name string | type_name string | trait_name string | impl_type string | function_name string | source string | section string | keys list | macro_type string | url string | title string | chunk_index int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
impl ApiEventMetric for FxExchangeRatesCacheEntry {} | crates/router/src/utils/currency.rs | router | impl_block | 12 | rust | null | FxExchangeRatesCacheEntry | ApiEventMetric for | impl ApiEventMetric for for FxExchangeRatesCacheEntry | null | null | null | null | null | null | null | null |
impl IncomingWebhook for Zsl {
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(notif.mer_ref),
))
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(get_status(notif.status))
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let response = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(Box::new(response))
}
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
_connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_account_details = connector_account_details
.parse_value::<ConnectorAuthType>("ConnectorAuthType")
.change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)?;
let auth_type = zsl::ZslAuthType::try_from(&connector_account_details)?;
let key = auth_type.api_key.expose();
let mer_id = auth_type.merchant_id.expose();
let webhook_response = get_webhook_object_from_body(request.body)?;
let signature = zsl::calculate_signature(
webhook_response.enctype,
zsl::ZslSignatureType::WebhookSignature {
status: webhook_response.status,
txn_id: webhook_response.txn_id,
txn_date: webhook_response.txn_date,
paid_ccy: webhook_response.paid_ccy.to_string(),
paid_amt: webhook_response.paid_amt,
mer_ref: webhook_response.mer_ref,
mer_id,
key,
},
)?;
Ok(signature.eq(&webhook_response.signature))
}
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
Ok(ApplicationResponse::TextPlain("CALLBACK-OK".to_string()))
}
} | crates/hyperswitch_connectors/src/connectors/zsl.rs | hyperswitch_connectors | impl_block | 655 | rust | null | Zsl | IncomingWebhook for | impl IncomingWebhook for for Zsl | null | null | null | null | null | null | null | null |
Web Documentation: Subscriptions | Hyperswitch
# Type: Web Doc
Hyperswitch enables you to work with your preferred subscription provider while having the flexibility to connect with multiple payment processors and payment methods. The benefits you gain by using Hyperswitch integration as a supplement to your Subscription Solution Provider are as follows:
Flexibility with Payment Processors
Choose any payment processor based on better costs or authorization rates.
Global Market Expansion
Integrate local payment methods to tap into global markets with ease.
Optimized Recurring Payments
Smart routing across multiple payment processors improves recurring payment success rates.
Unified Payment Management
A single solution for managing:
One-time payments
(e-commerce use cases)
Recurring payments
(subscription-based use cases)
What subscription providers do we support?
All major Subscription Solution Providers offer integration points to manage payments with external payment processors. And the integration solution proposed below should work universal across any subscription provider.
We also support
Kill Bill
(an open source subscription solution provider) via a direct
Plugin
.
Use cases supported
User flow 1 -
Plan First, Payment Later
User selects a plan followed by selecting the payment method and adding the payment method details to make the payment and start subscription.
User flow 2 -
Payment First, Plan Later
User selects a payment method and adds the payment method details which are saved. User finally selects the plan to start the subscription
Use cases common to both user flows
Subscription management portal
Subscription payment retries
Subscription reminder emails
User flow-1
User selects a plan followed by selecting the payment method and adding the payment method details to start subscription. This flow can be broken into 5 parts
Integration and set up
- Merchants will setup their account and generate API keys with the subscription provider and Hyperswitch as well as integrate with both of them. Merchants will set up their plans with the subscription provider and set up their payment providers with Hyperswitch.
Retrieve plans and create subscription
- Merchants will retrieve the eligible plans and display them on their website. The customer will select one of the plans shown to them. Merchant will use the selected plan to create a customer and a subscription with the subscription provider.
Collect payment method details
- Once the subscription is created and the key fields are received by the merchant, they'll initiate a Payments create call with Hyperswitch and load the payment SDK on their website (
more on SDK integration
) to collect payment details from the customer
Make payment and return invoice
- Using the payment details entered by the user the merchant will make a payment with Hyperswitch and create a mandate (
more details
). The subscription is marked as active upon successful payment and the invoice with the customer.
In case the subscription start date is in future and the customer need not be charged immediately then the merchant should initiate a $0 mandate with Hyperswitch (
more details
).
Make MIT transactions
User flow-2
User selects a payment method and adds the payment method details which are saved. User finally selects the plan to start the subscription. This flow can be broken into 5 parts
Integration and set up
- Merchants will setup their account and generate API keys with the subscription provider and Hyperswitch as well as integrate with both of them. Merchants will set up their plans with the subscription provider and set up their payment providers with Hyperswitch.
Collect and store payment method details
- Merchant will initiate a Payments create call with Hyperswitch and load the payment SDK on their website (
more on SDK integration
) to collect payment details from the customer.
Merchant will create a customer with the subscription provider
Merchant will initiate a $0 mandate with Hyperswitch (
more details
) to validate and store the payment details and create a mandate with Hyperswitch (using the same customer ID).
Retrieve plans and create subscription
- Merchants will retrieve the eligible plans and display them on their website. The customer will select one of the plans shown to them. Merchant will use the selected plan to create a subscription with the subscription provider.
Make payment and return invoice
- Using the mandate ID created earlier the merchant will make a payment with Hyperswitch. The subscription is marked as active upon successful payment and the invoice with the customer.
In case the subscription start date is in future and the customer need not be charged immediately then no payment is inittaed with Hyperswitch
Make MIT transactions
Subscription management portal
The customer-facing subscription management interface allows the customers to modify their billing address, add new payment method details for subscripotion payments and cancel subscription. If a merchant offers a subscription management portal then here's how Hyperswitch can support:
User updates billing address
- The merchant will update the new billing address with both Hyperswitch and the subscription provider using the customer ID.
User updates payment method details
- The merchant will load Hyperswitch SDK to allow the user to select the payment method and add the relevant payment method details. Merchant will validate and add this payment method with Hyperswitch using $0 mandate and create a new mandate.
User cancels subscriptions
- The merchant will revoke the mandate with Hyperswitch post which they will cancel the subscription with the subscription provider.
Subscription payment retries
The payment made for subscriptions can fail
When customer is present in the flow
- The user will retry the payment using same or different payment method
When customer is not present in the flow
- Once the merchant receives payment failed notification from Hyperswitch, they need to update the same with their subscription provider. All subscription providers have their own retry logics (default or configured by the merchant). Their retry logic will then send retry payment webhooks to the merchant. The merchant needs to consume the webhook and retrigger the payment with Hyperswitch (
more details
)
Subscription reminder emails
The merchant can use the Hyperswitch Payment links when sending email reminders to customers who failed to make their subscription payments. Here's how it'll work:
The customer is redirected to the payment link hosted page (with a validity of 15-mins) which allows them to make the payment using any payment option
Once the payment is successful, the merchant should mark the invoice as paid with their subscription provider and return the invoice to the customer
FAQs
Can I bring in my own subscription provider ?
Yes, we support any subscription provider using the above framework.
Can I process both one-time payments and recurring payments via the same setup?
Yes, once you're integrated with Hyperswitch, you'll be able to process both one-time payments and recurring payments.
10 months ago
Was this helpful? | https://docs.hyperswitch.io/explore-hyperswitch/payment-orchestration/subscriptions | null | web_doc_file | 1,339 | doc | null | null | null | null | null | web | null | null | null | https://docs.hyperswitch.io/explore-hyperswitch/payment-orchestration/subscriptions | Subscriptions | Hyperswitch | null |
impl api::MandateSetup for Tsys {} | crates/hyperswitch_connectors/src/connectors/tsys.rs | hyperswitch_connectors | impl_block | 11 | rust | null | Tsys | api::MandateSetup for | impl api::MandateSetup for for Tsys | null | null | null | null | null | null | null | null |
pub struct AdyenplatformInstantStatus {
status: Option<InstantPriorityStatus>,
estimated_arrival_time: Option<String>,
} | crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs | hyperswitch_connectors | struct_definition | 27 | rust | AdyenplatformInstantStatus | null | null | null | null | null | null | null | null | null | null | null |
pub struct CreateUserAuthenticationMethodRequest {
pub owner_id: String,
pub owner_type: common_enums::Owner,
pub auth_method: AuthConfig,
pub allow_signup: bool,
pub email_domain: Option<String>,
} | crates/api_models/src/user.rs | api_models | struct_definition | 49 | rust | CreateUserAuthenticationMethodRequest | null | null | null | null | null | null | null | null | null | null | null |
pub struct UrlDetails {
pub success_url: String,
pub failure_url: String,
pub pending_url: String,
} | crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs | hyperswitch_connectors | struct_definition | 27 | rust | UrlDetails | null | null | null | null | null | null | null | null | null | null | null |
impl api::Refund for Custombilling {} | crates/hyperswitch_connectors/src/connectors/custombilling.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Custombilling | api::Refund for | impl api::Refund for for Custombilling | null | null | null | null | null | null | null | null |
pub struct PaymentIntentMetricRow {
pub status: Option<DBEnumWrapper<storage_enums::IntentStatus>>,
pub currency: Option<DBEnumWrapper<storage_enums::Currency>>,
pub profile_id: Option<String>,
pub connector: Option<String>,
pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub card_network: Option<String>,
pub merchant_id: Option<String>,
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
pub first_attempt: Option<i64>,
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub start_bucket: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub end_bucket: Option<PrimitiveDateTime>,
} | crates/analytics/src/payment_intents/metrics.rs | analytics | struct_definition | 226 | rust | PaymentIntentMetricRow | null | null | null | null | null | null | null | null | null | null | null |
impl<'a> NetworkTokenizationBuilder<'a, CardStored> {
pub fn set_stored_token_response(
self,
store_token_response: &'a StoreLockerResponse,
) -> NetworkTokenizationBuilder<'a, CardTokenStored> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
card_tokenized: true,
stored_token: Some(&store_token_response.store_token_resp),
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_card: self.stored_card,
payment_method_response: self.payment_method_response,
error_code: self.error_code,
error_message: self.error_message,
}
}
} | crates/router/src/core/payment_methods/tokenize/card_executor.rs | router | impl_block | 160 | rust | null | NetworkTokenizationBuilder | null | impl NetworkTokenizationBuilder | null | null | null | null | null | null | null | null |
impl DummySignal {
/// Dummy handler for signals in windows (empty)
pub fn handle(&self) -> Self {
self.clone()
}
/// Hollow implementation, for windows compatibility
pub fn close(self) {}
} | crates/common_utils/src/signals.rs | common_utils | impl_block | 48 | rust | null | DummySignal | null | impl DummySignal | null | null | null | null | null | null | null | null |
impl api::RefundExecute for Nuvei {} | crates/hyperswitch_connectors/src/connectors/nuvei.rs | hyperswitch_connectors | impl_block | 11 | rust | null | Nuvei | api::RefundExecute for | impl api::RefundExecute for for Nuvei | null | null | null | null | null | null | null | null |
pub struct SmartRetriedAmountAccumulator {
pub amount: Option<i64>,
pub amount_without_retries: Option<i64>,
} | crates/analytics/src/payment_intents/accumulator.rs | analytics | struct_definition | 32 | rust | SmartRetriedAmountAccumulator | null | null | null | null | null | null | null | null | null | null | null |
impl FeatureMatrix {
pub fn server(state: AppState) -> Scope {
web::scope("/feature_matrix")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::get().to(feature_matrix::fetch_feature_matrix)))
}
} | crates/router/src/routes/app.rs | router | impl_block | 57 | rust | null | FeatureMatrix | null | impl FeatureMatrix | null | null | null | null | null | null | null | null |
pub async fn perform_locking_action<A>(
self,
state: &A,
merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<()>
where
A: SessionStateInfo,
{
match self {
Self::HoldMultiple { inputs } => {
let lock_retries = inputs
.iter()
.find_map(|input| input.override_lock_retries)
.unwrap_or(state.conf().lock_settings.lock_retries);
let request_id = state.get_request_id();
let redis_lock_expiry_seconds =
state.conf().lock_settings.redis_lock_expiry_seconds;
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_key_values = inputs
.iter()
.map(|input| input.get_redis_locking_key(&merchant_id))
.map(|key| (RedisKey::from(key.as_str()), request_id.clone()))
.collect::<Vec<_>>();
for _retry in 0..lock_retries {
let results: Vec<redis::SetGetReply<_>> = redis_conn
.set_multiple_keys_if_not_exists_and_get_values(
&redis_key_values,
Some(i64::from(redis_lock_expiry_seconds)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let lock_aqcuired = results.iter().all(|res| {
// each redis value must match the request_id
// if even 1 does match, the lock is not acquired
*res.get_value() == request_id
});
if lock_aqcuired {
logger::info!("Lock acquired for locking inputs {:?}", inputs);
return Ok(());
}
}
Err(report!(errors::ApiErrorResponse::ResourceBusy))
}
Self::Hold { input } => {
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_locking_key = input.get_redis_locking_key(&merchant_id);
let delay_between_retries_in_milliseconds = state
.conf()
.lock_settings
.delay_between_retries_in_milliseconds;
let redis_lock_expiry_seconds =
state.conf().lock_settings.redis_lock_expiry_seconds;
let lock_retries = input
.override_lock_retries
.unwrap_or(state.conf().lock_settings.lock_retries);
for _retry in 0..lock_retries {
let redis_lock_result = redis_conn
.set_key_if_not_exists_with_expiry(
&redis_locking_key.as_str().into(),
state.get_request_id(),
Some(i64::from(redis_lock_expiry_seconds)),
)
.await;
match redis_lock_result {
Ok(redis::SetnxReply::KeySet) => {
logger::info!("Lock acquired for locking input {:?}", input);
tracing::Span::current()
.record("redis_lock_acquired", redis_locking_key);
return Ok(());
}
Ok(redis::SetnxReply::KeyNotSet) => {
logger::info!(
"Lock busy by other request when tried for locking input {:?}",
input
);
actix_time::sleep(tokio::time::Duration::from_millis(u64::from(
delay_between_retries_in_milliseconds,
)))
.await;
}
Err(err) => {
return Err(err)
.change_context(errors::ApiErrorResponse::InternalServerError)
}
}
}
Err(report!(errors::ApiErrorResponse::ResourceBusy))
}
Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()),
}
} | crates/router/src/core/api_locking.rs | router | function_signature | 788 | rust | null | null | null | null | perform_locking_action | null | null | null | null | null | null | null |
pub async fn decide_action_type(
state: &SessionState,
is_connector_agnostic_mit_enabled: Option<bool>,
is_network_tokenization_enabled: bool,
payment_method_info: &domain::PaymentMethod,
filtered_nt_supported_connectors: Vec<api::ConnectorRoutingData>, //network tokenization supported connectors
) -> Option<ActionType> {
match (
is_network_token_with_network_transaction_id_flow(
is_connector_agnostic_mit_enabled,
is_network_tokenization_enabled,
payment_method_info,
),
!filtered_nt_supported_connectors.is_empty(),
) {
(IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id), true) => {
if let Ok((token_exp_month, token_exp_year)) =
network_tokenization::do_status_check_for_network_token(state, payment_method_info)
.await
{
Some(ActionType::NetworkTokenWithNetworkTransactionId(
NTWithNTIRef {
token_exp_month,
token_exp_year,
network_transaction_id,
},
))
} else {
None
}
}
(IsNtWithNtiFlow::NtWithNtiSupported(_), false)
| (IsNtWithNtiFlow::NTWithNTINotSupported, _) => None,
}
} | crates/router/src/core/payments.rs | router | function_signature | 279 | rust | null | null | null | null | decide_action_type | null | null | null | null | null | null | null |
OpenAPI Block Path: paths."/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/toggle"
{
"post": {
"tags": [
"Routing"
],
"summary": "Routing - Toggle success based dynamic routing for profile",
"description": "Create a success based dynamic routing algorithm",
"operationId": "Toggle success based dynamic routing algorithm",
"parameters": [
{
"name": "account_id",
"in": "path",
"description": "Merchant id",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "profile_id",
"in": "path",
"description": "Profile id under which Dynamic routing needs to be toggled",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "enable",
"in": "query",
"description": "Feature to enable for success based routing",
"required": true,
"schema": {
"$ref": "#/components/schemas/DynamicRoutingFeatures"
}
}
],
"responses": {
"200": {
"description": "Routing Algorithm created",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RoutingDictionaryRecord"
}
}
}
},
"400": {
"description": "Request body is malformed"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Resource missing"
},
"422": {
"description": "Unprocessable request"
},
"500": {
"description": "Internal server error"
}
},
"security": [
{
"api_key": []
},
{
"jwt_key": []
}
]
}
} | ./hyperswitch/api-reference/v1/openapi_spec_v1.json | null | openapi_block | 431 | .json | null | null | null | null | null | openapi_spec | paths | [
"/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/toggle"
] | null | null | null | null |
pub struct AwsSes {
sender: String,
ses_config: SESConfig,
settings: EmailSettings,
} | crates/external_services/src/email/ses.rs | external_services | struct_definition | 25 | rust | AwsSes | null | null | null | null | null | null | null | null | null | null | null |
pub struct MerchantInitiatedTransaction {
reason: Option<String>,
previous_transaction_id: Option<Secret<String>>,
//Required for recurring mandates payment
original_authorized_amount: Option<String>,
} | crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs | hyperswitch_connectors | struct_definition | 41 | rust | MerchantInitiatedTransaction | null | null | null | null | null | null | null | null | null | null | null |
pub async fn add_card_to_hs_locker(
state: &routes::SessionState,
payload: &payment_methods::StoreLockerReq,
customer_id: &id_type::CustomerId,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let db = &*state.store;
let stored_card_response = if !locker.mock_locker {
let request = payment_methods::mk_add_locker_request_hs(
jwekey,
locker,
payload,
locker_choice,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await?;
call_locker_api::<payment_methods::StoreCardResp>(
state,
request,
"add_card_to_hs_locker",
Some(locker_choice),
)
.await
.change_context(errors::VaultError::SaveCardFailed)?
} else {
let card_id = generate_id(consts::ID_LENGTH, "card");
mock_call_to_locker_hs(db, &card_id, payload, None, None, Some(customer_id)).await?
};
let stored_card = stored_card_response
.payload
.get_required_value("StoreCardRespPayload")
.change_context(errors::VaultError::SaveCardFailed)?;
Ok(stored_card)
} | crates/router/src/core/payment_methods/cards.rs | router | function_signature | 311 | rust | null | null | null | null | add_card_to_hs_locker | null | null | null | null | null | null | null |
File: crates/diesel_models/src/api_keys.rs
Public functions: 1
Public structs: 4
use diesel::{AsChangeset, AsExpression, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::schema::api_keys;
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, Identifiable, Queryable, Selectable,
)]
#[diesel(table_name = api_keys, primary_key(key_id), check_for_backend(diesel::pg::Pg))]
pub struct ApiKey {
pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub hashed_api_key: HashedApiKey,
pub prefix: String,
pub created_at: PrimitiveDateTime,
pub expires_at: Option<PrimitiveDateTime>,
pub last_used: Option<PrimitiveDateTime>,
}
#[derive(Debug, Insertable)]
#[diesel(table_name = api_keys)]
pub struct ApiKeyNew {
pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub hashed_api_key: HashedApiKey,
pub prefix: String,
pub created_at: PrimitiveDateTime,
pub expires_at: Option<PrimitiveDateTime>,
pub last_used: Option<PrimitiveDateTime>,
}
#[derive(Debug)]
pub enum ApiKeyUpdate {
Update {
name: Option<String>,
description: Option<String>,
expires_at: Option<Option<PrimitiveDateTime>>,
last_used: Option<PrimitiveDateTime>,
},
LastUsedUpdate {
last_used: PrimitiveDateTime,
},
}
#[derive(Debug, AsChangeset)]
#[diesel(table_name = api_keys)]
pub(crate) struct ApiKeyUpdateInternal {
pub name: Option<String>,
pub description: Option<String>,
pub expires_at: Option<Option<PrimitiveDateTime>>,
pub last_used: Option<PrimitiveDateTime>,
}
impl From<ApiKeyUpdate> for ApiKeyUpdateInternal {
fn from(api_key_update: ApiKeyUpdate) -> Self {
match api_key_update {
ApiKeyUpdate::Update {
name,
description,
expires_at,
last_used,
} => Self {
name,
description,
expires_at,
last_used,
},
ApiKeyUpdate::LastUsedUpdate { last_used } => Self {
last_used: Some(last_used),
name: None,
description: None,
expires_at: None,
},
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, AsExpression, PartialEq)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct HashedApiKey(String);
impl HashedApiKey {
pub fn into_inner(self) -> String {
self.0
}
}
impl From<String> for HashedApiKey {
fn from(hashed_api_key: String) -> Self {
Self(hashed_api_key)
}
}
mod diesel_impl {
use diesel::{
backend::Backend,
deserialize::FromSql,
serialize::{Output, ToSql},
sql_types::Text,
Queryable,
};
impl<DB> ToSql<Text, DB> for super::HashedApiKey
where
DB: Backend,
String: ToSql<Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> FromSql<Text, DB> for super::HashedApiKey
where
DB: Backend,
String: FromSql<Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
Ok(Self(String::from_sql(bytes)?))
}
}
impl<DB> Queryable<Text, DB> for super::HashedApiKey
where
DB: Backend,
Self: FromSql<Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(row)
}
}
}
// Tracking data by process_tracker
#[derive(Default, Debug, Deserialize, Serialize, Clone)]
pub struct ApiKeyExpiryTrackingData {
pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub api_key_name: String,
pub prefix: String,
pub api_key_expiry: Option<PrimitiveDateTime>,
// Days on which email reminder about api_key expiry has to be sent, prior to it's expiry.
pub expiry_reminder_days: Vec<u8>,
}
| crates/diesel_models/src/api_keys.rs | diesel_models | full_file | 1,029 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct StoredCredential {
/// Indicates the transaction processing model being executed when using stored
/// credentials.
pub model: Option<Model>,
/// Indicates the order of this transaction in the sequence of a planned repeating
/// transaction processing model.
pub sequence: Option<Sequence>,
} | crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs | hyperswitch_connectors | struct_definition | 60 | rust | StoredCredential | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.Method
{
"type": "string",
"enum": [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH"
]
} | ./hyperswitch/api-reference/v1/openapi_spec_v1.json | null | openapi_block | 46 | .json | null | null | null | null | null | openapi_spec | components | [
"schemas",
"Method"
] | null | null | null | null |
impl<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>
opentelemetry_sdk::trace::ShouldSample for ConditionalSampler<T>
{
fn should_sample(
&self,
parent_context: Option<&opentelemetry::Context>,
trace_id: opentelemetry::trace::TraceId,
name: &str,
span_kind: &opentelemetry::trace::SpanKind,
attributes: &[opentelemetry::KeyValue],
links: &[opentelemetry::trace::Link],
) -> opentelemetry::trace::SamplingResult {
use opentelemetry::trace::TraceContextExt;
match attributes
.iter()
.find(|&kv| kv.key == opentelemetry::Key::new("http.route"))
.map_or(self.0.default, |inner| {
self.0.should_trace_url(&inner.value.as_str())
}) {
true => {
self.1
.should_sample(parent_context, trace_id, name, span_kind, attributes, links)
}
false => opentelemetry::trace::SamplingResult {
decision: opentelemetry::trace::SamplingDecision::Drop,
attributes: Vec::new(),
trace_state: match parent_context {
Some(ctx) => ctx.span().span_context().trace_state().clone(),
None => opentelemetry::trace::TraceState::default(),
},
},
}
}
} | crates/router_env/src/logger/setup.rs | router_env | impl_block | 302 | rust | null | ConditionalSampler | opentelemetry_sdk::trace::ShouldSample for | impl opentelemetry_sdk::trace::ShouldSample for for ConditionalSampler | null | null | null | null | null | null | null | null |
pub async fn retry_delete_tokenize(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
pt: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await;
match schedule_time {
Some(s_time) => {
let retry_schedule = db
.as_scheduler()
.retry_process(pt, s_time)
.await
.map_err(Into::into);
metrics::TASKS_RESET_COUNT.add(
1,
router_env::metric_attributes!(("flow", "DeleteTokenizeData")),
);
retry_schedule
}
None => db
.as_scheduler()
.finish_process_with_business_status(
pt,
diesel_models::process_tracker::business_status::RETRIES_EXCEEDED,
)
.await
.map_err(Into::into),
}
} | crates/router/src/core/payment_methods/vault.rs | router | function_signature | 201 | rust | null | null | null | null | retry_delete_tokenize | null | null | null | null | null | null | null |
impl api::PaymentCapture for Coinbase {} | crates/hyperswitch_connectors/src/connectors/coinbase.rs | hyperswitch_connectors | impl_block | 8 | rust | null | Coinbase | api::PaymentCapture for | impl api::PaymentCapture for for Coinbase | null | null | null | null | null | null | null | null |
impl api::MandateSetup for Wellsfargopayout {} | crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs | hyperswitch_connectors | impl_block | 14 | rust | null | Wellsfargopayout | api::MandateSetup for | impl api::MandateSetup for for Wellsfargopayout | null | null | null | null | null | null | null | null |
pub async fn upload_file_to_theme_storage(
state: SessionState,
theme_id: String,
request: theme_api::UploadFileRequest,
) -> UserResponse<()> {
let db_theme = state
.store
.find_theme_by_theme_id(theme_id)
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_specific_file_key(&db_theme.theme_id, &request.asset_name),
request.asset_data.expose(),
)
.await?;
Ok(ApplicationResponse::StatusOk)
} | crates/router/src/core/user/theme.rs | router | function_signature | 130 | rust | null | null | null | null | upload_file_to_theme_storage | null | null | null | null | null | null | null |
impl MerchantConnectorResponse {
pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo {
MerchantConnectorInfo {
connector_label: connector_label.to_string(),
merchant_connector_id: self.merchant_connector_id.clone(),
}
}
} | crates/api_models/src/admin.rs | api_models | impl_block | 58 | rust | null | MerchantConnectorResponse | null | impl MerchantConnectorResponse | null | null | null | null | null | null | null | null |
pub struct BarclaycardErrorInformation {
reason: Option<String>,
message: Option<String>,
details: Option<Vec<Details>>,
} | crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs | hyperswitch_connectors | struct_definition | 29 | rust | BarclaycardErrorInformation | null | null | null | null | null | null | null | null | null | null | null |
pub struct XenditSplitRequestData {
#[serde(flatten)]
pub split_data: XenditSplitRequest,
} | crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs | hyperswitch_connectors | struct_definition | 27 | rust | XenditSplitRequestData | null | null | null | null | null | null | null | null | null | null | null |
pub async fn internal_trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails,
) -> errors::RouterResult<diesel_refund::Refund> {
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let routed_through = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve connector from payment attempt")?;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", routed_through.clone())),
);
let connector_enum = merchant_connector_details.connector_name;
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_enum.to_string(),
api::GetToken::Connector,
None,
)?;
refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(
merchant_connector_details,
);
let mut router_data = core_utils::construct_refund_router_data(
state,
connector_enum,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.await?;
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
))
.await;
let refund_update = get_refund_update_object(
state,
&connector,
&storage_scheme,
merchant_context,
&connector_response,
)
.await;
let response = match refund_update {
Some(refund_update) => state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.id.get_string_repr()
)
})?,
None => refund.to_owned(),
};
// Implement outgoing webhooks here
connector_response.to_refund_failed_response()?;
Ok(response)
} | crates/router/src/core/refunds_v2.rs | router | function_signature | 607 | rust | null | null | null | null | internal_trigger_refund_to_gateway | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
Public structs: 20
use common_enums::enums;
use common_utils::types::StringMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::CardData as _,
};
//TODO: Fill the struct with respective fields
pub struct FiservemeaRouterData<T> {
pub amount: StringMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for FiservemeaRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct FiservemeaTransactionAmount {
total: StringMajorUnit,
currency: common_enums::Currency,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaOrder {
order_id: String,
}
#[derive(Debug, Serialize)]
pub enum FiservemeaRequestType {
PaymentCardSaleTransaction,
PaymentCardPreAuthTransaction,
PostAuthTransaction,
VoidPreAuthTransactions,
ReturnTransaction,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaExpiryDate {
month: Secret<String>,
year: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentCard {
number: cards::CardNumber,
expiry_date: FiservemeaExpiryDate,
security_code: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum FiservemeaPaymentMethods {
PaymentCard(FiservemeaPaymentCard),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentsRequest {
request_type: FiservemeaRequestType,
merchant_transaction_id: String,
transaction_amount: FiservemeaTransactionAmount,
order: FiservemeaOrder,
payment_method: FiservemeaPaymentMethods,
}
impl TryFrom<&FiservemeaRouterData<&PaymentsAuthorizeRouterData>> for FiservemeaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservemeaRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = FiservemeaPaymentCard {
number: req_card.card_number.clone(),
expiry_date: FiservemeaExpiryDate {
month: req_card.card_exp_month.clone(),
year: req_card.get_card_expiry_year_2_digit()?,
},
security_code: req_card.card_cvc,
};
let request_type = if matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
) {
FiservemeaRequestType::PaymentCardSaleTransaction
} else {
FiservemeaRequestType::PaymentCardPreAuthTransaction
};
Ok(Self {
request_type,
merchant_transaction_id: item
.router_data
.request
.merchant_order_reference_id
.clone()
.unwrap_or(item.router_data.connector_request_reference_id.clone()),
transaction_amount: FiservemeaTransactionAmount {
total: item.amount.clone(),
currency: item.router_data.request.currency,
},
order: FiservemeaOrder {
order_id: item.router_data.connector_request_reference_id.clone(),
},
payment_method: FiservemeaPaymentMethods::PaymentCard(card),
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Selected payment method through fiservemea".to_string(),
)
.into()),
}
}
}
// Auth Struct
#[derive(Clone)]
pub struct FiservemeaAuthType {
pub(super) api_key: Secret<String>,
pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FiservemeaAuthType {
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 {
api_key: api_key.to_owned(),
secret_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Serialize, Deserialize)]
pub enum ResponseType {
BadRequest,
Unauthenticated,
Unauthorized,
NotFound,
GatewayDeclined,
EndpointDeclined,
ServerError,
EndpointCommunicationError,
UnsupportedMediaType,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservemeaTransactionType {
Sale,
Preauth,
Credit,
ForcedTicket,
Void,
Return,
Postauth,
PayerAuth,
Disbursement,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservemeaTransactionOrigin {
Ecom,
Moto,
Mail,
Phone,
Retail,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservemeaPaymentStatus {
Approved,
Waiting,
Partial,
ValidationFailed,
ProcessingFailed,
Declined,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservemeaPaymentResult {
Approved,
Declined,
Failed,
Waiting,
Partial,
Fraud,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentCardResponse {
expiry_date: Option<FiservemeaExpiryDate>,
bin: Option<String>,
last4: Option<String>,
brand: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentMethodDetails {
payment_card: Option<FiservemeaPaymentCardResponse>,
payment_method_type: Option<String>,
payment_method_brand: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Components {
subtotal: Option<f64>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AmountDetails {
total: Option<f64>,
currency: Option<common_enums::Currency>,
components: Option<Components>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AvsResponse {
street_match: Option<String>,
postal_code_match: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Processor {
reference_number: Option<String>,
authorization_code: Option<String>,
response_code: Option<String>,
response_message: Option<String>,
avs_response: Option<AvsResponse>,
security_code_response: Option<String>,
}
fn map_status(
fiservemea_status: Option<FiservemeaPaymentStatus>,
fiservemea_result: Option<FiservemeaPaymentResult>,
transaction_type: FiservemeaTransactionType,
) -> common_enums::AttemptStatus {
match fiservemea_status {
Some(status) => match status {
FiservemeaPaymentStatus::Approved => match transaction_type {
FiservemeaTransactionType::Preauth => common_enums::AttemptStatus::Authorized,
FiservemeaTransactionType::Void => common_enums::AttemptStatus::Voided,
FiservemeaTransactionType::Sale | FiservemeaTransactionType::Postauth => {
common_enums::AttemptStatus::Charged
}
FiservemeaTransactionType::Credit
| FiservemeaTransactionType::ForcedTicket
| FiservemeaTransactionType::Return
| FiservemeaTransactionType::PayerAuth
| FiservemeaTransactionType::Disbursement => common_enums::AttemptStatus::Failure,
},
FiservemeaPaymentStatus::Waiting => common_enums::AttemptStatus::Pending,
FiservemeaPaymentStatus::Partial => common_enums::AttemptStatus::PartialCharged,
FiservemeaPaymentStatus::ValidationFailed
| FiservemeaPaymentStatus::ProcessingFailed
| FiservemeaPaymentStatus::Declined => common_enums::AttemptStatus::Failure,
},
None => match fiservemea_result {
Some(result) => match result {
FiservemeaPaymentResult::Approved => match transaction_type {
FiservemeaTransactionType::Preauth => common_enums::AttemptStatus::Authorized,
FiservemeaTransactionType::Void => common_enums::AttemptStatus::Voided,
FiservemeaTransactionType::Sale | FiservemeaTransactionType::Postauth => {
common_enums::AttemptStatus::Charged
}
FiservemeaTransactionType::Credit
| FiservemeaTransactionType::ForcedTicket
| FiservemeaTransactionType::Return
| FiservemeaTransactionType::PayerAuth
| FiservemeaTransactionType::Disbursement => {
common_enums::AttemptStatus::Failure
}
},
FiservemeaPaymentResult::Waiting => common_enums::AttemptStatus::Pending,
FiservemeaPaymentResult::Partial => common_enums::AttemptStatus::PartialCharged,
FiservemeaPaymentResult::Declined
| FiservemeaPaymentResult::Failed
| FiservemeaPaymentResult::Fraud => common_enums::AttemptStatus::Failure,
},
None => common_enums::AttemptStatus::Pending,
},
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentsResponse {
response_type: Option<ResponseType>,
#[serde(rename = "type")]
fiservemea_type: Option<String>,
client_request_id: Option<String>,
api_trace_id: Option<String>,
ipg_transaction_id: String,
order_id: Option<String>,
transaction_type: FiservemeaTransactionType,
transaction_origin: Option<FiservemeaTransactionOrigin>,
payment_method_details: Option<FiservemeaPaymentMethodDetails>,
country: Option<Secret<String>>,
terminal_id: Option<String>,
merchant_id: Option<String>,
merchant_transaction_id: Option<String>,
transaction_time: Option<i64>,
approved_amount: Option<AmountDetails>,
transaction_amount: Option<AmountDetails>,
transaction_status: Option<FiservemeaPaymentStatus>, // FiservEMEA Docs mention that this field is deprecated. We are using it for now because transaction_result is not present in the response.
transaction_result: Option<FiservemeaPaymentResult>,
approval_code: Option<String>,
error_message: Option<String>,
transaction_state: Option<String>,
scheme_transaction_id: Option<String>,
processor: Option<Processor>,
}
impl<F, T> TryFrom<ResponseRouterData<F, FiservemeaPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FiservemeaPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: map_status(
item.response.transaction_status,
item.response.transaction_result,
item.response.transaction_type,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.ipg_transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaCaptureRequest {
request_type: FiservemeaRequestType,
transaction_amount: FiservemeaTransactionAmount,
}
impl TryFrom<&FiservemeaRouterData<&PaymentsCaptureRouterData>> for FiservemeaCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservemeaRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_type: FiservemeaRequestType::PostAuthTransaction,
transaction_amount: FiservemeaTransactionAmount {
total: item.amount.clone(),
currency: item.router_data.request.currency,
},
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaVoidRequest {
request_type: FiservemeaRequestType,
}
impl TryFrom<&PaymentsCancelRouterData> for FiservemeaVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
request_type: FiservemeaRequestType::VoidPreAuthTransactions,
})
}
}
// REFUND :
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaRefundRequest {
request_type: FiservemeaRequestType,
transaction_amount: FiservemeaTransactionAmount,
}
impl<F> TryFrom<&FiservemeaRouterData<&RefundsRouterData<F>>> for FiservemeaRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &FiservemeaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
request_type: FiservemeaRequestType::ReturnTransaction,
transaction_amount: FiservemeaTransactionAmount {
total: item.amount.clone(),
currency: item.router_data.request.currency,
},
})
}
}
fn map_refund_status(
fiservemea_status: Option<FiservemeaPaymentStatus>,
fiservemea_result: Option<FiservemeaPaymentResult>,
) -> Result<enums::RefundStatus, errors::ConnectorError> {
match fiservemea_status {
Some(status) => match status {
FiservemeaPaymentStatus::Approved => Ok(enums::RefundStatus::Success),
FiservemeaPaymentStatus::Partial | FiservemeaPaymentStatus::Waiting => {
Ok(enums::RefundStatus::Pending)
}
FiservemeaPaymentStatus::ValidationFailed
| FiservemeaPaymentStatus::ProcessingFailed
| FiservemeaPaymentStatus::Declined => Ok(enums::RefundStatus::Failure),
},
None => match fiservemea_result {
Some(result) => match result {
FiservemeaPaymentResult::Approved => Ok(enums::RefundStatus::Success),
FiservemeaPaymentResult::Partial | FiservemeaPaymentResult::Waiting => {
Ok(enums::RefundStatus::Pending)
}
FiservemeaPaymentResult::Declined
| FiservemeaPaymentResult::Failed
| FiservemeaPaymentResult::Fraud => Ok(enums::RefundStatus::Failure),
},
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "transactionResult",
}),
},
}
}
impl TryFrom<RefundsResponseRouterData<Execute, FiservemeaPaymentsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, FiservemeaPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id,
refund_status: map_refund_status(
item.response.transaction_status,
item.response.transaction_result,
)?,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, FiservemeaPaymentsResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, FiservemeaPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id,
refund_status: map_refund_status(
item.response.transaction_status,
item.response.transaction_result,
)?,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorDetails {
pub field: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiservemeaError {
pub code: Option<String>,
pub message: Option<String>,
pub details: Option<Vec<ErrorDetails>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiservemeaErrorResponse {
#[serde(rename = "type")]
fiservemea_type: Option<String>,
client_request_id: Option<String>,
api_trace_id: Option<String>,
pub response_type: Option<String>,
pub error: Option<FiservemeaError>,
}
| crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs | hyperswitch_connectors | full_file | 4,139 | null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/analytics/src/payments/filters.rs
Public functions: 1
Public structs: 1
use api_models::analytics::{payments::PaymentDimensions, Granularity, TimeRange};
use common_utils::errors::ReportSwitchExt;
use diesel_models::enums::{AttemptStatus, AuthenticationType, Currency, RoutingApproach};
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
types::{
AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult,
LoadRow,
},
};
pub trait PaymentFilterAnalytics: LoadRow<PaymentFilterRow> {}
pub async fn get_payment_filter_for_dimension<T>(
dimension: PaymentDimensions,
auth: &AuthInfo,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<PaymentFilterRow>>
where
T: AnalyticsDataSource + PaymentFilterAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment);
query_builder.add_select_column(dimension).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
query_builder.set_distinct();
query_builder
.execute_query::<PaymentFilterRow, _>(pool)
.await
.change_context(FiltersError::QueryBuildingError)?
.change_context(FiltersError::QueryExecutionFailure)
}
#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct PaymentFilterRow {
pub currency: Option<DBEnumWrapper<Currency>>,
pub status: Option<DBEnumWrapper<AttemptStatus>>,
pub connector: Option<String>,
pub authentication_type: Option<DBEnumWrapper<AuthenticationType>>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: Option<String>,
pub card_network: Option<String>,
pub merchant_id: Option<String>,
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
pub first_attempt: Option<bool>,
pub routing_approach: Option<DBEnumWrapper<RoutingApproach>>,
pub signature_network: Option<String>,
pub is_issuer_regulated: Option<bool>,
pub is_debit_routed: Option<bool>,
}
| crates/analytics/src/payments/filters.rs | analytics | full_file | 594 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn new(
frm_status: Option<String>,
frm_name: Option<String>,
frm_transaction_type: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
frm_status,
frm_name,
frm_transaction_type,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
} | crates/api_models/src/analytics/frm.rs | api_models | function_signature | 77 | rust | null | null | null | null | new | null | null | null | null | null | null | null |
impl ConnectorAccessToken for KafkaStore {
async fn get_access_token(
&self,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
) -> CustomResult<Option<AccessToken>, errors::StorageError> {
self.diesel_store
.get_access_token(merchant_id, merchant_connector_id)
.await
}
async fn set_access_token(
&self,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
access_token: AccessToken,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store
.set_access_token(merchant_id, merchant_connector_id, access_token)
.await
}
} | crates/router/src/db/kafka_store.rs | router | impl_block | 154 | rust | null | KafkaStore | ConnectorAccessToken for | impl ConnectorAccessToken for for KafkaStore | null | null | null | null | null | null | null | null |
pub trait ValidateRequest<F, R, D> {
fn validate_request(
&self,
request: &R,
merchant_context: &domain::MerchantContext,
) -> RouterResult<ValidateResult>;
} | crates/router/src/core/payments/operations.rs | router | trait_definition | 46 | rust | null | null | ValidateRequest | null | null | null | null | null | null | null | null | null |
impl Responder {
let flow = Flow::RoutingRetrieveDictionary;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
query.into_inner(),
|state, auth: auth::AuthenticationData, query_params, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
routing::retrieve_merchant_routing_dictionary(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
query_params.clone(),
transaction_type
.or(query_params.transaction_type)
.unwrap_or(enums::TransactionType::Payment),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/routing.rs | router | impl_block | 226 | rust | null | Responder | null | impl Responder | null | null | null | null | null | null | null | null |
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
} | crates/hyperswitch_connectors/src/connectors/novalnet.rs | hyperswitch_connectors | function_signature | 28 | rust | null | null | null | null | new | null | null | null | null | null | null | null |
pub struct TokenizationData {
pub brand_reference: Option<String>,
} | crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs | hyperswitch_connectors | struct_definition | 15 | rust | TokenizationData | null | null | null | null | null | null | null | null | null | null | null |
pub struct AuthenticationAuthenticateRequest {
/// Authentication ID for the authentication
#[serde(skip_deserializing)]
pub authentication_id: id_type::AuthenticationId,
/// Client secret for the authentication
#[schema(value_type = String)]
pub client_secret: Option<masking::Secret<String>>,
/// SDK Information if request is from SDK
pub sdk_information: Option<SdkInformation>,
/// Device Channel indicating whether request is coming from App or Browser
pub device_channel: DeviceChannel,
/// Indicates if 3DS method data was successfully completed or not
pub threeds_method_comp_ind: ThreeDsCompletionIndicator,
} | crates/api_models/src/authentication.rs | api_models | struct_definition | 134 | rust | AuthenticationAuthenticateRequest | null | null | null | null | null | null | null | null | null | null | null |
/// Build connections to all gRPC services
pub async fn build_connections(
config: &GrpcClientSettings,
client: Client,
) -> Result<Self, Box<dyn std::error::Error>> {
let dynamic_routing_config = &config.dynamic_routing_client;
let connection = match dynamic_routing_config {
Some(DynamicRoutingClientConfig::Enabled {
host,
port,
service,
}) => Some((host.clone(), *port, service.clone())),
_ => None,
};
let mut client_map = HashMap::new();
if let Some(conn) = connection {
let uri = format!("http://{}:{}", conn.0, conn.1).parse::<tonic::transport::Uri>()?;
let health_client = HealthClient::with_origin(client, uri);
client_map.insert(HealthCheckServices::DynamicRoutingService, health_client);
}
Ok(Self {
clients: client_map,
})
} | crates/external_services/src/grpc_client/health_check_client.rs | external_services | function_signature | 200 | rust | null | null | null | null | build_connections | null | null | null | null | null | null | null |
pub struct RoutableConnectorChoice {
#[serde(skip)]
pub choice_kind: RoutableChoiceKind,
pub connector: RoutableConnectors,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
} | crates/euclid/src/frontend/ast.rs | euclid | struct_definition | 50 | rust | RoutableConnectorChoice | null | null | null | null | null | null | null | null | null | null | null |
pub struct UpdateEliminationBucketEventRequest {
pub id: String,
pub params: String,
pub labels_with_bucket_name: Vec<LabelWithBucketNameEventRequest>,
pub config: Option<EliminationRoutingEventBucketConfig>,
} | crates/router/src/core/payments/routing/utils.rs | router | struct_definition | 51 | rust | UpdateEliminationBucketEventRequest | null | null | null | null | null | null | null | null | null | null | null |
pub async fn frm_fulfillment(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<frm_core::types::FrmFulfillmentRequest>,
) -> HttpResponse {
let flow = Flow::FrmFulfillment;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, auth: services::authentication::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
frm_core::frm_fulfillment_core(state, merchant_context, req)
},
&services::authentication::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/fraud_check.rs | router | function_signature | 194 | rust | null | null | null | null | frm_fulfillment | null | null | null | null | null | null | null |
pub async fn api_key_update() {} | crates/openapi/src/routes/api_keys.rs | openapi | function_signature | 8 | rust | null | null | null | null | api_key_update | null | null | null | null | null | null | null |
pub async fn check_merchant_account_kv_status(
state: SessionState,
merchant_id: id_type::MerchantId,
) -> RouterResponse<api_models::admin::ToggleKVResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
// check if the merchant account exists
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let kv_status = matches!(
merchant_account.storage_scheme,
MerchantStorageScheme::RedisKv
);
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ToggleKVResponse {
merchant_id: merchant_account.get_id().to_owned(),
kv_enabled: kv_status,
},
))
} | crates/router/src/core/admin.rs | router | function_signature | 249 | rust | null | null | null | null | check_merchant_account_kv_status | null | null | null | null | null | null | null |
pub struct Authentication; | crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs | hyperswitch_domain_models | struct_definition | 4 | rust | Authentication | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentVoid for Bamboraapac {} | crates/hyperswitch_connectors/src/connectors/bamboraapac.rs | hyperswitch_connectors | impl_block | 12 | rust | null | Bamboraapac | api::PaymentVoid for | impl api::PaymentVoid for for Bamboraapac | null | null | null | null | null | null | null | null |
pub struct AddVaultResponse {
pub entity_id: Option<id_type::GlobalCustomerId>,
pub vault_id: domain::VaultId,
pub fingerprint_id: Option<String>,
} | crates/router/src/types/payment_methods.rs | router | struct_definition | 38 | rust | AddVaultResponse | null | null | null | null | null | null | null | null | null | null | null |
pub fn perform_volume_split(
mut splits: Vec<routing_types::ConnectorVolumeSplit>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();
let weighted_index = distributions::WeightedIndex::new(weights)
.change_context(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Error creating weighted distribution for volume split")?;
let mut rng = rand::thread_rng();
let idx = weighted_index.sample(&mut rng);
splits
.get(idx)
.ok_or(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Volume split index lookup failed")?;
// Panic Safety: We have performed a `get(idx)` operation just above which will
// ensure that the index is always present, else throw an error.
let removed = splits.remove(idx);
splits.insert(0, removed);
Ok(splits.into_iter().map(|sp| sp.connector).collect())
} | crates/router/src/core/payments/routing.rs | router | function_signature | 220 | rust | null | null | null | null | perform_volume_split | null | null | null | null | null | null | null |
pub async fn routing_retrieve_default_config() {} | crates/openapi/src/routes/routing.rs | openapi | function_signature | 10 | rust | null | null | null | null | routing_retrieve_default_config | null | null | null | null | null | null | null |
impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetAuthEventMetricRequest");
let flow = AnalyticsFlow::GetAuthMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
analytics::auth_events::get_metrics(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
auth::auth_type(
&auth::PlatformOrgAdminAuth {
is_admin_auth_allowed: false,
organization_id: None,
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/analytics.rs | router | impl_block | 251 | rust | null | Responder | null | impl Responder | null | null | null | null | null | null | null | null |
Documentation: api-reference/intelligent-router-api-reference/elimination/fetch-eliminated-processor-list.mdx
# Type: Doc File
---
openapi: post /elimination.EliminationAnalyser/GetEliminationStatus
--- | api-reference/intelligent-router-api-reference/elimination/fetch-eliminated-processor-list.mdx | null | doc_file | 49 | doc | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetPaymentFiltersRequest,
auth: &AuthInfo,
) -> AnalyticsResult<PaymentFiltersResponse> {
let mut res = PaymentFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(pool) => {
get_payment_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::Clickhouse(pool) => {
get_payment_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedCkh(sqlx_poll, ckh_pool) => {
let ckh_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_poll,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics filters")
},
_ => {}
};
ckh_result
}
AnalyticsProvider::CombinedSqlx(sqlx_poll, ckh_pool) => {
let ckh_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_poll,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics filters")
},
_ => {}
};
sqlx_result
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: PaymentFilterRow| match dim {
PaymentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),
PaymentDimensions::PaymentStatus => fil.status.map(|i| i.as_ref().to_string()),
PaymentDimensions::Connector => fil.connector,
PaymentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()),
PaymentDimensions::PaymentMethod => fil.payment_method,
PaymentDimensions::PaymentMethodType => fil.payment_method_type,
PaymentDimensions::ClientSource => fil.client_source,
PaymentDimensions::ClientVersion => fil.client_version,
PaymentDimensions::ProfileId => fil.profile_id,
PaymentDimensions::CardNetwork => fil.card_network,
PaymentDimensions::MerchantId => fil.merchant_id,
PaymentDimensions::CardLast4 => fil.card_last_4,
PaymentDimensions::CardIssuer => fil.card_issuer,
PaymentDimensions::ErrorReason => fil.error_reason,
PaymentDimensions::RoutingApproach => fil.routing_approach.map(|i| i.as_ref().to_string()),
PaymentDimensions::SignatureNetwork => fil.signature_network,
PaymentDimensions::IsIssuerRegulated => fil.is_issuer_regulated.map(|b| b.to_string()),
PaymentDimensions::IsDebitRouted => fil.is_debit_routed.map(|b| b.to_string())
})
.collect::<Vec<String>>();
res.query_data.push(FilterValue {
dimension: dim,
values,
})
}
Ok(res)
} | crates/analytics/src/payments/core.rs | analytics | function_signature | 810 | rust | null | null | null | null | get_filters | null | null | null | null | null | null | null |
pub struct StripebillingPaymentsResponse {
status: StripebillingPaymentStatus,
id: String,
} | crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs | hyperswitch_connectors | struct_definition | 21 | rust | StripebillingPaymentsResponse | null | null | null | null | null | null | null | null | null | null | null |
pub async fn update_config(
state: SessionState,
config_update: &api::ConfigUpdate,
) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.update_config_by_key(&config_update.key, config_update.foreign_into())
.await
.to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
} | crates/router/src/core/configs.rs | router | function_signature | 94 | rust | null | null | null | null | update_config | null | null | null | null | null | null | null |
impl api::PaymentToken for Opayo {} | crates/hyperswitch_connectors/src/connectors/opayo.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Opayo | api::PaymentToken for | impl api::PaymentToken for for Opayo | null | null | null | null | null | null | null | null |
pub struct RefundResponse {
id: String,
status: RefundStatus,
} | crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs | hyperswitch_connectors | struct_definition | 19 | rust | RefundResponse | null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_bank_from_hs_locker(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
temp_token: Option<&String>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
token_ref: &str,
) -> errors::RouterResult<api::BankPayout> {
let payment_method = get_payment_method_from_hs_locker(
state,
key_store,
customer_id,
merchant_id,
token_ref,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting payment method from locker")?;
let pm_parsed: api::PayoutMethodData = payment_method
.peek()
.to_string()
.parse_struct("PayoutMethodData")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match &pm_parsed {
api::PayoutMethodData::Bank(bank) => {
if let Some(token) = temp_token {
vault::Vault::store_payout_method_data_in_locker(
state,
Some(token.clone()),
&pm_parsed,
Some(customer_id.to_owned()),
key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error storing payout method data in temporary locker")?;
}
Ok(bank.to_owned())
}
api::PayoutMethodData::Card(_) => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected bank details, found card details instead".to_string(),
}
.into()),
api::PayoutMethodData::Wallet(_) => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected bank details, found wallet details instead".to_string(),
}
.into()),
}
} | crates/router/src/core/payment_methods/cards.rs | router | function_signature | 392 | rust | null | null | null | null | get_bank_from_hs_locker | null | null | null | null | null | null | null |
pub struct HeaderAuth<I>(pub I); | crates/router/src/services/authentication.rs | router | struct_definition | 9 | rust | HeaderAuth | null | null | null | null | null | null | null | null | null | null | null |
pub async fn merchant_account_toggle_kv(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::ToggleKVRequest>,
) -> HttpResponse {
let flow = Flow::ConfigKeyUpdate;
let mut payload = json_payload.into_inner();
payload.merchant_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| kv_for_merchant(state, payload.merchant_id, payload.kv_enabled),
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
} | crates/router/src/routes/admin.rs | router | function_signature | 158 | rust | null | null | null | null | merchant_account_toggle_kv | null | null | null | null | null | null | null |
pub struct VerifyConnectorRequest {
pub connector_name: enums::Connector,
pub connector_account_details: admin::ConnectorAuthType,
} | crates/api_models/src/verify_connector.rs | api_models | struct_definition | 28 | rust | VerifyConnectorRequest | null | null | null | null | null | null | null | null | null | null | null |
pub struct FiuuWebhooksRefundResponse {
pub refund_type: FiuuWebhooksRefundType,
#[serde(rename = "MerchantID")]
pub merchant_id: Secret<String>,
#[serde(rename = "RefID")]
pub ref_id: String,
#[serde(rename = "RefundID")]
pub refund_id: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub amount: StringMajorUnit,
pub status: FiuuRefundsWebhookStatus,
pub signature: Secret<String>,
} | crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs | hyperswitch_connectors | struct_definition | 121 | rust | FiuuWebhooksRefundResponse | null | null | null | null | null | null | null | null | null | null | null |
impl AuthenticationUpdateInternal {
pub fn apply_changeset(self, source: Authentication) -> Authentication {
let Self {
connector_authentication_id,
payment_method_id,
authentication_type,
authentication_status,
authentication_lifecycle_status,
modified_at: _,
error_code,
error_message,
connector_metadata,
maximum_supported_version,
threeds_server_transaction_id,
authentication_flow_type,
message_version,
eci,
trans_status,
acquirer_bin,
acquirer_merchant_id,
three_ds_method_data,
three_ds_method_url,
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
ds_trans_id,
directory_server_id,
acquirer_country_code,
service_details,
force_3ds_challenge,
psd2_sca_exemption_type,
billing_address,
shipping_address,
browser_info,
email,
profile_acquirer_id,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
} = self;
Authentication {
connector_authentication_id: connector_authentication_id
.or(source.connector_authentication_id),
payment_method_id: payment_method_id.unwrap_or(source.payment_method_id),
authentication_type: authentication_type.or(source.authentication_type),
authentication_status: authentication_status.unwrap_or(source.authentication_status),
authentication_lifecycle_status: authentication_lifecycle_status
.unwrap_or(source.authentication_lifecycle_status),
modified_at: common_utils::date_time::now(),
error_code: error_code.or(source.error_code),
error_message: error_message.or(source.error_message),
connector_metadata: connector_metadata.or(source.connector_metadata),
maximum_supported_version: maximum_supported_version
.or(source.maximum_supported_version),
threeds_server_transaction_id: threeds_server_transaction_id
.or(source.threeds_server_transaction_id),
authentication_flow_type: authentication_flow_type.or(source.authentication_flow_type),
message_version: message_version.or(source.message_version),
eci: eci.or(source.eci),
trans_status: trans_status.or(source.trans_status),
acquirer_bin: acquirer_bin.or(source.acquirer_bin),
acquirer_merchant_id: acquirer_merchant_id.or(source.acquirer_merchant_id),
three_ds_method_data: three_ds_method_data.or(source.three_ds_method_data),
three_ds_method_url: three_ds_method_url.or(source.three_ds_method_url),
acs_url: acs_url.or(source.acs_url),
challenge_request: challenge_request.or(source.challenge_request),
acs_reference_number: acs_reference_number.or(source.acs_reference_number),
acs_trans_id: acs_trans_id.or(source.acs_trans_id),
acs_signed_content: acs_signed_content.or(source.acs_signed_content),
ds_trans_id: ds_trans_id.or(source.ds_trans_id),
directory_server_id: directory_server_id.or(source.directory_server_id),
acquirer_country_code: acquirer_country_code.or(source.acquirer_country_code),
service_details: service_details.or(source.service_details),
force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge),
psd2_sca_exemption_type: psd2_sca_exemption_type.or(source.psd2_sca_exemption_type),
billing_address: billing_address.or(source.billing_address),
shipping_address: shipping_address.or(source.shipping_address),
browser_info: browser_info.or(source.browser_info),
email: email.or(source.email),
profile_acquirer_id: profile_acquirer_id.or(source.profile_acquirer_id),
challenge_code: challenge_code.or(source.challenge_code),
challenge_cancel: challenge_cancel.or(source.challenge_cancel),
challenge_code_reason: challenge_code_reason.or(source.challenge_code_reason),
message_extension: message_extension.or(source.message_extension),
..source
}
}
} | crates/diesel_models/src/authentication.rs | diesel_models | impl_block | 812 | rust | null | AuthenticationUpdateInternal | null | impl AuthenticationUpdateInternal | null | null | null | null | null | null | null | null |
pub async fn deep_health_check(
conf: web::Data<Settings>,
stores: web::Data<HashMap<String, Arc<Store>>>,
) -> impl actix_web::Responder {
let mut deep_health_res = HashMap::new();
for (tenant, store) in stores.iter() {
logger::info!("Tenant: {:?}", tenant);
let response = match deep_health_check_func(conf.clone(), store).await {
Ok(response) => serde_json::to_string(&response)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
Err(err) => return log_and_return_error_response(err),
};
deep_health_res.insert(tenant.clone(), response);
}
services::http_response_json(
serde_json::to_string(&deep_health_res)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
)
} | crates/drainer/src/health_check.rs | drainer | function_signature | 202 | rust | null | null | null | null | deep_health_check | null | null | null | null | null | null | null |
#[schema(example = "USD", value_type = Currency)]
pub currency: common_enums::Currency,
/// The shipping cost of the order. This has to be collected from the merchant
pub shipping_cost: Option<MinorUnit>,
/// Tax amount related to the order. This will be calculated by the external tax provider
pub order_tax_amount: Option<MinorUnit>,
/// The action to whether calculate tax by calling external tax provider or not
#[schema(value_type = TaxCalculationOverride)]
pub external_tax_calculation: common_enums::TaxCalculationOverride,
/// The action to whether calculate surcharge or not
#[schema(value_type = SurchargeCalculationOverride)]
pub surcharge_calculation: common_enums::SurchargeCalculationOverride,
/// The surcharge amount to be added to the order, collected from the merchant
pub surcharge_amount: Option<MinorUnit>,
/// tax on surcharge amount
pub tax_on_surcharge: Option<MinorUnit>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)]
pub struct PaymentAmountDetailsResponse {
/// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)
#[schema(value_type = u64, example = 6540)]
#[serde(default, deserialize_with = "amount::deserialize")]
pub order_amount: MinorUnit,
/// The currency of the order
#[schema(example = "USD", value_type = Currency)]
pub currency: common_enums::Currency,
/// The shipping cost of the order. This has to be collected from the merchant
pub shipping_cost: Option<MinorUnit>,
/// Tax amount related to the order. This will be calculated by the external tax provider
pub order_tax_amount: Option<MinorUnit>,
/// The action to whether calculate tax by calling external tax provider or not
#[schema(value_type = TaxCalculationOverride)]
pub external_tax_calculation: common_enums::TaxCalculationOverride,
/// The action to whether calculate surcharge or not
#[schema(value_type = SurchargeCalculationOverride)]
pub surcharge_calculation: common_enums::SurchargeCalculationOverride,
/// The surcharge amount to be added to the order, collected from the merchant
pub surcharge_amount: Option<MinorUnit>,
/// tax on surcharge amount
pub tax_on_surcharge: Option<MinorUnit>,
/// The total amount of the order including tax, surcharge and shipping cost
pub net_amount: MinorUnit,
/// The amount that was requested to be captured for this payment
pub amount_to_capture: Option<MinorUnit>,
/// The amount that can be captured on the payment. Either in one go or through multiple captures.
/// This is applicable in case the capture method was either `manual` or `manual_multiple`
pub amount_capturable: MinorUnit,
/// The amount that was captured for this payment. This is the sum of all the captures done on this payment
pub amount_captured: Option<MinorUnit>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentAttemptAmountDetails {
/// The total amount of the order including tax, surcharge and shipping cost
pub net_amount: MinorUnit,
/// The amount that was requested to be captured for this payment
pub amount_to_capture: Option<MinorUnit>,
/// Surcharge amount for the payment attempt.
/// This is either derived by surcharge rules, or sent by the merchant
pub surcharge_amount: Option<MinorUnit>,
/// Tax amount for the payment attempt
/// This is either derived by surcharge rules, or sent by the merchant
pub tax_on_surcharge: Option<MinorUnit>,
/// The total amount that can be captured for this payment attempt.
pub amount_capturable: MinorUnit,
/// Shipping cost for the payment attempt.
/// Shipping cost for the payment attempt.
pub shipping_cost: Option<MinorUnit>,
/// Tax amount for the order.
/// This is either derived by calling an external tax processor, or sent by the merchant
pub order_tax_amount: Option<MinorUnit>,
}
#[cfg(feature = "v2")]
impl AmountDetails {
pub fn new(amount_details_setter: AmountDetailsSetter) -> Self {
Self {
order_amount: amount_details_setter.order_amount,
currency: amount_details_setter.currency,
shipping_cost: amount_details_setter.shipping_cost,
order_tax_amount: amount_details_setter.order_tax_amount,
skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation,
skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation,
surcharge_amount: amount_details_setter.surcharge_amount,
tax_on_surcharge: amount_details_setter.tax_on_surcharge,
}
}
pub fn order_amount(&self) -> Amount {
self.order_amount
}
pub fn currency(&self) -> common_enums::Currency {
self.currency
}
pub fn shipping_cost(&self) -> Option<MinorUnit> {
self.shipping_cost
}
pub fn order_tax_amount(&self) -> Option<MinorUnit> {
self.order_tax_amount
}
pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride {
self.skip_external_tax_calculation
}
pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride {
self.skip_surcharge_calculation
}
pub fn surcharge_amount(&self) -> Option<MinorUnit> {
self.surcharge_amount
}
pub fn tax_on_surcharge(&self) -> Option<MinorUnit> {
self.tax_on_surcharge
}
}
#[cfg(feature = "v2")]
impl AmountDetailsUpdate {
pub fn order_amount(&self) -> Option<Amount> {
self.order_amount
}
pub fn currency(&self) -> Option<common_enums::Currency> {
self.currency
}
pub fn shipping_cost(&self) -> Option<MinorUnit> {
self.shipping_cost
}
pub fn order_tax_amount(&self) -> Option<MinorUnit> {
self.order_tax_amount
}
pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> {
self.skip_external_tax_calculation
}
pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> {
self.skip_surcharge_calculation
}
pub fn surcharge_amount(&self) -> Option<MinorUnit> {
self.surcharge_amount
}
pub fn tax_on_surcharge(&self) -> Option<MinorUnit> {
self.tax_on_surcharge
}
}
#[cfg(feature = "v1")]
#[derive(
Default,
Debug,
serde::Deserialize,
serde::Serialize,
Clone,
ToSchema,
router_derive::PolymorphicSchema,
router_derive::ValidateSchema,
)]
#[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)]
#[serde(deny_unknown_fields)]
pub struct PaymentsRequest {
/// The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment.
#[schema(value_type = Option<u64>, example = 6540)]
#[serde(default, deserialize_with = "amount::deserialize_option")]
#[mandatory_in(PaymentsCreateRequest = u64)]
// Makes the field mandatory in PaymentsCreateRequest
pub amount: Option<Amount>,
/// Total tax amount applicable to the order, in the lowest denomination of the currency.
#[schema(value_type = Option<i64>, example = 6540)]
pub order_tax_amount: Option<MinorUnit>,
/// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment.
#[schema(example = "USD", value_type = Option<Currency>)]
#[mandatory_in(PaymentsCreateRequest = Currency)]
pub currency: Option<api_enums::Currency>,
/// The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount.
#[schema(value_type = Option<i64>, example = 6540)]
pub amount_to_capture: Option<MinorUnit>,
/// The shipping cost for the payment. This is required for tax calculation in some regions.
#[schema(value_type = Option<i64>, example = 6540)]
pub shipping_cost: Option<MinorUnit>,
/// Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., "pay_mbabizu24mvu3mela5njyhpit4"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment.
#[schema(
value_type = Option<String>,
min_length = 30,
max_length = 30,
example = "pay_mbabizu24mvu3mela5njyhpit4"
)]
#[serde(default, deserialize_with = "payment_id_type::deserialize_option")]
pub payment_id: Option<PaymentIdType>,
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
#[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub merchant_id: Option<id_type::MerchantId>,
/// Details of the routing configuration for that payment
#[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({
"type": "single",
"data": {"connector": "stripe", "merchant_connector_id": "mca_123"}
}))]
pub routing: Option<serde_json::Value>,
/// This allows to manually select a connector with which the payment can go through.
#[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))]
pub connector: Option<Vec<api_enums::Connector>>,
#[schema(value_type = Option<CaptureMethod>, example = "automatic")]
pub capture_method: Option<api_enums::CaptureMethod>,
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")]
pub authentication_type: Option<api_enums::AuthenticationType>,
/// The billing details of the payment. This address will be used for invoicing.
pub billing: Option<Address>,
/// A timestamp (ISO 8601 code) that determines when the payment should be captured.
/// Providing this field will automatically set `capture` to true
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub capture_on: Option<PrimitiveDateTime>,
/// If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization.
#[schema(default = false, example = true)]
pub confirm: Option<bool>,
/// Passing this object creates a new customer or attaches an existing customer to the payment
pub customer: Option<CustomerDetails>,
/// The identifier for the customer
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
/// The customer's email address.
/// This field will be deprecated soon, use the customer object instead
#[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub email: Option<Email>,
/// The customer's name.
/// This field will be deprecated soon, use the customer object instead.
#[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub name: Option<Secret<String>>,
/// The customer's phone number
/// This field will be deprecated soon, use the customer object instead
#[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub phone: Option<Secret<String>>,
/// The country code for the customer phone number
/// This field will be deprecated soon, use the customer object instead
#[schema(max_length = 255, example = "+1", deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub phone_country_code: Option<String>,
/// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory
#[schema(example = true)]
pub off_session: Option<bool>,
/// An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping.
#[schema(example = "It's my first payment request")]
pub description: Option<String>,
/// The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments).
#[schema(value_type = Option<String>, example = "https://hyperswitch.io", max_length = 2048)]
pub return_url: Option<Url>,
#[schema(value_type = Option<FutureUsage>, example = "off_session")]
pub setup_future_usage: Option<api_enums::FutureUsage>,
#[schema(example = "bank_transfer")]
#[serde(with = "payment_method_data_serde", default)]
pub payment_method_data: Option<PaymentMethodDataRequest>,
#[schema(value_type = Option<PaymentMethod>, example = "card")]
pub payment_method: Option<api_enums::PaymentMethod>,
/// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner.
#[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")]
pub payment_token: Option<String>,
/// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead
#[schema(value_type = Option<String>, deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub card_cvc: Option<Secret<String>>,
/// The shipping address for the payment
pub shipping: Option<Address>,
/// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.
#[schema(max_length = 255, example = "Hyperswitch Router")]
pub statement_descriptor_name: Option<String>,
/// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.
#[schema(max_length = 255, example = "Payment for shoes purchase")]
pub statement_descriptor_suffix: Option<String>,
/// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount
#[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{
"product_name": "Apple iPhone 16",
"quantity": 1,
"amount" : 69000
"product_img_link" : "https://dummy-img-link.com"
}]"#)]
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
/// It's a token used for client side verification.
#[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)]
pub client_secret: Option<String>,
/// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server.
pub mandate_data: Option<MandateData>,
/// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client.
#[schema(value_type = Option<CustomerAcceptance>)]
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
/// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data
#[schema(max_length = 64, example = "mandate_iwer89rnjef349dni3")]
#[remove_in(PaymentsUpdateRequest)]
pub mandate_id: Option<String>,
/// Additional details required by 3DS 2.0
#[schema(value_type = Option<BrowserInformation>, example = r#"{
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled":true
}"#)]
pub browser_info: Option<serde_json::Value>,
/// To indicate the type of payment experience that the payment method would go through
#[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")]
pub payment_experience: Option<api_enums::PaymentExperience>,
/// Can be used to specify the Payment Method Type
#[schema(value_type = Option<PaymentMethodType>, example = "google_pay")]
pub payment_method_type: Option<api_enums::PaymentMethodType>,
/// Business country of the merchant for this payment.
/// To be deprecated soon. Pass the profile_id instead
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
#[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)]
pub business_country: Option<api_enums::CountryAlpha2>,
/// Business label of the merchant for this payment.
/// To be deprecated soon. Pass the profile_id instead
#[schema(example = "food")]
#[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)]
pub business_label: Option<String>,
#[schema(value_type = Option<MerchantConnectorDetailsWrap>)]
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
/// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent
#[schema(value_type = Option<Vec<PaymentMethodType>>)]
pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>,
/// Business sub label for the payment
#[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)]
pub business_sub_label: Option<String>,
/// Denotes the retry action
#[schema(value_type = Option<RetryAction>)]
#[remove_in(PaymentsCreateRequest)]
pub retry_action: Option<api_enums::RetryAction>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<serde_json::Value>,
/// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below.
pub connector_metadata: Option<ConnectorMetadata>,
/// Additional data that might be required by hyperswitch based on the requested features by the merchants.
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub feature_metadata: Option<FeatureMetadata>,
/// Whether to generate the payment link for this payment or not (if applicable)
#[schema(default = false, example = true)]
pub payment_link: Option<bool>,
#[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)]
pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>,
/// Custom payment link config id set at business profile, send only if business_specific_configs is configured
pub payment_link_config_id: Option<String>,
/// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up.
#[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)]
#[schema(value_type = Option<String>)]
pub profile_id: Option<id_type::ProfileId>,
#[remove_in(PaymentsConfirmRequest)]
#[schema(value_type = Option<RequestSurchargeDetails>)]
pub surcharge_details: Option<RequestSurchargeDetails>,
/// The type of the payment that differentiates between normal and various types of mandate payments
#[schema(value_type = Option<PaymentType>)]
pub payment_type: Option<api_enums::PaymentType>,
///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it.
pub request_incremental_authorization: Option<bool>,
///Will be used to expire client secret after certain amount of time to be supplied in seconds
///(900) for 15 mins
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// Additional data related to some frm(Fraud Risk Management) connectors
#[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)]
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// Whether to perform external authentication (if applicable)
#[schema(example = true)]
pub request_external_three_ds_authentication: Option<bool>,
/// Details required for recurring payment
pub recurring_details: Option<RecurringDetails>,
/// Fee information to be charged on the payment being collected
#[schema(value_type = Option<SplitPaymentsRequest>)]
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
/// Optional boolean value to extent authorization period of this payment
///
/// capture method must be manual or manual_multiple
#[schema(value_type = Option<bool>, default = false)]
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
/// Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported.
#[schema(
value_type = Option<String>,
max_length = 255,
example = "Custom_Order_id_123"
)]
pub merchant_order_reference_id: Option<String>,
/// Whether to calculate tax for this payment intent
pub skip_external_tax_calculation: Option<bool>,
/// Choose what kind of sca exemption is required for this payment
#[schema(value_type = Option<ScaExemptionType>)]
pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>,
/// Service details for click to pay external authentication
#[schema(value_type = Option<CtpServiceDetails>)]
pub ctp_service_details: Option<CtpServiceDetails>,
/// Indicates if 3ds challenge is forced
pub force_3ds_challenge: Option<bool>,
/// Indicates if 3DS method data was successfully completed or not
pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>,
/// Indicates if the redirection has to open in the iframe
pub is_iframe_redirection_enabled: Option<bool>,
/// If enabled, provides whole connector response
pub all_keys_required: Option<bool>,
/// Indicates whether the `payment_id` was provided by the merchant
/// This value is inferred internally based on the request
#[serde(skip_deserializing)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub is_payment_id_from_merchant: bool,
/// Indicates how the payment was initiated (e.g., ecommerce, mail, or telephone).
#[schema(value_type = Option<PaymentChannel>)]
pub payment_channel: Option<common_enums::PaymentChannel>,
/// Your tax status for this order or transaction.
#[schema(value_type = Option<TaxStatus>)]
pub tax_status: Option<api_enums::TaxStatus>,
/// Total amount of the discount you have applied to the order or transaction.
#[schema(value_type = Option<i64>, example = 6540)]
pub discount_amount: Option<MinorUnit>,
/// Tax amount applied to shipping charges.
pub shipping_amount_tax: Option<MinorUnit>,
/// Duty or customs fee amount for international transactions.
pub duty_amount: Option<MinorUnit>,
/// Date the payer placed the order.
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub order_date: Option<PrimitiveDateTime>,
/// Allow partial authorization for this payment
pub enable_partial_authorization: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CtpServiceDetails {
/// merchant transaction id
pub merchant_transaction_id: Option<String>,
/// network transaction correlation id
pub correlation_id: Option<String>,
/// session transaction flow id
pub x_src_flow_id: Option<String>,
/// provider Eg: Visa, Mastercard
#[schema(value_type = Option<CtpServiceProvider>)]
pub provider: Option<api_enums::CtpServiceProvider>,
/// Encrypted payload
#[schema(value_type = Option<String>)]
pub encrypted_payload: Option<Secret<String>>,
}
impl CtpServiceDetails {
pub fn is_network_confirmation_call_required(&self) -> bool {
self.provider == Some(api_enums::CtpServiceProvider::Mastercard)
}
}
#[cfg(feature = "v1")]
/// Checks if the inner values of two options are equal
/// Returns true if values are not equal, returns false in other cases
fn are_optional_values_invalid<T: PartialEq>(
first_option: Option<&T>,
second_option: Option<&T>,
) -> bool {
match (first_option, second_option) {
(Some(first_option), Some(second_option)) => first_option != second_option,
_ => false,
}
}
#[cfg(feature = "v1")]
impl PaymentsRequest {
/// Get the customer id
///
/// First check the id for `customer.id`
/// If not present, check for `customer_id` at the root level
pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> {
self.customer_id
.as_ref()
.or(self.customer.as_ref().map(|customer| &customer.id))
}
pub fn validate_and_get_request_extended_authorization(
&self,
) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError>
{
self.request_extended_authorization
.as_ref()
.map(|request_extended_authorization| {
request_extended_authorization.validate_field_and_get(self)
})
.transpose()
}
/// Checks if the customer details are passed in both places
/// If they are passed in both places, check for both the values to be equal
/// Or else, return the field which has inconsistent data
pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> {
if let Some(CustomerDetails {
id,
name,
email,
phone,
phone_country_code,
..
}) = self.customer.as_ref()
{
let invalid_fields = [
are_optional_values_invalid(self.customer_id.as_ref(), Some(id))
.then_some("customer_id and customer.id"),
are_optional_values_invalid(self.email.as_ref(), email.as_ref())
.then_some("email and customer.email"),
are_optional_values_invalid(self.name.as_ref(), name.as_ref())
.then_some("name and customer.name"),
are_optional_values_invalid(self.phone.as_ref(), phone.as_ref())
.then_some("phone and customer.phone"),
are_optional_values_invalid(
self.phone_country_code.as_ref(),
phone_country_code.as_ref(),
)
.then_some("phone_country_code and customer.phone_country_code"),
]
.into_iter()
.flatten()
.collect::<Vec<_>>();
if invalid_fields.is_empty() {
None
} else {
Some(invalid_fields)
}
} else {
None
}
}
pub fn get_feature_metadata_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<serde_json::Value>,
common_utils::errors::ParsingError,
> {
self.feature_metadata
.as_ref()
.map(Encode::encode_to_value)
.transpose()
}
pub fn get_connector_metadata_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<serde_json::Value>,
common_utils::errors::ParsingError,
> {
self.connector_metadata
.as_ref()
.map(Encode::encode_to_value)
.transpose()
}
pub fn get_allowed_payment_method_types_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<serde_json::Value>,
common_utils::errors::ParsingError,
> {
self.allowed_payment_method_types
.as_ref()
.map(Encode::encode_to_value)
.transpose()
}
pub fn get_order_details_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<Vec<pii::SecretSerdeValue>>,
common_utils::errors::ParsingError,
> {
self.order_details
.as_ref()
.map(|od| {
od.iter()
.map(|order| order.encode_to_value().map(Secret::new))
.collect::<Result<Vec<_>, _>>()
})
.transpose()
}
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod payments_request_test {
use common_utils::generate_customer_id_of_default_length;
use super::*;
#[test]
fn test_valid_case_where_customer_details_are_passed_only_once() {
let customer_id = generate_customer_id_of_default_length();
let payments_request = PaymentsRequest {
customer_id: Some(customer_id),
..Default::default()
};
assert!(payments_request
.validate_customer_details_in_request()
.is_none());
}
#[test]
fn test_valid_case_where_customer_id_is_passed_in_both_places() {
let customer_id = generate_customer_id_of_default_length();
let customer_object = CustomerDetails {
id: customer_id.clone(),
name: None,
email: None,
phone: None,
phone_country_code: None,
tax_registration_id: None,
};
let payments_request = PaymentsRequest {
customer_id: Some(customer_id),
customer: Some(customer_object),
..Default::default()
};
assert!(payments_request
.validate_customer_details_in_request()
.is_none());
}
#[test]
fn test_invalid_case_where_customer_id_is_passed_in_both_places() {
let customer_id = generate_customer_id_of_default_length();
let another_customer_id = generate_customer_id_of_default_length();
let customer_object = CustomerDetails {
id: customer_id.clone(),
name: None,
email: None,
phone: None,
phone_country_code: None,
tax_registration_id: None,
};
let payments_request = PaymentsRequest {
customer_id: Some(another_customer_id),
customer: Some(customer_object),
..Default::default()
};
assert_eq!(
payments_request.validate_customer_details_in_request(),
Some(vec!["customer_id and customer.id"])
);
}
}
/// Details of surcharge applied on this payment, if applicable
#[derive(
Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq,
)]
pub struct RequestSurchargeDetails {
#[schema(value_type = i64, example = 6540)]
pub surcharge_amount: MinorUnit,
pub tax_amount: Option<MinorUnit>,
}
// for v2 use the type from common_utils::types
#[cfg(feature = "v1")]
/// Browser information to be used for 3DS 2.0
#[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct BrowserInformation {
/// Color depth supported by the browser
pub color_depth: Option<u8>,
/// Whether java is enabled in the browser
pub java_enabled: Option<bool>,
/// Whether javascript is enabled in the browser
pub java_script_enabled: Option<bool>,
/// Language supported
pub language: Option<String>,
/// The screen height in pixels
pub screen_height: Option<u32>,
/// The screen width in pixels
pub screen_width: Option<u32>,
/// Time zone of the client
pub time_zone: Option<i32>,
/// Ip address of the client
#[schema(value_type = Option<String>)]
pub ip_address: Option<std::net::IpAddr>,
/// List of headers that are accepted
#[schema(
example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
)]
pub accept_header: Option<String>,
/// User-agent of the browser
pub user_agent: Option<String>,
/// The os type of the client device
pub os_type: Option<String>,
/// The os version of the client device
pub os_version: Option<String>,
/// The device model of the client
pub device_model: Option<String>,
}
impl RequestSurchargeDetails {
pub fn is_surcharge_zero(&self) -> bool {
self.surcharge_amount == MinorUnit::new(0)
&& self.tax_amount.unwrap_or_default() == MinorUnit::new(0)
}
pub fn get_total_surcharge_amount(&self) -> MinorUnit {
self.surcharge_amount + self.tax_amount.unwrap_or_default()
}
pub fn get_surcharge_amount(&self) -> MinorUnit {
self.surcharge_amount
}
pub fn get_tax_amount(&self) -> Option<MinorUnit> {
self.tax_amount
}
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)]
pub struct PaymentAttemptResponse { | crates/api_models/src/payments.rs#chunk1 | api_models | chunk | 8,184 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::RefundSync for Opennode {} | crates/hyperswitch_connectors/src/connectors/opennode.rs | hyperswitch_connectors | impl_block | 11 | rust | null | Opennode | api::RefundSync for | impl api::RefundSync for for Opennode | null | null | null | null | null | null | null | null |
pub struct BillwerkPaymentsResponse {
state: BillwerkPaymentState,
handle: String,
error: Option<String>,
error_state: Option<String>,
} | crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs | hyperswitch_connectors | struct_definition | 34 | rust | BillwerkPaymentsResponse | null | null | null | null | null | null | null | null | null | null | null |
pub async fn organization_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::OrganizationCreateRequest>,
) -> HttpResponse {
let flow = Flow::OrganizationCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| create_organization(state, req),
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/admin.rs | router | function_signature | 115 | rust | null | null | null | null | organization_create | null | null | null | null | null | null | null |
impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsUpdateIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: path.into_inner(),
payload: json_payload.into_inner(),
};
let global_payment_id = internal_payload.global_payment_id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account.clone(), auth.key_store.clone()),
));
payments::payments_intent_core::<
api_types::PaymentUpdateIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentUpdateIntent>,
>(
state,
req_state,
merchant_context,
auth.profile,
payments::operations::PaymentUpdateIntent,
req.payload,
global_payment_id.clone(),
header_payload.clone(),
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/payments.rs | router | impl_block | 323 | rust | null | Responder | null | impl Responder | null | null | null | null | null | null | null | null |
impl Responder {
let flow = Flow::UpdateDynamicRoutingConfigs;
let routing_payload_wrapper = routing_types::EliminationRoutingPayloadWrapper {
updated_config: json_payload.into_inner(),
algorithm_id: path.clone().algorithm_id,
profile_id: path.clone().profile_id,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
routing_payload_wrapper.clone(),
|state, _, wrapper: routing_types::EliminationRoutingPayloadWrapper, _| async {
Box::pin(routing::elimination_routing_update_configs(
state,
wrapper.updated_config,
wrapper.algorithm_id,
wrapper.profile_id,
))
.await
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
required_permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/routing.rs | router | impl_block | 236 | rust | null | Responder | null | impl Responder | null | null | null | null | null | null | null | null |
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> {
generics::generic_insert(conn, self).await
} | crates/diesel_models/src/query/cards_info.rs | diesel_models | function_signature | 33 | rust | null | null | null | null | insert | null | null | null | null | null | null | null |
File: crates/diesel_models/src/user_authentication_method.rs
Public structs: 3
use common_utils::encryption::Encryption;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::{enums, schema::user_authentication_methods};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))]
pub struct UserAuthenticationMethod {
pub id: String,
pub auth_id: String,
pub owner_id: String,
pub owner_type: enums::Owner,
pub auth_type: enums::UserAuthType,
pub private_config: Option<Encryption>,
pub public_config: Option<serde_json::Value>,
pub allow_signup: bool,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub email_domain: String,
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = user_authentication_methods)]
pub struct UserAuthenticationMethodNew {
pub id: String,
pub auth_id: String,
pub owner_id: String,
pub owner_type: enums::Owner,
pub auth_type: enums::UserAuthType,
pub private_config: Option<Encryption>,
pub public_config: Option<serde_json::Value>,
pub allow_signup: bool,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub email_domain: String,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = user_authentication_methods)]
pub struct OrgAuthenticationMethodUpdateInternal {
pub private_config: Option<Encryption>,
pub public_config: Option<serde_json::Value>,
pub last_modified_at: PrimitiveDateTime,
pub email_domain: Option<String>,
}
pub enum UserAuthenticationMethodUpdate {
UpdateConfig {
private_config: Option<Encryption>,
public_config: Option<serde_json::Value>,
},
EmailDomain {
email_domain: String,
},
}
impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInternal {
fn from(value: UserAuthenticationMethodUpdate) -> Self {
let last_modified_at = common_utils::date_time::now();
match value {
UserAuthenticationMethodUpdate::UpdateConfig {
private_config,
public_config,
} => Self {
private_config,
public_config,
last_modified_at,
email_domain: None,
},
UserAuthenticationMethodUpdate::EmailDomain { email_domain } => Self {
private_config: None,
public_config: None,
last_modified_at,
email_domain: Some(email_domain),
},
}
}
}
| crates/diesel_models/src/user_authentication_method.rs | diesel_models | full_file | 584 | null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/common_utils/src/types/primitive_wrappers.rs
Public functions: 1
Public structs: 3
pub(crate) mod bool_wrappers {
use serde::{Deserialize, Serialize};
/// Bool that represents if Extended Authorization is Applied or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ExtendedAuthorizationAppliedBool(bool);
impl From<bool> for ExtendedAuthorizationAppliedBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct RequestExtendedAuthorizationBool(bool);
impl From<bool> for RequestExtendedAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl RequestExtendedAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is always Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysRequestExtendedAuthorization(bool);
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
}
| crates/common_utils/src/types/primitive_wrappers.rs | common_utils | full_file | 952 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn profile_acquirer_update() { /* … */
} | crates/openapi/src/routes/profile_acquirer.rs | openapi | function_signature | 13 | rust | null | null | null | null | profile_acquirer_update | null | null | null | null | null | null | null |
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_id));
let m_router_data_response = router_data.response.clone();
let mandate_update_fut = tokio::spawn(
async move {
mandate::update_connector_mandate_id(
m_db.as_ref(),
&m_router_data_merchant_id,
m_payment_data_mandate_id,
m_payment_method_id,
m_router_data_response,
storage_scheme,
)
.await
}
.in_current_span(),
);
let (payment_intent, _, payment_attempt) = futures::try_join!(
utils::flatten_join_error(payment_intent_fut),
utils::flatten_join_error(mandate_update_fut),
utils::flatten_join_error(payment_attempt_fut)
)?;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
{
if payment_intent.status.is_in_terminal_state()
&& business_profile.dynamic_routing_algorithm.is_some()
{
let dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef =
business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DynamicRoutingAlgorithmRef not found in profile")?;
let state = state.clone();
let profile_id = business_profile.get_id().to_owned();
let payment_attempt = payment_attempt.clone();
let dynamic_routing_config_params_interpolator =
routing_helpers::DynamicRoutingConfigParamsInterpolator::new(
payment_attempt.payment_method,
payment_attempt.payment_method_type,
payment_attempt.authentication_type,
payment_attempt.currency,
payment_data
.address
.get_payment_billing()
.and_then(|address| address.clone().address)
.and_then(|address| address.country),
payment_attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
payment_attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_isin"))
.and_then(|card_isin| card_isin.as_str())
.map(|card_isin| card_isin.to_string()),
);
tokio::spawn(
async move {
let should_route_to_open_router =
state.conf.open_router.dynamic_routing_enabled;
if should_route_to_open_router {
routing_helpers::update_gateway_score_helper_with_open_router(
&state,
&payment_attempt,
&profile_id,
dynamic_routing_algo_ref.clone(),
)
.await
.map_err(|e| logger::error!(open_router_update_gateway_score_err=?e))
.ok();
} else {
routing_helpers::push_metrics_with_update_window_for_success_based_routing(
&state,
&payment_attempt,
routable_connectors.clone(),
&profile_id,
dynamic_routing_algo_ref.clone(),
dynamic_routing_config_params_interpolator.clone(),
)
.await
.map_err(|e| logger::error!(success_based_routing_metrics_error=?e))
.ok();
if let Some(gsm_error_category) = gsm_error_category {
if gsm_error_category.should_perform_elimination_routing() {
logger::info!("Performing update window for elimination routing");
routing_helpers::update_window_for_elimination_routing(
&state,
&payment_attempt,
&profile_id,
dynamic_routing_algo_ref.clone(),
dynamic_routing_config_params_interpolator.clone(),
gsm_error_category,
)
.await
.map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))
.ok();
};
};
routing_helpers::push_metrics_with_update_window_for_contract_based_routing(
&state,
&payment_attempt,
routable_connectors,
&profile_id,
dynamic_routing_algo_ref,
dynamic_routing_config_params_interpolator,
)
.await
.map_err(|e| logger::error!(contract_based_routing_metrics_error=?e))
.ok();
}
}
.in_current_span(),
);
}
}
payment_data.payment_intent = payment_intent;
payment_data.payment_attempt = payment_attempt;
router_data.payment_method_status.and_then(|status| {
payment_data
.payment_method_info
.as_mut()
.map(|info| info.status = status)
});
if payment_data.payment_attempt.status == enums::AttemptStatus::Failure {
let _ = card_testing_guard_utils::increment_blocked_count_in_cache(
state,
payment_data.card_testing_guard_data.clone(),
)
.await;
}
match router_data.integrity_check {
Ok(()) => Ok(payment_data),
Err(err) => {
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
(
"connector",
payment_data
.payment_attempt
.connector
.clone()
.unwrap_or_default(),
),
(
"merchant_id",
payment_data.payment_attempt.merchant_id.clone(),
)
),
);
Err(error_stack::Report::new(
errors::ApiErrorResponse::IntegrityCheckFailed {
connector_transaction_id: payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
reason: payment_data
.payment_attempt
.error_message
.unwrap_or_default(),
field_names: err.field_names,
},
))
}
}
}
#[cfg(feature = "v2")]
async fn update_payment_method_status_and_ntid<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<()> {
todo!()
}
#[cfg(feature = "v1")]
async fn update_payment_method_status_and_ntid<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<()> {
// If the payment_method is deleted then ignore the error related to retrieving payment method
// This should be handled when the payment method is soft deleted
if let Some(id) = &payment_data.payment_attempt.payment_method_id {
let payment_method = match state
.store
.find_payment_method(&(state.into()), key_store, id, storage_scheme)
.await
{
Ok(payment_method) => payment_method,
Err(error) => {
if error.current_context().is_db_not_found() {
logger::info!(
"Payment Method not found in db and skipping payment method update {:?}",
error
);
return Ok(());
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error retrieving payment method from db in update_payment_method_status_and_ntid")?
}
}
};
let pm_resp_network_transaction_id = payment_response
.map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp {
network_transaction_id
} else {None})
.map_err(|err| {
logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response");
})
.ok()
.flatten();
let network_transaction_id = if payment_data.payment_intent.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
{
if pm_resp_network_transaction_id.is_some() {
pm_resp_network_transaction_id
} else {
logger::info!("Skip storing network transaction id");
None
}
} else {
None
};
let pm_update = if payment_method.status != common_enums::PaymentMethodStatus::Active
&& payment_method.status != attempt_status.into()
{
let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status);
payment_data
.payment_method_info
.as_mut()
.map(|info| info.status = updated_pm_status);
storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status: Some(updated_pm_status),
}
} else {
storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status: None,
}
};
state
.store
.update_payment_method(
&(state.into()),
key_store,
payment_method,
pm_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
};
Ok(())
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for &PaymentResponse {
type Data = PaymentConfirmData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsAuthorizeData> + Send + Sync),
> {
Ok(*self)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for PaymentResponse {
type Data = PaymentConfirmData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsAuthorizeData> + Send + Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::PaymentsCaptureData> for PaymentResponse {
type Data = hyperswitch_domain_models::payments::PaymentCaptureData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsCaptureData> + Send + Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone>
PostUpdateTracker<
F,
hyperswitch_domain_models::payments::PaymentCaptureData<F>,
types::PaymentsCaptureData,
> for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: hyperswitch_domain_models::payments::PaymentCaptureData<F>,
response: types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<hyperswitch_domain_models::payments::PaymentCaptureData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsCaptureData,
hyperswitch_domain_models::payments::PaymentCaptureData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsAuthorizeData,
PaymentConfirmData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
let attempt_status = updated_payment_attempt.status;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
if let Some(payment_method) = &payment_data.payment_method {
match attempt_status {
common_enums::AttemptStatus::AuthenticationFailed
| common_enums::AttemptStatus::RouterDeclined
| common_enums::AttemptStatus::AuthorizationFailed
| common_enums::AttemptStatus::Voided
| common_enums::AttemptStatus::VoidedPostCharge
| common_enums::AttemptStatus::VoidInitiated
| common_enums::AttemptStatus::CaptureFailed
| common_enums::AttemptStatus::VoidFailed
| common_enums::AttemptStatus::AutoRefunded
| common_enums::AttemptStatus::Unresolved
| common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::Failure
| common_enums::AttemptStatus::Expired => (),
common_enums::AttemptStatus::Started
| common_enums::AttemptStatus::AuthenticationPending
| common_enums::AttemptStatus::AuthenticationSuccessful
| common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::PartiallyAuthorized
| common_enums::AttemptStatus::Charged
| common_enums::AttemptStatus::Authorizing
| common_enums::AttemptStatus::CodInitiated
| common_enums::AttemptStatus::PartialCharged
| common_enums::AttemptStatus::PartialChargedAndChargeable
| common_enums::AttemptStatus::CaptureInitiated
| common_enums::AttemptStatus::PaymentMethodAwaited
| common_enums::AttemptStatus::ConfirmationAwaited
| common_enums::AttemptStatus::DeviceDataCollectionPending
| common_enums::AttemptStatus::IntegrityFailure => {
let pm_update_status = enums::PaymentMethodStatus::Active;
// payment_methods microservice call
payment_methods::update_payment_method_status_internal(
state,
key_store,
storage_scheme,
pm_update_status,
payment_method.get_id(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method status")?;
}
}
}
Ok(payment_data)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::PaymentsSyncData> for PaymentResponse {
type Data = PaymentStatusData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsSyncData> + Send + Sync)>
{
Ok(self)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentStatusData<F>, types::PaymentsSyncData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentStatusData<F>,
response: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentStatusData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsSyncData,
PaymentStatusData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let payment_attempt = payment_data.payment_attempt;
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for &PaymentResponse {
type Data = PaymentConfirmData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::SetupMandateRequestData> + Send + Sync),
> {
Ok(*self)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for PaymentResponse {
type Data = PaymentConfirmData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::SetupMandateRequestData> + Send + Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
impl
Operation<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> for PaymentResponse
{
type Data =
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
Self::Data,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> + Send
+ Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
impl
Operation<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> for &PaymentResponse
{
type Data =
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
Self::Data,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> + Send
+ Sync),
> {
Ok(*self)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl
PostUpdateTracker<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
>,
response: types::RouterData<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
>
where
types::RouterData<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
// TODO: Add external vault specific post-update logic if needed
Ok(payment_data)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRequestData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::SetupMandateRequestData,
PaymentConfirmData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
router_data: &types::RouterData<
F,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentConfirmData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
// If we received a payment_method_id from connector in the router data response
// Then we either update the payment method or create a new payment method
// The case for updating the payment method is when the payment is created from the payment method service
let Ok(payments_response) = &router_data.response else {
// In case there was an error response from the connector
// We do not take any action related to the payment method
return Ok(());
};
let connector_request_reference_id = payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|token_details| token_details.get_connector_token_request_reference_id());
let connector_token =
payments_response.get_updated_connector_token_details(connector_request_reference_id);
let payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
// TODO: check what all conditions we will need to see if card need to be saved
match (
connector_token
.as_ref()
.and_then(|connector_token| connector_token.connector_mandate_id.clone()),
payment_method_id,
) {
(Some(token), Some(payment_method_id)) => {
if !matches!(
router_data.status,
enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized
) {
return Ok(());
}
let connector_id = payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing connector id")?;
let net_amount = payment_data.payment_attempt.amount_details.get_net_amount();
let currency = payment_data.payment_intent.amount_details.currency;
let connector_token_details_for_payment_method_update =
api_models::payment_methods::ConnectorTokenDetails {
connector_id,
status: common_enums::ConnectorTokenStatus::Active,
connector_token_request_reference_id: connector_token
.and_then(|details| details.connector_token_request_reference_id),
original_payment_authorized_amount: Some(net_amount),
original_payment_authorized_currency: Some(currency),
metadata: None,
token: masking::Secret::new(token),
token_type: common_enums::TokenizationType::MultiUse,
};
let payment_method_update_request =
api_models::payment_methods::PaymentMethodUpdate {
payment_method_data: None,
connector_token_details: Some(
connector_token_details_for_payment_method_update,
),
};
payment_methods::update_payment_method_core(
state,
merchant_context,
business_profile,
payment_method_update_request,
&payment_method_id,
)
.await
.attach_printable("Failed to update payment method")?;
}
(Some(_), None) => {
// TODO: create a new payment method
}
(None, Some(_)) | (None, None) => {}
}
Ok(())
}
}
#[cfg(feature = "v1")]
fn update_connector_mandate_details_for_the_flow<F: Clone>(
connector_mandate_id: Option<String>,
mandate_metadata: Option<masking::Secret<serde_json::Value>>,
connector_mandate_request_reference_id: Option<String>,
payment_data: &mut PaymentData<F>,
) -> RouterResult<()> {
let mut original_connector_mandate_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone()));
let connector_mandate_reference_id = if connector_mandate_id.is_some() {
if let Some(ref mut record) = original_connector_mandate_reference_id {
record.update(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
);
Some(record.clone())
} else {
Some(ConnectorMandateReferenceId::new(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
))
}
} else {
original_connector_mandate_reference_id
};
payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
.clone()
.map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
MandateReferenceId::ConnectorMandateId(connector_mandate_id)
}),
});
Ok(())
}
fn response_to_capture_update(
multiple_capture_data: &MultipleCaptureData,
response_list: HashMap<String, CaptureSyncResponse>,
) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> {
let mut capture_update_list = vec![];
let mut unmapped_captures = vec![];
for (connector_capture_id, capture_sync_response) in response_list {
let capture =
multiple_capture_data.get_capture_by_connector_capture_id(&connector_capture_id);
if let Some(capture) = capture {
capture_update_list.push((
capture.clone(),
storage::CaptureUpdate::foreign_try_from(capture_sync_response)?,
))
} else {
// connector_capture_id may not be populated in the captures table in some case
// if so, we try to map the unmapped capture response and captures in DB.
unmapped_captures.push(capture_sync_response)
}
}
capture_update_list.extend(get_capture_update_for_unmapped_capture_responses(
unmapped_captures,
multiple_capture_data,
)?);
Ok(capture_update_list)
}
fn get_capture_update_for_unmapped_capture_responses(
unmapped_capture_sync_response_list: Vec<CaptureSyncResponse>,
multiple_capture_data: &MultipleCaptureData,
) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> {
let mut result = Vec::new();
let captures_without_connector_capture_id: Vec<_> = multiple_capture_data
.get_pending_captures_without_connector_capture_id()
.into_iter()
.cloned()
.collect();
for capture_sync_response in unmapped_capture_sync_response_list {
if let Some(capture) = captures_without_connector_capture_id
.iter()
.find(|capture| {
capture_sync_response.get_connector_response_reference_id()
== Some(capture.capture_id.clone())
|| capture_sync_response.get_amount_captured() == Some(capture.amount)
})
{
result.push((
capture.clone(),
storage::CaptureUpdate::foreign_try_from(capture_sync_response)?,
))
}
}
Ok(result)
}
fn get_total_amount_captured<F: Clone, T: types::Capturable>(
request: &T,
amount_captured: Option<MinorUnit>,
router_data_status: enums::AttemptStatus,
payment_data: &PaymentData<F>,
) -> Option<MinorUnit> {
match &payment_data.multiple_capture_data {
Some(multiple_capture_data) => {
//multiple capture
Some(multiple_capture_data.get_total_blocked_amount())
}
None => {
//Non multiple capture
let amount = request
.get_captured_amount(
amount_captured.map(MinorUnit::get_amount_as_i64),
payment_data,
)
.map(MinorUnit::new);
amount_captured.or_else(|| {
if router_data_status == enums::AttemptStatus::Charged {
amount
} else {
None
}
})
}
}
}
| crates/router/src/core/payments/operations/payment_response.rs#chunk2 | router | chunk | 7,593 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn get_permission_groups(&self) -> Vec<PermissionGroup> {
self.groups
.iter()
.flat_map(|group| group.accessible_groups())
.collect::<HashSet<_>>()
.into_iter()
.collect()
} | crates/router/src/services/authorization/roles.rs | router | function_signature | 54 | rust | null | null | null | null | get_permission_groups | null | null | null | null | null | null | null |
File: crates/router/src/core/payments/flows/session_update_flow.rs
use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> for PaymentData<api::SdkSessionUpdate>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
Box::pin(
transformers::construct_router_data_to_update_calculated_tax::<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
),
)
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData>
for types::RouterData<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| crates/router/src/core/payments/flows/session_update_flow.rs | router | full_file | 949 | null | null | null | null | null | null | null | null | null | null | null | null | null |
Documentation: api-reference/v1/merchant-account/merchant-account--create.mdx
# Type: Doc File
---
openapi: post /accounts
--- | api-reference/v1/merchant-account/merchant-account--create.mdx | null | doc_file | 32 | doc | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PlacetopayNextActionRequest {
auth: PlacetopayAuth,
internal_reference: u64,
action: PlacetopayNextAction,
} | crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs | hyperswitch_connectors | struct_definition | 38 | rust | PlacetopayNextActionRequest | null | null | null | null | null | null | null | null | null | null | null |
pub async fn refunds_retrieve_with_gateway_creds(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalRefundId>,
payload: web::Json<api_models::refunds::RefundsRetrievePayload>,
) -> HttpResponse {
let flow = match payload.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let refund_request = refunds::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: payload.force_sync,
merchant_connector_details: payload.merchant_connector_details.clone(),
};
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
)
};
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_retrieve_core_with_refund_id(
state,
merchant_context,
auth.profile,
refund_request,
)
},
auth_type,
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/refunds.rs | router | function_signature | 365 | rust | null | null | null | null | refunds_retrieve_with_gateway_creds | null | null | null | null | null | null | null |
pub struct UsersConfigs {
pub user_email: String,
pub user_password: String,
pub wrong_password: String,
pub user_base_email_for_signup: String,
pub user_domain_for_signup: String,
} | crates/test_utils/src/connector_auth.rs | test_utils | struct_definition | 46 | rust | UsersConfigs | null | null | null | null | null | null | null | null | null | null | null |
impl FraudCheckRecordReturn for Riskified {} | crates/hyperswitch_connectors/src/connectors/riskified.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Riskified | FraudCheckRecordReturn for | impl FraudCheckRecordReturn for for Riskified | null | null | null | null | null | null | null | null |
pub async fn add_process_dispute_task_to_pt(
db: &dyn StorageInterface,
connector_name: &str,
dispute_payload: &DisputeSyncResponse,
merchant_id: common_utils::id_type::MerchantId,
schedule_time: Option<time::PrimitiveDateTime>,
) -> common_utils::errors::CustomResult<(), errors::StorageError> {
match schedule_time {
Some(time) => {
TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", "dispute_process")),
);
let tracking_data = disputes::ProcessDisputePTData {
connector_name: connector_name.to_string(),
dispute_payload: dispute_payload.clone(),
merchant_id: merchant_id.clone(),
};
let runner = common_enums::ProcessTrackerRunner::ProcessDisputeWorkflow;
let task = "DISPUTE_PROCESS";
let tag = ["PROCESS", "DISPUTE"];
let process_tracker_id = scheduler::utils::get_process_tracker_id(
runner,
task,
&dispute_payload.connector_dispute_id.clone(),
&merchant_id,
);
let process_tracker_entry = diesel_models::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
time,
common_types::consts::API_VERSION,
)
.map_err(errors::StorageError::from)?;
db.insert_process(process_tracker_entry).await?;
Ok(())
}
None => Ok(()),
}
} | crates/router/src/core/disputes.rs | router | function_signature | 317 | rust | null | null | null | null | add_process_dispute_task_to_pt | null | null | null | null | null | null | null |
pub struct PaypalIncrementalAuthStatusDetails {
reason: PaypalStatusPendingReason,
} | crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs | hyperswitch_connectors | struct_definition | 18 | rust | PaypalIncrementalAuthStatusDetails | null | null | null | null | null | null | null | null | null | null | null |
Documentation: api-reference/v1/customers/customers--list.mdx
# Type: Doc File
---
openapi: get /customers/list
--- | api-reference/v1/customers/customers--list.mdx | null | doc_file | 31 | doc | null | null | null | null | null | null | null | null | null | null | null | null |
impl ProfileNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Profile> {
generics::generic_insert(conn, self).await
}
} | crates/diesel_models/src/query/business_profile.rs | diesel_models | impl_block | 40 | rust | null | ProfileNew | null | impl ProfileNew | null | null | null | null | null | null | null | null |
pub async fn update_by_user_email(
conn: &PgPooledConn,
user_email: &pii::Email,
user_update: UserUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
users_dsl::email.eq(user_email.to_owned()),
UserUpdateInternal::from(user_update),
)
.await
} | crates/diesel_models/src/query/user.rs | diesel_models | function_signature | 106 | rust | null | null | null | null | update_by_user_email | null | null | null | null | null | null | null |
pub async fn relay_flow_decider(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_optional: Option<id_type::ProfileId>,
request: relay_api_models::RelayRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let relay_flow_request = match request.relay_type {
common_enums::RelayType::Refund => {
RelayRequestInner::<RelayRefund>::from_relay_request(request)?
}
};
relay(
state,
merchant_context,
profile_id_optional,
relay_flow_request,
)
.await
} | crates/router/src/core/relay.rs | router | function_signature | 133 | rust | null | null | null | null | relay_flow_decider | null | null | null | null | null | null | null |
pub async fn initiate_pm_collect_link(
state: SessionState,
merchant_context: domain::MerchantContext,
req: payment_methods::PaymentMethodCollectLinkRequest,
) -> RouterResponse<payment_methods::PaymentMethodCollectLinkResponse> {
// Validate request and initiate flow
let pm_collect_link_data =
validator::validate_request_and_initiate_payment_method_collect_link(
&state,
&merchant_context,
&req,
)
.await?;
// Create DB entry
let pm_collect_link = create_pm_collect_db_entry(
&state,
&merchant_context,
&pm_collect_link_data,
req.return_url.clone(),
)
.await?;
let customer_id = id_type::CustomerId::try_from(Cow::from(pm_collect_link.primary_reference))
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})?;
// Return response
let url = pm_collect_link.url.peek();
let response = payment_methods::PaymentMethodCollectLinkResponse {
pm_collect_link_id: pm_collect_link.link_id,
customer_id,
expiry: pm_collect_link.expiry,
link: url::Url::parse(url)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Failed to parse the payment method collect link - {url}")
})?
.into(),
return_url: pm_collect_link.return_url,
ui_config: pm_collect_link.link_data.ui_config,
enabled_payment_methods: pm_collect_link.link_data.enabled_payment_methods,
};
Ok(services::ApplicationResponse::Json(response))
} | crates/router/src/core/payment_methods.rs | router | function_signature | 343 | rust | null | null | null | null | initiate_pm_collect_link | null | null | null | null | null | null | null |
impl DummyConnector {
pub fn server(state: AppState) -> Scope {
let mut routes_with_restricted_access = web::scope("");
#[cfg(not(feature = "external_access_dc"))]
{
routes_with_restricted_access =
routes_with_restricted_access.guard(actix_web::guard::Host("localhost"));
}
routes_with_restricted_access = routes_with_restricted_access
.service(web::resource("/payment").route(web::post().to(dummy_connector_payment)));
web::scope("/dummy-connector")
.app_data(web::Data::new(state))
.service(routes_with_restricted_access)
}
} | crates/router/src/routes/app.rs | router | impl_block | 132 | rust | null | DummyConnector | null | impl DummyConnector | null | null | null | null | null | null | null | null |
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?,
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetQueryParams {
payer_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalConfirmRequest {
create_transaction_request: PaypalConfirmTransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalConfirmTransactionRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: TransactionConfirmRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionConfirmRequest {
transaction_type: TransactionType,
payment: PaypalPaymentConfirm,
ref_trans_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalPaymentConfirm {
pay_pal: Paypal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Paypal {
#[serde(rename = "payerID")]
payer_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalQueryParams {
#[serde(rename = "PayerID")]
payer_id: Option<Secret<String>>,
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsCompleteAuthorizeRouterData>>
for PaypalConfirmRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let params = item
.router_data
.request
.redirect_response
.as_ref()
.and_then(|redirect_response| redirect_response.params.as_ref())
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let query_params: PaypalQueryParams = serde_urlencoded::from_str(params.peek())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Failed to parse connector response")?;
let payer_id = query_params.payer_id;
let transaction_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => Ok(TransactionType::ContinueAuthorization),
Some(enums::CaptureMethod::SequentialAutomatic)
| Some(enums::CaptureMethod::Automatic)
| None => Ok(TransactionType::ContinueCapture),
Some(enums::CaptureMethod::ManualMultiple) => {
Err(errors::ConnectorError::NotSupported {
message: enums::CaptureMethod::ManualMultiple.to_string(),
connector: "authorizedotnet",
})
}
Some(enums::CaptureMethod::Scheduled) => Err(errors::ConnectorError::NotSupported {
message: enums::CaptureMethod::Scheduled.to_string(),
connector: "authorizedotnet",
}),
}?;
let transaction_request = TransactionConfirmRequest {
transaction_type,
payment: PaypalPaymentConfirm {
pay_pal: Paypal { payer_id },
},
ref_trans_id: item.router_data.request.connector_transaction_id.clone(),
};
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: PaypalConfirmTransactionRequest {
merchant_authentication,
transaction_request,
},
})
}
}
| crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs#chunk2 | hyperswitch_connectors | chunk | 1,005 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub trait VaultingInterface {
fn get_vaulting_request_url() -> &'static str;
fn get_vaulting_flow_name() -> &'static str;
} | crates/router/src/types/payment_methods.rs | router | trait_definition | 35 | rust | null | null | VaultingInterface | null | null | null | null | null | null | null | null | null |
impl SPTFlow {
async fn is_required(
&self,
user: &UserFromStorage,
path: &[TokenPurpose],
state: &SessionState,
user_tenant_id: &id_type::TenantId,
) -> UserResult<bool> {
match self {
// Auth
Self::AuthSelect => Ok(true),
Self::SSO => Ok(true),
// TOTP
Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)),
// Main email APIs
Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true),
Self::VerifyEmail => Ok(true),
// Final Checks
Self::ForceSetPassword => user
.is_password_rotate_required(state)
.map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)),
Self::MerchantSelect => Ok(state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user.get_user_id(),
tenant_id: user_tenant_id,
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)?
.is_empty()),
}
}
pub async fn generate_spt(
self,
state: &SessionState,
next_flow: &NextFlow,
) -> UserResult<Secret<String>> {
auth::SinglePurposeToken::new_token(
next_flow.user.get_user_id().to_string(),
self.into(),
next_flow.origin.clone(),
&state.conf,
next_flow.path.to_vec(),
Some(state.tenant.tenant_id.clone()),
)
.await
.map(|token| token.into())
}
} | crates/router/src/types/domain/user/decision_manager.rs | router | impl_block | 403 | rust | null | SPTFlow | null | impl SPTFlow | null | null | null | null | null | null | null | null |
pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::id.eq(id.to_owned()),
)
.await
} | crates/diesel_models/src/query/callback_mapper.rs | diesel_models | function_signature | 64 | rust | null | null | null | null | find_by_id | null | null | null | null | null | null | null |
pub fn add_bool_filter_clause(
&mut self,
key: impl ToSql<T>,
value: impl ToSql<T>,
) -> QueryResult<()> {
self.add_custom_filter_clause(key, value, FilterTypes::EqualBool)
} | crates/analytics/src/query.rs | analytics | function_signature | 53 | rust | null | null | null | null | add_bool_filter_clause | null | null | null | null | null | null | null |
File: crates/diesel_models/src/blocklist_fingerprint.rs
Public structs: 2
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use crate::schema::blocklist_fingerprint;
#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = blocklist_fingerprint)]
pub struct BlocklistFingerprintNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub encrypted_fingerprint: String,
pub created_at: time::PrimitiveDateTime,
}
#[derive(
Clone, Debug, Eq, PartialEq, Queryable, Identifiable, Selectable, Deserialize, Serialize,
)]
#[diesel(table_name = blocklist_fingerprint, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))]
pub struct BlocklistFingerprint {
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub encrypted_fingerprint: String,
pub created_at: time::PrimitiveDateTime,
}
| crates/diesel_models/src/blocklist_fingerprint.rs | diesel_models | full_file | 258 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl FileUpload for Stripe {
fn validate_file_upload(
&self,
purpose: FilePurpose,
file_size: i32,
file_type: mime::Mime,
) -> CustomResult<(), ConnectorError> {
match purpose {
FilePurpose::DisputeEvidence => {
let supported_file_types = ["image/jpeg", "image/png", "application/pdf"];
// 5 Megabytes (MB)
if file_size > 5000000 {
Err(ConnectorError::FileValidationFailed {
reason: "file_size exceeded the max file size of 5MB".to_owned(),
})?
}
if !supported_file_types.contains(&file_type.to_string().as_str()) {
Err(ConnectorError::FileValidationFailed {
reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(),
})?
}
}
}
Ok(())
}
} | crates/hyperswitch_connectors/src/connectors/stripe.rs | hyperswitch_connectors | impl_block | 201 | rust | null | Stripe | FileUpload for | impl FileUpload for for Stripe | null | null | null | null | null | null | null | null |
pub struct ZenBrowserDetails {
color_depth: String,
java_enabled: bool,
lang: String,
screen_height: String,
screen_width: String,
timezone: String,
accept_header: String,
window_size: String,
user_agent: String,
} | crates/hyperswitch_connectors/src/connectors/zen/transformers.rs | hyperswitch_connectors | struct_definition | 59 | rust | ZenBrowserDetails | null | null | null | null | null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.