text
string
file_path
string
module
string
type
string
tokens
int64
language
string
struct_name
string
type_name
string
trait_name
string
impl_type
string
function_name
string
source
string
section
string
keys
list
macro_type
string
url
string
title
string
chunk_index
int64
pub struct BillingConnectorAdditionalCardInfo { /// Card Network pub card_network: Option<common_enums::enums::CardNetwork>, /// Card Issuer pub card_issuer: Option<String>, }
crates/diesel_models/src/types.rs
diesel_models
struct_definition
45
rust
BillingConnectorAdditionalCardInfo
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorSpecifications for Silverflow { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&SILVERFLOW_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*SILVERFLOW_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&SILVERFLOW_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/silverflow.rs
hyperswitch_connectors
impl_block
111
rust
null
Silverflow
ConnectorSpecifications for
impl ConnectorSpecifications for for Silverflow
null
null
null
null
null
null
null
null
impl<'a> KafkaRefundEvent<'a> { pub fn from_storage(refund: &'a Refund) -> Self { let Refund { payment_id, merchant_id, connector_transaction_id, connector, connector_refund_id, external_reference_id, refund_type, total_amount, currency, refund_amount, refund_status, sent_to_gateway, refund_error_message, metadata, refund_arn, created_at, modified_at, description, attempt_id, refund_reason, refund_error_code, profile_id, updated_by, charges, organization_id, split_refunds, unified_code, unified_message, processor_refund_data, processor_transaction_data, id, merchant_reference_id, connector_id, } = refund; Self { refund_id: id, merchant_reference_id, payment_id, merchant_id, connector_transaction_id, connector, connector_refund_id: connector_refund_id.as_ref(), external_reference_id: external_reference_id.as_ref(), refund_type, total_amount, currency, refund_amount, refund_status, sent_to_gateway, refund_error_message: refund_error_message.as_ref(), refund_arn: refund_arn.as_ref(), created_at: created_at.assume_utc(), modified_at: modified_at.assume_utc(), description: description.as_ref(), attempt_id, refund_reason: refund_reason.as_ref(), refund_error_code: refund_error_code.as_ref(), profile_id: profile_id.as_ref(), organization_id, metadata: metadata.as_ref(), updated_by, merchant_connector_id: connector_id.as_ref(), charges: charges.as_ref(), connector_refund_data: processor_refund_data.as_ref(), connector_transaction_data: processor_transaction_data.as_ref(), split_refunds: split_refunds.as_ref(), unified_code: unified_code.as_ref(), unified_message: unified_message.as_ref(), processor_refund_data: processor_refund_data.as_ref(), processor_transaction_data: processor_transaction_data.as_ref(), } } }
crates/router/src/services/kafka/refund_event.rs
router
impl_block
451
rust
null
KafkaRefundEvent
null
impl KafkaRefundEvent
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.RequestPaymentMethodTypes { "type": "object", "required": [ "payment_method_type" ], "properties": { "payment_method_type": { "$ref": "#/components/schemas/PaymentMethodType" }, "payment_experience": { "allOf": [ { "$ref": "#/components/schemas/PaymentExperience" } ], "nullable": true }, "card_networks": { "type": "array", "items": { "$ref": "#/components/schemas/CardNetwork" }, "nullable": true }, "accepted_currencies": { "allOf": [ { "$ref": "#/components/schemas/AcceptedCurrencies" } ], "nullable": true }, "accepted_countries": { "allOf": [ { "$ref": "#/components/schemas/AcceptedCountries" } ], "nullable": true }, "minimum_amount": { "allOf": [ { "$ref": "#/components/schemas/MinorUnit" } ], "nullable": true }, "maximum_amount": { "allOf": [ { "$ref": "#/components/schemas/MinorUnit" } ], "nullable": true }, "recurring_enabled": { "type": "boolean", "description": "Indicates whether the payment method supports recurring payments. Optional.", "example": false, "nullable": true }, "installment_payment_enabled": { "type": "boolean", "description": "Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.", "example": true, "nullable": true } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
409
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "RequestPaymentMethodTypes" ]
null
null
null
null
pub struct ChargebackDocumentUploadResponse { #[serde(rename = "@xmlns")] pub xmlns: String, pub merchant_id: String, pub case_id: String, pub document_id: Option<String>, pub response_code: WorldpayvantivFileUploadResponseCode, pub response_message: String, }
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
hyperswitch_connectors
struct_definition
66
rust
ChargebackDocumentUploadResponse
null
null
null
null
null
null
null
null
null
null
null
impl ThemeNew { pub fn new( theme_id: String, theme_name: String, lineage: ThemeLineage, email_config: EmailThemeConfig, ) -> Self { let now = date_time::now(); Self { theme_id, theme_name, tenant_id: lineage.tenant_id().to_owned(), org_id: lineage.org_id().cloned(), merchant_id: lineage.merchant_id().cloned(), profile_id: lineage.profile_id().cloned(), entity_type: lineage.entity_type(), created_at: now, last_modified_at: now, email_primary_color: email_config.primary_color, email_foreground_color: email_config.foreground_color, email_background_color: email_config.background_color, email_entity_name: email_config.entity_name, email_entity_logo_url: email_config.entity_logo_url, } } }
crates/diesel_models/src/user/theme.rs
diesel_models
impl_block
187
rust
null
ThemeNew
null
impl ThemeNew
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.NextActionData { "oneOf": [ { "type": "object", "description": "Contains the url for redirection flow", "required": [ "redirect_to_url", "type" ], "properties": { "redirect_to_url": { "type": "string" }, "type": { "type": "string", "enum": [ "redirect_to_url" ] } } }, { "type": "object", "required": [ "popup_url", "redirect_response_url", "type" ], "properties": { "popup_url": { "type": "string" }, "redirect_response_url": { "type": "string" }, "type": { "type": "string", "enum": [ "redirect_inside_popup" ] } } }, { "type": "object", "description": "Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc)", "required": [ "bank_transfer_steps_and_charges_details", "type" ], "properties": { "bank_transfer_steps_and_charges_details": { "$ref": "#/components/schemas/BankTransferNextStepsData" }, "type": { "type": "string", "enum": [ "display_bank_transfer_information" ] } } }, { "type": "object", "description": "Contains third party sdk session token response", "required": [ "type" ], "properties": { "session_token": { "allOf": [ { "$ref": "#/components/schemas/SessionToken" } ], "nullable": true }, "type": { "type": "string", "enum": [ "third_party_sdk_session_token" ] } } }, { "type": "object", "description": "Contains url for Qr code image, this qr code has to be shown in sdk", "required": [ "image_data_url", "qr_code_url", "type" ], "properties": { "image_data_url": { "type": "string", "description": "Hyperswitch generated image data source url" }, "display_to_timestamp": { "type": "integer", "format": "int64", "nullable": true }, "qr_code_url": { "type": "string", "description": "The url for Qr code given by the connector" }, "display_text": { "type": "string", "nullable": true }, "border_color": { "type": "string", "nullable": true }, "type": { "type": "string", "enum": [ "qr_code_information" ] } } }, { "type": "object", "description": "Contains url to fetch Qr code data", "required": [ "qr_code_fetch_url", "type" ], "properties": { "qr_code_fetch_url": { "type": "string" }, "type": { "type": "string", "enum": [ "fetch_qr_code_information" ] } } }, { "type": "object", "description": "Contains the download url and the reference number for transaction", "required": [ "voucher_details", "type" ], "properties": { "voucher_details": { "type": "string" }, "type": { "type": "string", "enum": [ "display_voucher_information" ] } } }, { "type": "object", "description": "Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk", "required": [ "display_from_timestamp", "type" ], "properties": { "display_from_timestamp": { "type": "integer" }, "display_to_timestamp": { "type": "integer", "nullable": true }, "poll_config": { "allOf": [ { "$ref": "#/components/schemas/PollConfig" } ], "nullable": true }, "type": { "type": "string", "enum": [ "wait_screen_information" ] } } }, { "type": "object", "description": "Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows", "required": [ "three_ds_data", "type" ], "properties": { "three_ds_data": { "$ref": "#/components/schemas/ThreeDsData" }, "type": { "type": "string", "enum": [ "three_ds_invoke" ] } } }, { "type": "object", "required": [ "next_action_data", "type" ], "properties": { "next_action_data": { "$ref": "#/components/schemas/SdkNextActionData" }, "type": { "type": "string", "enum": [ "invoke_sdk_client" ] } } }, { "type": "object", "description": "Contains consent to collect otp for mobile payment", "required": [ "consent_data_required", "type" ], "properties": { "consent_data_required": { "$ref": "#/components/schemas/MobilePaymentConsent" }, "type": { "type": "string", "enum": [ "collect_otp" ] } } }, { "type": "object", "description": "Contains data required to invoke hidden iframe", "required": [ "iframe_data", "type" ], "properties": { "iframe_data": { "$ref": "#/components/schemas/IframeData" }, "type": { "type": "string", "enum": [ "invoke_hidden_iframe" ] } } } ], "discriminator": { "propertyName": "type" } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
1,429
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "NextActionData" ]
null
null
null
null
/// Validate the amount to capture that is sent in the request pub fn validate_amount_to_capture( &self, request_amount_to_capture: MinorUnit, ) -> Result<(), ValidationError> { common_utils::fp_utils::when(request_amount_to_capture > self.get_net_amount(), || { Err(ValidationError::IncorrectValueProvided { field_name: "amount_to_capture", }) }) }
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
function_signature
87
rust
null
null
null
null
validate_amount_to_capture
null
null
null
null
null
null
null
pub struct MpgsCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, }
crates/hyperswitch_connectors/src/connectors/mpgs/transformers.rs
hyperswitch_connectors
struct_definition
42
rust
MpgsCard
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentsCompleteAuthorize for Worldpay {}
crates/hyperswitch_connectors/src/connectors/worldpay.rs
hyperswitch_connectors
impl_block
10
rust
null
Worldpay
api::PaymentsCompleteAuthorize for
impl api::PaymentsCompleteAuthorize for for Worldpay
null
null
null
null
null
null
null
null
impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {}
crates/analytics/src/sqlx.rs
analytics
impl_block
16
rust
null
SqlxClient
super::frm::metrics::FrmMetricAnalytics for
impl super::frm::metrics::FrmMetricAnalytics for for SqlxClient
null
null
null
null
null
null
null
null
impl ConnectorCommon for ConnectorEnum { fn id(&self) -> &'static str { match self { Self::Old(connector) => connector.id(), Self::New(connector) => connector.id(), } } fn get_currency_unit(&self) -> CurrencyUnit { match self { Self::Old(connector) => connector.get_currency_unit(), Self::New(connector) => connector.get_currency_unit(), } } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_auth_header(auth_type), Self::New(connector) => connector.get_auth_header(auth_type), } } fn common_get_content_type(&self) -> &'static str { match self { Self::Old(connector) => connector.common_get_content_type(), Self::New(connector) => connector.common_get_content_type(), } } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { match self { Self::Old(connector) => connector.base_url(connectors), Self::New(connector) => connector.base_url(connectors), } } fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { match self { Self::Old(connector) => connector.build_error_response(res, event_builder), Self::New(connector) => connector.build_error_response(res, event_builder), } } }
crates/hyperswitch_interfaces/src/connector_integration_interface.rs
hyperswitch_interfaces
impl_block
364
rust
null
ConnectorEnum
ConnectorCommon for
impl ConnectorCommon for for ConnectorEnum
null
null
null
null
null
null
null
null
pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) { let metrics_collection_interval = metrics_collection_interval_in_secs .unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS); let cache_instances = [ &cache::CONFIG_CACHE, &cache::ACCOUNTS_CACHE, &cache::ROUTING_CACHE, &cache::CGRAPH_CACHE, &cache::PM_FILTERS_CGRAPH_CACHE, &cache::DECISION_MANAGER_CACHE, &cache::SURCHARGE_CACHE, &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, &cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, &cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, ]; tokio::spawn(async move { loop { for instance in cache_instances { instance.record_entry_count_metric().await } tokio::time::sleep(std::time::Duration::from_secs( metrics_collection_interval.into(), )) .await } }); }
crates/router/src/routes/metrics/bg_metrics_collector.rs
router
function_signature
213
rust
null
null
null
null
spawn_metrics_collector
null
null
null
null
null
null
null
impl Responder { use hyperswitch_domain_models::payments::PaymentConfirmData; let flow = Flow::ProxyConfirmIntent; // Extract the payment ID from the path let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); // Parse and validate headers let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; // Prepare the internal payload let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id, payload: json_payload.into_inner(), }; // Determine the locking action, if required let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| { let payment_id = req.global_payment_id; let request = req.payload; // Define the operation for proxy payments intent let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); // Call the core proxy logic Box::pin(payments::proxy_for_payments_core::< api_types::Authorize, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<api_types::Authorize>, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), None, )) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, locking_action, )) .await }
crates/router/src/routes/payments.rs
router
impl_block
433
rust
null
Responder
null
impl Responder
null
null
null
null
null
null
null
null
impl VaultData { pub fn get_card_vault_data(&self) -> Option<payment_method_data::Card> { match self { Self::Card(card_data) => Some(card_data.clone()), Self::NetworkToken(_network_token_data) => None, Self::CardAndNetworkToken(vault_data) => Some(vault_data.card_data.clone()), } } pub fn get_network_token_data(&self) -> Option<payment_method_data::NetworkTokenData> { match self { Self::Card(_card_data) => None, Self::NetworkToken(network_token_data) => Some(network_token_data.clone()), Self::CardAndNetworkToken(vault_data) => Some(vault_data.network_token_data.clone()), } } }
crates/hyperswitch_domain_models/src/payments.rs
hyperswitch_domain_models
impl_block
158
rust
null
VaultData
null
impl VaultData
null
null
null
null
null
null
null
null
pub struct NoonSubscriptionData { #[serde(rename = "type")] subscription_type: NoonSubscriptionType, //Short description about the subscription. name: String, max_amount: StringMajorUnit, }
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
hyperswitch_connectors
struct_definition
44
rust
NoonSubscriptionData
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.BankDebitData { "oneOf": [ { "type": "object", "required": [ "ach_bank_debit" ], "properties": { "ach_bank_debit": { "type": "object", "description": "Payment Method data for Ach bank debit", "required": [ "account_number", "routing_number", "card_holder_name", "bank_account_holder_name", "bank_name", "bank_type", "bank_holder_type" ], "properties": { "billing_details": { "allOf": [ { "$ref": "#/components/schemas/BankDebitBilling" } ], "nullable": true }, "account_number": { "type": "string", "description": "Account number for ach bank debit payment", "example": "000123456789" }, "routing_number": { "type": "string", "description": "Routing number for ach bank debit payment", "example": "110000000" }, "card_holder_name": { "type": "string", "example": "John Test" }, "bank_account_holder_name": { "type": "string", "example": "John Doe" }, "bank_name": { "type": "string", "example": "ACH" }, "bank_type": { "type": "string", "example": "Checking" }, "bank_holder_type": { "type": "string", "example": "Personal" } } } } }, { "type": "object", "required": [ "sepa_bank_debit" ], "properties": { "sepa_bank_debit": { "type": "object", "required": [ "iban", "bank_account_holder_name" ], "properties": { "billing_details": { "allOf": [ { "$ref": "#/components/schemas/BankDebitBilling" } ], "nullable": true }, "iban": { "type": "string", "description": "International bank account number (iban) for SEPA", "example": "DE89370400440532013000" }, "bank_account_holder_name": { "type": "string", "description": "Owner name for bank debit", "example": "A. Schneider" } } } } }, { "type": "object", "required": [ "becs_bank_debit" ], "properties": { "becs_bank_debit": { "type": "object", "required": [ "account_number", "bsb_number" ], "properties": { "billing_details": { "allOf": [ { "$ref": "#/components/schemas/BankDebitBilling" } ], "nullable": true }, "account_number": { "type": "string", "description": "Account number for Becs payment method", "example": "000123456" }, "bsb_number": { "type": "string", "description": "Bank-State-Branch (bsb) number", "example": "000000" }, "bank_account_holder_name": { "type": "string", "description": "Owner name for bank debit", "example": "A. Schneider", "nullable": true } } } } }, { "type": "object", "required": [ "bacs_bank_debit" ], "properties": { "bacs_bank_debit": { "type": "object", "required": [ "account_number", "sort_code", "bank_account_holder_name" ], "properties": { "billing_details": { "allOf": [ { "$ref": "#/components/schemas/BankDebitBilling" } ], "nullable": true }, "account_number": { "type": "string", "description": "Account number for Bacs payment method", "example": "00012345" }, "sort_code": { "type": "string", "description": "Sort code for Bacs payment method", "example": "108800" }, "bank_account_holder_name": { "type": "string", "description": "holder name for bank debit", "example": "A. Schneider" } } } } } ] }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
1,084
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "BankDebitData" ]
null
null
null
null
pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> { get_header_value_by_key("api-key".into(), headers)?.get_required_value("api_key") }
crates/router/src/services/authentication.rs
router
function_signature
40
rust
null
null
null
null
get_api_key
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/square.rs Public structs: 1 pub mod transformers; use std::fmt::Debug; use api_models::{ enums, webhooks::{IncomingWebhookEvent, ObjectReferenceId}, }; use base64::Engine; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, request::{Method, Request, RequestBuilder, RequestContent}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, AuthorizeSessionToken, }, router_request_types::{ AccessTokenRequestData, AuthorizeSessionTokenData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, consts, errors, events::connector_api_logs::ConnectorEvent, types::{self, PaymentsAuthorizeType, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use lazy_static::lazy_static; use masking::{Mask, Maskable, PeekInterface}; use transformers::{ self as square, SquareAuthType, SquarePaymentsRequest, SquareRefundRequest, SquareTokenRequest, }; use crate::{ constants::headers, types::ResponseRouterData, utils::{get_header_key_value, RefundsRequestData}, }; #[derive(Debug, Clone)] pub struct Square; impl api::Payment for Square {} impl api::PaymentSession for Square {} impl api::ConnectorAccessToken for Square {} impl api::MandateSetup for Square {} impl api::PaymentAuthorize for Square {} impl api::PaymentAuthorizeSessionToken for Square {} impl api::PaymentSync for Square {} impl api::PaymentCapture for Square {} impl api::PaymentVoid for Square {} impl api::Refund for Square {} impl api::RefundExecute for Square {} impl api::RefundSync for Square {} impl api::PaymentToken for Square {} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Square where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Square { fn id(&self) -> &'static str { "square" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.square.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let auth = SquareAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), format!("Bearer {}", auth.api_key.peek()).into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: square::SquareErrorResponse = res .response .parse_struct("SquareErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); let mut reason_list = Vec::new(); for error_iter in response.errors.iter() { if let Some(error) = error_iter.detail.clone() { reason_list.push(error) } } let reason = reason_list.join(" "); Ok(ErrorResponse { status_code: res.status_code, code: response .errors .first() .and_then(|error| error.code.clone()) .unwrap_or(consts::NO_ERROR_CODE.to_string()), message: response .errors .first() .and_then(|error| error.category.clone()) .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: Some(reason), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Square {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Square { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Square {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Square { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Square".to_string()) .into(), ) } } #[async_trait::async_trait] impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Square { fn get_headers( &self, _req: &TokenizationRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![( headers::CONTENT_TYPE.to_string(), types::TokenizationType::get_content_type(self) .to_string() .into(), )]) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/card-nonce", connectors .square .secondary_base_url .clone() .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?, )) } fn get_request_body( &self, req: &TokenizationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = SquareTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::TokenizationType::get_headers(self, req, connectors)?) .set_body(types::TokenizationType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> where PaymentsResponseData: Clone, { let response: square::SquareTokenResponse = res .response .parse_struct("SquareTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> for Square { fn get_headers( &self, _req: &PaymentsAuthorizeSessionTokenRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![( headers::CONTENT_TYPE.to_string(), PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsAuthorizeSessionTokenRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let auth = SquareAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( "{}payments/hydrate?applicationId={}", connectors .square .secondary_base_url .clone() .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?, auth.key1.peek() )) } fn build_request( &self, req: &PaymentsAuthorizeSessionTokenRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsPreAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPreAuthorizeType::get_headers( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeSessionTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> { let response: square::SquareSessionResponse = res .response .parse_struct("SquareSessionResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Square { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/payments", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = SquarePaymentsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Square { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}v2/payments/{connector_payment_id}", self.base_url(connectors), )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Square { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/payments/{}/complete", self.base_url(connectors), req.request.connector_transaction_id, )) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { if req.request.amount_to_capture != req.request.payment_amount { Err(errors::ConnectorError::NotSupported { message: "Partial Capture".to_string(), connector: "Square", })? } Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Square { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/payments/{}/cancel", self.base_url(connectors), req.request.connector_transaction_id, )) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsVoidResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Square { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/refunds", self.base_url(connectors),)) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = SquareRefundRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: square::RefundResponse = res .response .parse_struct("SquareRefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Square { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/refunds/{}", self.base_url(connectors), req.request.get_connector_refund_id()?, )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: square::RefundResponse = res .response .parse_struct("SquareRefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl IncomingWebhook for Square { fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn common_utils::crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(common_utils::crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let encoded_signature = get_header_key_value("x-square-hmacsha256-signature", request.headers)?; let signature = common_utils::consts::BASE64_ENGINE .decode(encoded_signature) .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; Ok(signature) } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let header_value = request .headers .get(actix_web::http::header::HOST) .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; let authority = header_value .to_str() .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(format!( "https://{}{}{}", authority, request.uri, String::from_utf8_lossy(request.body) ) .into_bytes()) } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { let webhook_body: square::SquareWebhookBody = request .body .parse_struct("SquareWebhookBody") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; match webhook_body.data.object { square::SquareWebhookObject::Payment(_) => Ok(ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId(webhook_body.data.id), )), square::SquareWebhookObject::Refund(_) => Ok(ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.data.id), )), } } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { let details: square::SquareWebhookBody = request .body .parse_struct("SquareWebhookEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(IncomingWebhookEvent::from(details.data.object)) } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let details: square::SquareWebhookBody = request .body .parse_struct("SquareWebhookObject") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(match details.data.object { square::SquareWebhookObject::Payment(square_payments_response_details) => { Box::new(square_payments_response_details) } square::SquareWebhookObject::Refund(square_refund_response_details) => { Box::new(square_refund_response_details) } }) } } lazy_static! { static ref SQUARE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Square", description: "Square is the largest business technology platform serving all kinds of businesses.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Alpha, }; static ref SQUARE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::Discover, common_enums::CardNetwork::UnionPay, common_enums::CardNetwork::Interac, common_enums::CardNetwork::JCB, ]; let mut square_supported_payment_methods = SupportedPaymentMethods::new(); square_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); square_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods, specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network, } }), ), }, ); square_supported_payment_methods }; static ref SQUARE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![enums::EventClass::Payments, enums::EventClass::Refunds,]; } impl ConnectorSpecifications for Square { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&*SQUARE_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*SQUARE_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&*SQUARE_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/square.rs
hyperswitch_connectors
full_file
7,186
null
null
null
null
null
null
null
null
null
null
null
null
null
pub fn construct_pre_authentication_router_data<F: Clone>( state: &SessionState, authentication_connector: String, card: hyperswitch_domain_models::payment_method_data::Card, merchant_connector_account: &payments_helpers::MerchantConnectorAccountType, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult< types::RouterData< F, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, > { let router_request = types::authentication::PreAuthNRequestData { card }; construct_router_data( state, authentication_connector, PaymentMethod::default(), merchant_id, types::PaymentAddress::default(), router_request, merchant_connector_account, None, payment_id, ) }
crates/router/src/core/authentication/transformers.rs
router
function_signature
183
rust
null
null
null
null
construct_pre_authentication_router_data
null
null
null
null
null
null
null
### Documentation - Add architecture and monitoring diagram of hyperswitch ([#1825](https://github.com/juspay/hyperswitch/pull/1825)) ([`125ef2b`](https://github.com/juspay/hyperswitch/commit/125ef2b4f82c922209bcfe161ce4790fe2ee3a86)) ### Miscellaneous Tasks - **configs:** Add `payout_connector_list` config to toml ([#1909](https://github.com/juspay/hyperswitch/pull/1909)) ([`c1e5626`](https://github.com/juspay/hyperswitch/commit/c1e56266df6aabd1c498d6a7ebec324b0df23c12)) - Add connector functionality validation based on connector_type ([#1849](https://github.com/juspay/hyperswitch/pull/1849)) ([`33c6d71`](https://github.com/juspay/hyperswitch/commit/33c6d71a8a71619f811accbc21f3c22c3c279c47)) - Remove spaces at beginning of commit messages when generating changelogs ([#1906](https://github.com/juspay/hyperswitch/pull/1906)) ([`7d13226`](https://github.com/juspay/hyperswitch/commit/7d13226740dbc4c1b6ec19631bb93ba89281d303)) **Full Changelog:** [`v1.18.0...v1.19.0`](https://github.com/juspay/hyperswitch/compare/v1.18.0...v1.19.0) - - - ## 1.18.0 (2023-08-09) ### Features - **connector:** - [Adyen] Add support for card redirection (KNET, BENEFIT) ([#1816](https://github.com/juspay/hyperswitch/pull/1816)) ([`62461f1`](https://github.com/juspay/hyperswitch/commit/62461f1b3849bfde3d0c0608b9efd96334e30f97)) - [Checkout] unify error code, message and reason in error response ([#1855](https://github.com/juspay/hyperswitch/pull/1855)) ([`e8a51c2`](https://github.com/juspay/hyperswitch/commit/e8a51c2abeaead3a78ec7fbe9580cf742f7dfbe3)) - Unified error message & errorCode for blueSnap connector ([#1856](https://github.com/juspay/hyperswitch/pull/1856)) ([`222afee`](https://github.com/juspay/hyperswitch/commit/222afee5d5e18132ae40509fb792d6fd13600069)) - [Adyen] Implement Open Banking Uk in Bank Redirects ([#1802](https://github.com/juspay/hyperswitch/pull/1802)) ([`b9f1270`](https://github.com/juspay/hyperswitch/commit/b9f12708e108c3ac691314d32b7976d7e381eee7)) - [Adyen] Implement Momo Atm(Napas) in Card Redirects ([#1820](https://github.com/juspay/hyperswitch/pull/1820)) ([`8ae6737`](https://github.com/juspay/hyperswitch/commit/8ae67377cca506b4d7017bfd167a5ccdb03e8707)) - [Stax] Implement Bank Debits and Webhooks for Connector Stax ([#1832](https://github.com/juspay/hyperswitch/pull/1832)) ([`0f2bb6c`](https://github.com/juspay/hyperswitch/commit/0f2bb6c09bb929a7274af6049ecff5a5f9049ca1)) - **pm_list:** Add pm required field info for crypto pay ([#1891](https://github.com/juspay/hyperswitch/pull/1891)) ([`c205f06`](https://github.com/juspay/hyperswitch/commit/c205f064b91df483cbf0fb4d581d8908bf8fa673)) - **router:** Add support for multiple partial capture ([#1721](https://github.com/juspay/hyperswitch/pull/1721)) ([`c333fb7`](https://github.com/juspay/hyperswitch/commit/c333fb7fc02cf19d74ca80093552e4c4628f248a)) ### Bug Fixes - **router:** - Add `serde(transparent)` annotation for `PaymentMethodMetadata` ([#1899](https://github.com/juspay/hyperswitch/pull/1899)) ([`2d83917`](https://github.com/juspay/hyperswitch/commit/2d839170fe889051772f5d99cdaff33573b4fb20)) - Send error_reason as error_message in payments and refund flows ([#1878](https://github.com/juspay/hyperswitch/pull/1878)) ([`6982194`](https://github.com/juspay/hyperswitch/commit/69821948c0a31b224e1b519388071b66c0d67eb1)) ### Refactors - **access_token:** Handle timeout errors gracefully ([#1882](https://github.com/juspay/hyperswitch/pull/1882)) ([`cc4136f`](https://github.com/juspay/hyperswitch/commit/cc4136f85f0a64b56c4a09157f9bc4847b920b54)) - **authorize_flow:** Suppress error while saving a card to locker after successful payment ([#1874](https://github.com/juspay/hyperswitch/pull/1874)) ([`3cc4548`](https://github.com/juspay/hyperswitch/commit/3cc4548eee4289455da99de2bf54c6b312291374)) ### Testing - **connector:** Add support for webhook tests ([#1863](https://github.com/juspay/hyperswitch/pull/1863)) ([`7b2c419`](https://github.com/juspay/hyperswitch/commit/7b2c419ce5c8f429dad3ace852891f76d2281646)) **Full Changelog:** [`v1.17.1...v1.18.0`](https://github.com/juspay/hyperswitch/compare/v1.17.1...v1.18.0) - - - ## 1.17.1 (2023-08-07) ### Bug Fixes - **connector:** [DummyConnector] add new icons and fix `we_chat_pay` ([#1845](https://github.com/juspay/hyperswitch/pull/1845)) ([`985ff6b`](https://github.com/juspay/hyperswitch/commit/985ff6ba419b6ed13fc9e2f74dfa824a27bdd3e3)) - **kms:** Fix kms decryption for jwe keys ([#1872](https://github.com/juspay/hyperswitch/pull/1872)) ([`ddc0302`](https://github.com/juspay/hyperswitch/commit/ddc0302298aefab0860b49210ce73abd4d121fb9)) ### Revert - Ci: use `sccache-action` for caching compilation artifacts ([#1880](https://github.com/juspay/hyperswitch/pull/1880)) ([`a988018`](https://github.com/juspay/hyperswitch/commit/a988018350dccebe94b4cac66b54375b95fcbbbe)) **Full Changelog:** [`v1.17.0...v1.17.1`](https://github.com/juspay/hyperswitch/compare/v1.17.0...v1.17.1) - - - ## 1.17.0 (2023-08-07) ### Features - **config:** Add config support to pt_mapping along with redis ([#1861](https://github.com/juspay/hyperswitch/pull/1861)) ([`b03dd24`](https://github.com/juspay/hyperswitch/commit/b03dd244561641f5b3481c79035766561bcd0a8a)) - **connector:** [Payme] Add Sync, RSync & webhook flow support ([#1862](https://github.com/juspay/hyperswitch/pull/1862)) ([`8057980`](https://github.com/juspay/hyperswitch/commit/80579805f9dd7c387eb3c0b5c48e01fa69e48299)) ### Bug Fixes - **core:** If frm is not called, send None in frm_message instead of initial values in update tracker ([#1867](https://github.com/juspay/hyperswitch/pull/1867)) ([`3250204`](https://github.com/juspay/hyperswitch/commit/3250204acc1e32f92dad725378b19dd3e4da33f6)) ### Revert - Fix(core): add validation for all the connector auth_type ([#1833](https://github.com/juspay/hyperswitch/pull/1833)) ([`ae3d25e`](https://github.com/juspay/hyperswitch/commit/ae3d25e6899af0d78171d40c980146d58f8fc03f)) **Full Changelog:** [`v1.16.0...v1.17.0`](https://github.com/juspay/hyperswitch/compare/v1.16.0...v1.17.0) - - - ## 1.16.0 (2023-08-04) ### Features - **connector:** - [Adyen] implement PaySafe ([#1805](https://github.com/juspay/hyperswitch/pull/1805)) ([`0f09199`](https://github.com/juspay/hyperswitch/commit/0f0919963fd1c887d3315039420a939bb377e738)) - [Adyen] Add support for gift cards balance ([#1672](https://github.com/juspay/hyperswitch/pull/1672)) ([`c4796ff`](https://github.com/juspay/hyperswitch/commit/c4796ffdb77a6270e7abc2e65e142ee4e7639b54)) - [Square] Add template code for connector Square ([#1834](https://github.com/juspay/hyperswitch/pull/1834)) ([`80b74e0`](https://github.com/juspay/hyperswitch/commit/80b74e096d56e08685ad52fb3049f6b611d587b3)) - [Adyen] implement Oxxo ([#1808](https://github.com/juspay/hyperswitch/pull/1808)) ([`5ed3f34`](https://github.com/juspay/hyperswitch/commit/5ed3f34c24c82d182921d317361bc9fc72be58ce)) ### Bug Fixes - **webhooks:** Do not send duplicate webhooks ([#1850](https://github.com/juspay/hyperswitch/pull/1850)) ([`0d996b8`](https://github.com/juspay/hyperswitch/commit/0d996b8960c7445289e451744c4bdeeb87d7d567)) ### Refactors - **connector:** Use utility function to raise payment method not implemented errors ([#1847](https://github.com/juspay/hyperswitch/pull/1847)) ([`f2fcc25`](https://github.com/juspay/hyperswitch/commit/f2fcc2595ae6f1c0ac5553c1a21ab33a6078b3e2)) - **payment_methods:** Add `requires_cvv` field to customer payment method list api object ([#1852](https://github.com/juspay/hyperswitch/pull/1852)) ([`2dec2ca`](https://github.com/juspay/hyperswitch/commit/2dec2ca50bbac0eed6f9fc562662b86436b4b656)) **Full Changelog:** [`v1.15.0...v1.16.0`](https://github.com/juspay/hyperswitch/compare/v1.15.0...v1.16.0) - - - ## 1.15.0 (2023-08-03) ### Features - **connector:** - [Boku] Implement Authorize, Psync, Refund and Rsync flow ([#1699](https://github.com/juspay/hyperswitch/pull/1699)) ([`9cba7da`](https://github.com/juspay/hyperswitch/commit/9cba7da0d3d4b87101debef8ec25b52a908975c5)) - add support for bank redirect for Paypal ([#1107](https://github.com/juspay/hyperswitch/pull/1107)) ([`57887bd`](https://github.com/juspay/hyperswitch/commit/57887bdf3a892548afea80859c2553d5a1cca49d)) - [Adyen] implement Adyen bank transfers and voucher payments in Indonesia ([#1804](https://github.com/juspay/hyperswitch/pull/1804)) ([`9977f9d`](https://github.com/juspay/hyperswitch/commit/9977f9d40ea349cada6171af7166a533e694450f)) - Unified errorCode and errorMessage map error reason as errorMessage in Stripe Connector ([#1797](https://github.com/juspay/hyperswitch/pull/1797)) ([`c464cc5`](https://github.com/juspay/hyperswitch/commit/c464cc510ded595ea846e7da95f60919614e2bd3)) ### Refactors - **common_enums:** Added derive for additional traits in FutureU… ([#1848](https://github.com/juspay/hyperswitch/pull/1848)) ([`8f6583f`](https://github.com/juspay/hyperswitch/commit/8f6583fbeeb7ab7ac31566adf9d182a839ed9a51)) - **config:** Add new type for kms encrypted values ([#1823](https://github.com/juspay/hyperswitch/pull/1823)) ([`73ed7ae`](https://github.com/juspay/hyperswitch/commit/73ed7ae7e305c391f413e3ac88775148db304779)) **Full Changelog:** [`v1.14.1...v1.15.0`](https://github.com/juspay/hyperswitch/compare/v1.14.1...v1.15.0) - - - ## 1.14.1 (2023-08-02) ### Bug Fixes - Include merchant reference in CreateIntentRequest ([#1846](https://github.com/juspay/hyperswitch/pull/1846)) ([`db55ed0`](https://github.com/juspay/hyperswitch/commit/db55ed0f6dcb2442784da5d38d76810541c95051)) **Full Changelog:** [`v1.14.0...v1.14.1`](https://github.com/juspay/hyperswitch/compare/v1.14.0...v1.14.1) - - - ## 1.14.0 (2023-08-02) ### Features - **Connector:** [Stripe] Implement Cashapp Wallet ([#1103](https://github.com/juspay/hyperswitch/pull/1103)) ([`dadd13e`](https://github.com/juspay/hyperswitch/commit/dadd13e3819095273e710a1c6ba6e5f2fef2ed7e)) - **connector:** - [iatapay] fix refund amount, hardcode IN for UPI, send merchant payment id ([#1824](https://github.com/juspay/hyperswitch/pull/1824)) ([`505aa21`](https://github.com/juspay/hyperswitch/commit/505aa218cf2b417929a7e2caaa8d820b5a68fe75)) - [Adyen] implement Swish for Adyen ([#1701](https://github.com/juspay/hyperswitch/pull/1701)) ([`cf30255`](https://github.com/juspay/hyperswitch/commit/cf3025562ffdb9cbab77fe40795051faad750fd5)) - [Trustpay] unify error_code, error_message and error_reason in error response ([#1817](https://github.com/juspay/hyperswitch/pull/1817)) ([`8a638e4`](https://github.com/juspay/hyperswitch/commit/8a638e4a089c772cd53742fa48f22f4bf8585c79)) - [Stax] Implement Cards for Connector Stax ([#1773](https://github.com/juspay/hyperswitch/pull/1773)) ([`f492d0a`](https://github.com/juspay/hyperswitch/commit/f492d0a943ed57aadc7abed721f90ed9e19e0c88)) - [Adyen] Implement Boleto Bancario in Vouchers and Add support for Voucher in Next Action ([#1657](https://github.com/juspay/hyperswitch/pull/1657)) ([`801946f`](https://github.com/juspay/hyperswitch/commit/801946f29f5701e3018f7fd54d3b3d0b4a13bc8e)) - [Adyen] Add support for Blik ([#1727](https://github.com/juspay/hyperswitch/pull/1727)) ([`30e41a9`](https://github.com/juspay/hyperswitch/commit/30e41a9f2f73fa7406696c6bf3bb6b4a38c24405)) - **core:** Added key should_cancel_transaction in update trackers to support Frm Pre flow cancellation ([#1811](https://github.com/juspay/hyperswitch/pull/1811)) ([`5d6510e`](https://github.com/juspay/hyperswitch/commit/5d6510eddf71b574f8d36743a56d1e6236af0bef)) - **payment_methods:** Added value Field in required Field for Pre-filling ([#1827](https://github.com/juspay/hyperswitch/pull/1827)) ([`e047a11`](https://github.com/juspay/hyperswitch/commit/e047a11dedbceaf9778a0f4aed1f9658f4af6783)) - **pii:** Implement a masking strategy for UPI VPAs ([#1641](https://github.com/juspay/hyperswitch/pull/1641)) ([`e3a33bb`](https://github.com/juspay/hyperswitch/commit/e3a33bb5c281ddf9c5746fad485bffa274a48b44)) ### Bug Fixes - **connector:** - [Stripe] change payment_method name Wechatpay to wechatpayqr ([#1813](https://github.com/juspay/hyperswitch/pull/1813)) ([`208d619`](https://github.com/juspay/hyperswitch/commit/208d619409ee03b7115b7c6268457df12149bee1)) - Refactor capture and refund flow for Connectors ([#1821](https://github.com/juspay/hyperswitch/pull/1821)) ([`d06adc7`](https://github.com/juspay/hyperswitch/commit/d06adc705c7c92307cdf3dd63b41c5ee1583a189)) - [Payme] Fix refund request fields ([#1831](https://github.com/juspay/hyperswitch/pull/1831)) ([`6f8be0c`](https://github.com/juspay/hyperswitch/commit/6f8be0c675cb55237da9deffb857dc4958fb6828)) - [Airwallex] Psync response ([#1826](https://github.com/juspay/hyperswitch/pull/1826)) ([`8f65819`](https://github.com/juspay/hyperswitch/commit/8f65819f1265577c9886f9c14ddfe16f2318d3d5)) - Refactor psync and rsync for connectors ([#1830](https://github.com/juspay/hyperswitch/pull/1830)) ([`7a0d6f6`](https://github.com/juspay/hyperswitch/commit/7a0d6f69211a44d4e362fe0857cdda2ff5167f0a)) - **payments:** - All AdditionalCardInfo fields optional ([#1840](https://github.com/juspay/hyperswitch/pull/1840)) ([`a1cb255`](https://github.com/juspay/hyperswitch/commit/a1cb255765394e7c91aa33bea72b2e48b597b443)) - Write a foreign_from implementation for payment_method_data and add missing payment methods in helpers.rs ([#1801](https://github.com/juspay/hyperswitch/pull/1801)) ([`50298c1`](https://github.com/juspay/hyperswitch/commit/50298c19674cf75fe6a6aee4fa099a4885902357)) - **ui-tests:** - Run ui-tests for each PR on approval ([#1839](https://github.com/juspay/hyperswitch/pull/1839)) ([`f2b370f`](https://github.com/juspay/hyperswitch/commit/f2b370f2855ccd77604fe73526a7edef81a90a47)) - Allow ui tests on workflow dispatch ([#1843](https://github.com/juspay/hyperswitch/pull/1843)) ([`c9fd421`](https://github.com/juspay/hyperswitch/commit/c9fd421d09db5746e2a21a8132813d8e2bf5ec35)) - Request amount fix for trustpay apple pay ([#1837](https://github.com/juspay/hyperswitch/pull/1837)) ([`3da69f3`](https://github.com/juspay/hyperswitch/commit/3da69f3ee160b022a3e2cf64c78833eb3fd95aea)) ### Refactors - **multiple_mca:** Make `primary_business_detail` optional and remove default values ([#1677](https://github.com/juspay/hyperswitch/pull/1677)) ([`9c7ac62`](https://github.com/juspay/hyperswitch/commit/9c7ac6246d6cf434855bc61f7cd625101665de5c)) - **redis:** Invoke `redis_conn()` method instead of cloning `redis_conn` property in `StorageInterface` ([#1552](https://github.com/juspay/hyperswitch/pull/1552)) ([`f32fdec`](https://github.com/juspay/hyperswitch/commit/f32fdec290a2f303887550d8db1ae2a3c065bafe)) - **router:** Include currency conversion utility functions as `Currency` methods ([#1790](https://github.com/juspay/hyperswitch/pull/1790)) ([`2c9c8f0`](https://github.com/juspay/hyperswitch/commit/2c9c8f081d7a99574dacae471ca2996ea2b2aa44)) - **ui_tests:** Move ui_tests to test_utils crate to reduce development time ([#1822](https://github.com/juspay/hyperswitch/pull/1822)) ([`5773faf`](https://github.com/juspay/hyperswitch/commit/5773faf739f1525cfe442c2df9d33f7475cf6b7c)) **Full Changelog:** [`v1.13.2...v1.14.0`](https://github.com/juspay/hyperswitch/compare/v1.13.2...v1.14.0) - - - ## 1.13.2 (2023-08-01) ### Bug Fixes - **webhook:** Provide acknowledgment for webhooks with unsupported event types ([#1815](https://github.com/juspay/hyperswitch/pull/1815)) ([`28a371b`](https://github.com/juspay/hyperswitch/commit/28a371b24a590787a569f08d84149515b46ebda6)) **Full Changelog:** [`v1.13.1...v1.13.2`](https://github.com/juspay/hyperswitch/compare/v1.13.1...v1.13.2) - - - ## 1.13.1 (2023-07-31) ### Bug Fixes - **connector:** [Trustpay] send billing address name as cardholder name ([#1806](https://github.com/juspay/hyperswitch/pull/1806)) ([`71b75c6`](https://github.com/juspay/hyperswitch/commit/71b75c653845685b71c6fb6007a718b6cb2c65c5)) - **logs:** Remove request from logs ([#1810](https://github.com/juspay/hyperswitch/pull/1810)) ([`5ad3950`](https://github.com/juspay/hyperswitch/commit/5ad3950892fc0c84b26092b0732dd18d2d913d12)) ### Testing - **connector:** Refactor UI test for connectors ([#1807](https://github.com/juspay/hyperswitch/pull/1807)) ([`34ff408`](https://github.com/juspay/hyperswitch/commit/34ff4080aeb4e8dacdeb13f2b5c17d8ead9561c8)) **Full Changelog:** [`v1.13.0...v1.13.1`](https://github.com/juspay/hyperswitch/compare/v1.13.0...v1.13.1) - - - ## 1.13.0 (2023-07-28) ### Features - **dummy_connector:** Add 3DS Flow, Wallets and Pay Later for Dummy Connector ([#1781](https://github.com/juspay/hyperswitch/pull/1781)) ([`8186c77`](https://github.com/juspay/hyperswitch/commit/8186c778bddb8932b37e5cf4c7b3e2d507f73e89)) - **router:** Validate payment method type in payments request against given payment method data for non-card flows ([#1236](https://github.com/juspay/hyperswitch/pull/1236)) ([`7607b6b`](https://github.com/juspay/hyperswitch/commit/7607b6b67153fce1e965d7ef7e41c62380884d8f)) ### Bug Fixes - **Connector:** [Noon] Update ApplePay Payment Struct ([#1794](https://github.com/juspay/hyperswitch/pull/1794)) ([`b96687c`](https://github.com/juspay/hyperswitch/commit/b96687c3fa863af76afef68170ee2c59946b76fd)) - **router:** Add validation for all the connector auth type ([#1748](https://github.com/juspay/hyperswitch/pull/1748)) ([`1cda7ad`](https://github.com/juspay/hyperswitch/commit/1cda7ad5fccb64c1adefc24a47b79b8315f91a59)) ### Documentation - Add renewed links for readme ([#1796](https://github.com/juspay/hyperswitch/pull/1796)) ([`e06e62c`](https://github.com/juspay/hyperswitch/commit/e06e62cc75497cb245fa115bb718a29c31e577c5)) **Full Changelog:** [`v1.12.0...v1.13.0`](https://github.com/juspay/hyperswitch/compare/v1.12.0...v1.13.0) - - - ## 1.12.0 (2023-07-27) ### Features - **connector:** [Zen] Add Latam Payment Methods ([#1670](https://github.com/juspay/hyperswitch/pull/1670)) ([`4df67ad`](https://github.com/juspay/hyperswitch/commit/4df67adb9bb110f1c5f3fc094fe21bf4741cda46))
CHANGELOG.md#chunk54
null
doc_chunk
8,136
doc
null
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentSync for Klarna {}
crates/hyperswitch_connectors/src/connectors/klarna.rs
hyperswitch_connectors
impl_block
9
rust
null
Klarna
api::PaymentSync for
impl api::PaymentSync for for Klarna
null
null
null
null
null
null
null
null
pub struct Prophetpay;
crates/hyperswitch_connectors/src/connectors/prophetpay.rs
hyperswitch_connectors
struct_definition
5
rust
Prophetpay
null
null
null
null
null
null
null
null
null
null
null
pub fn get_all_connectors() -> JsResult { Ok(serde_wasm_bindgen::to_value(RoutableConnectors::VARIANTS)?) }
crates/euclid_wasm/src/lib.rs
euclid_wasm
function_signature
34
rust
null
null
null
null
get_all_connectors
null
null
null
null
null
null
null
/// Verifies that the [`HashiCorpVault`] configuration is usable. pub fn validate(&self) -> Result<(), &'static str> { when(self.url.is_default_or_empty(), || { Err("HashiCorp vault url must not be empty") })?; when(self.token.is_default_or_empty(), || { Err("HashiCorp vault token must not be empty") }) }
crates/external_services/src/hashicorp_vault/core.rs
external_services
function_signature
85
rust
null
null
null
null
validate
null
null
null
null
null
null
null
pub struct CloneConnectorSource { pub mca_id: id_type::MerchantConnectorAccountId, pub merchant_id: id_type::MerchantId, }
crates/api_models/src/user.rs
api_models
struct_definition
31
rust
CloneConnectorSource
null
null
null
null
null
null
null
null
null
null
null
impl RedisResult { /// fn try_into_get(&self)-> Result<i32, RedisError> { /// match self { /// Self::Get(a) => Ok(a), /// _=>Err(RedisError::UnknownResult) /// } /// } /// /// fn try_into_set(&self)-> Result<String, RedisError> { /// match self { /// Self::Set(a) => Ok(a), /// _=> Err(RedisError::UnknownResult) /// } /// } /// }
crates/router_derive/src/lib.rs
router_derive
impl_block
109
rust
null
RedisResult
null
impl RedisResult
null
null
null
null
null
null
null
null
pub async fn update_merchant_account() {}
crates/openapi/src/routes/merchant_account.rs
openapi
function_signature
9
rust
null
null
null
null
update_merchant_account
null
null
null
null
null
null
null
pub struct JpmorganPaymentsRequest { capture_method: CapMethod, amount: MinorUnit, currency: common_enums::Currency, merchant: JpmorganMerchant, payment_method_type: JpmorganPaymentMethodType, }
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
hyperswitch_connectors
struct_definition
51
rust
JpmorganPaymentsRequest
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentSync for Boku {}
crates/hyperswitch_connectors/src/connectors/boku.rs
hyperswitch_connectors
impl_block
9
rust
null
Boku
api::PaymentSync for
impl api::PaymentSync for for Boku
null
null
null
null
null
null
null
null
pub fn from_hashmap( hashmap: HashMap<String, String>, ) -> errors::CustomResult<Self, errors::ParsingError> { let iter = MapDeserializer::< '_, std::collections::hash_map::IntoIter<String, String>, serde_json::error::Error, >::new(hashmap.into_iter()); Self::deserialize(iter) .change_context(errors::ParsingError::StructParseFailure("StreamData")) }
crates/drainer/src/types.rs
drainer
function_signature
94
rust
null
null
null
null
from_hashmap
null
null
null
null
null
null
null
/// This struct represents the encrypted Gpay payment data pub struct GpayEcryptedTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, }
crates/common_types/src/payments.rs
common_types
struct_definition
59
rust
GpayEcryptedTokenizationData
null
null
null
null
null
null
null
null
null
null
null
pub struct UpdateSuccessRateWindowEventRequest { pub id: String, pub params: String, pub labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, pub config: Option<UpdateSuccessRateWindowConfig>, pub global_labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, }
crates/router/src/core/payments/routing/utils.rs
router
struct_definition
65
rust
UpdateSuccessRateWindowEventRequest
null
null
null
null
null
null
null
null
null
null
null
pub struct MandateResponse { id: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
hyperswitch_connectors
struct_definition
13
rust
MandateResponse
null
null
null
null
null
null
null
null
null
null
null
impl PaymentAuthorize for Riskified {}
crates/hyperswitch_connectors/src/connectors/riskified.rs
hyperswitch_connectors
impl_block
7
rust
null
Riskified
PaymentAuthorize for
impl PaymentAuthorize for for Riskified
null
null
null
null
null
null
null
null
pub struct PaypalWebhooksPurchaseUnits { pub reference_id: String, pub amount: OrderAmount, }
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
struct_definition
23
rust
PaypalWebhooksPurchaseUnits
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: tags [ { "name": "Merchant Account", "description": "Create and manage merchant accounts" }, { "name": "Profile", "description": "Create and manage profiles" }, { "name": "Merchant Connector Account", "description": "Create and manage merchant connector accounts" }, { "name": "Payments", "description": "Create and manage one-time payments, recurring payments and mandates" }, { "name": "Refunds", "description": "Create and manage refunds for successful payments" }, { "name": "Mandates", "description": "Manage mandates" }, { "name": "Customers", "description": "Create and manage customers" }, { "name": "Payment Methods", "description": "Create and manage payment methods of customers" }, { "name": "Disputes", "description": "Manage disputes" }, { "name": "API Key", "description": "Create and manage API Keys" }, { "name": "Payouts", "description": "Create and manage payouts" }, { "name": "payment link", "description": "Create payment link" }, { "name": "Routing", "description": "Create and manage routing configurations" }, { "name": "Event", "description": "Manage events" }, { "name": "Authentication", "description": "Create and manage authentication" } ]
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
348
.json
null
null
null
null
null
openapi_spec
tags
[]
null
null
null
null
OpenAPI Block Path: components.schemas.AmazonPaySessionTokenData { "type": "object", "required": [ "amazon_pay" ], "properties": { "amazon_pay": { "$ref": "#/components/schemas/AmazonPayMerchantCredentials" } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
67
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "AmazonPaySessionTokenData" ]
null
null
null
null
pub async fn get_payment_link_status( _state: SessionState, _merchant_context: domain::MerchantContext, _merchant_id: common_utils::id_type::MerchantId, _payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { todo!() }
crates/router/src/core/payment_link.rs
router
function_signature
70
rust
null
null
null
null
get_payment_link_status
null
null
null
null
null
null
null
impl api::PaymentCapture for Chargebee {}
crates/hyperswitch_connectors/src/connectors/chargebee.rs
hyperswitch_connectors
impl_block
9
rust
null
Chargebee
api::PaymentCapture for
impl api::PaymentCapture for for Chargebee
null
null
null
null
null
null
null
null
pub async fn create_domain_model_using_record_request( payment_intent: &super::PaymentIntent, cell_id: id_type::CellId, storage_scheme: storage_enums::MerchantStorageScheme, request: &api_models::payments::PaymentsAttemptRecordRequest, encrypted_data: DecryptedPaymentAttempt, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let id = id_type::GlobalAttemptId::generate(&cell_id); let amount_details = AttemptAmountDetailsSetter::from(&request.amount_details); let now = common_utils::date_time::now(); // we consume transaction_created_at from webhook request, if it is not present we take store current time as transaction_created_at. let transaction_created_at = request .transaction_created_at .unwrap_or(common_utils::date_time::now()); // This function is called in the record attempt flow, which tells us that this is a payment attempt created by an external system. let feature_metadata = PaymentAttemptFeatureMetadata { revenue_recovery: Some({ PaymentAttemptRevenueRecoveryData { attempt_triggered_by: request.triggered_by, charge_id: request.feature_metadata.as_ref().and_then(|metadata| { metadata .revenue_recovery .as_ref() .and_then(|data| data.charge_id.clone()) }), } }), }; let payment_method_data = request .payment_method_data .as_ref() .map(|data| data.payment_method_data.clone().encode_to_value()) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode additional payment method data")? .map(pii::SecretSerdeValue::new); let payment_method_billing_address = encrypted_data .payment_method_billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let error = request.error.as_ref().map(ErrorDetails::from); let connector_payment_id = request .connector_transaction_id .as_ref() .map(|txn_id| txn_id.get_id().clone()); let connector = request.connector.map(|connector| connector.to_string()); let connector_request_reference_id = payment_intent .merchant_reference_id .as_ref() .map(|id| id.get_string_repr().to_owned()); Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), amount_details: AttemptAmountDetails::from(amount_details), status: request.status, connector, authentication_type: storage_enums::AuthenticationType::NoThreeDs, created_at: transaction_created_at, modified_at: now, last_synced: None, cancellation_reason: None, browser_info: None, payment_token: None, connector_metadata: None, payment_experience: None, payment_method_data, routing_result: None, preprocessing_step_id: None, multiple_capture_count: None, connector_response_reference_id: None, updated_by: storage_scheme.to_string(), redirection_data: None, encoded_data: None, merchant_connector_id: request.payment_merchant_connector_id.clone(), external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, client_source: None, client_version: None, customer_acceptance: None, profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: request.payment_method_type, payment_method_id: None, connector_payment_id, payment_method_subtype: request.payment_method_subtype, authentication_applied: None, external_reference_id: None, payment_method_billing_address, error, feature_metadata: Some(feature_metadata), id, connector_token_details: Some(diesel_models::ConnectorTokenDetails { connector_mandate_id: Some(request.processor_payment_method_token.clone()), connector_token_request_reference_id: None, }), card_discovery: None, charges: None, processor_merchant_id: payment_intent.merchant_id.clone(), created_by: None, connector_request_reference_id, network_transaction_id: None, }) }
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
function_signature
949
rust
null
null
null
null
create_domain_model_using_record_request
null
null
null
null
null
null
null
pub fn build_paypal_get_request(url: String, access_token: String) -> RouterResult<Request> { Ok(RequestBuilder::new() .method(Method::Get) .url(&url) .attach_default_headers() .header( header::AUTHORIZATION.to_string().as_str(), format!("Bearer {access_token}").as_str(), ) .build()) }
crates/router/src/utils/connector_onboarding/paypal.rs
router
function_signature
83
rust
null
null
null
null
build_paypal_get_request
null
null
null
null
null
null
null
impl Rapyd { pub fn generate_signature( &self, auth: &rapyd::RapydAuthType, http_method: &str, url_path: &str, body: &str, timestamp: i64, salt: &str, ) -> CustomResult<String, errors::ConnectorError> { let rapyd::RapydAuthType { access_key, secret_key, } = auth; let to_sign = format!( "{http_method}{url_path}{salt}{timestamp}{}{}{body}", access_key.peek(), secret_key.peek() ); let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.peek().as_bytes()); let tag = hmac::sign(&key, to_sign.as_bytes()); let hmac_sign = hex::encode(tag); let signature_value = BASE64_ENGINE_URL_SAFE.encode(hmac_sign); Ok(signature_value) } }
crates/hyperswitch_connectors/src/connectors/rapyd.rs
hyperswitch_connectors
impl_block
209
rust
null
Rapyd
null
impl Rapyd
null
null
null
null
null
null
null
null
impl ConnectorValidation for Tokenio { //TODO: implement functions when support enabled }
crates/hyperswitch_connectors/src/connectors/tokenio.rs
hyperswitch_connectors
impl_block
18
rust
null
Tokenio
ConnectorValidation for
impl ConnectorValidation for for Tokenio
null
null
null
null
null
null
null
null
pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } }
crates/hyperswitch_connectors/src/connectors/tsys.rs
hyperswitch_connectors
function_signature
28
rust
null
null
null
null
new
null
null
null
null
null
null
null
pub struct NonThreeDSResponseData { #[serde(rename = "tranID")] pub tran_id: String, pub status: String, #[serde(rename = "extraP")] pub extra_parameters: Option<ExtraParameters>, pub error_code: Option<String>, pub error_desc: Option<String>, }
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
hyperswitch_connectors
struct_definition
66
rust
NonThreeDSResponseData
null
null
null
null
null
null
null
null
null
null
null
pub struct PayoutsNew { pub payout_id: id_type::PayoutId, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, }
crates/hyperswitch_domain_models/src/payouts/payouts.rs
hyperswitch_domain_models
struct_definition
247
rust
PayoutsNew
null
null
null
null
null
null
null
null
null
null
null
Documentation: api-reference/v1/payments/payments--update.mdx # Type: Doc File --- openapi: post /payments/{payment_id} ---
api-reference/v1/payments/payments--update.mdx
null
doc_file
33
doc
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/scheduler/src/consumer/types/batch.rs Public functions: 2 Public structs: 1 use std::collections::HashMap; use common_utils::{errors::CustomResult, ext_traits::OptionExt}; use diesel_models::process_tracker::ProcessTracker; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::errors; #[derive(Debug, Clone)] pub struct ProcessTrackerBatch { pub id: String, pub group_name: String, pub stream_name: String, pub connection_name: String, pub created_time: PrimitiveDateTime, pub rule: String, // is it required? pub trackers: Vec<ProcessTracker>, /* FIXME: Add sized also here, list */ } impl ProcessTrackerBatch { pub fn to_redis_field_value_pairs( &self, ) -> CustomResult<Vec<(&str, String)>, errors::ProcessTrackerError> { Ok(vec![ ("id", self.id.to_string()), ("group_name", self.group_name.to_string()), ("stream_name", self.stream_name.to_string()), ("connection_name", self.connection_name.to_string()), ( "created_time", self.created_time.assume_utc().unix_timestamp().to_string(), ), ("rule", self.rule.to_string()), ( "trackers", serde_json::to_string(&self.trackers) .change_context(errors::ProcessTrackerError::SerializationFailed) .attach_printable_lazy(|| { format!("Unable to stringify trackers: {:?}", self.trackers) })?, ), ]) } pub fn from_redis_stream_entry( entry: HashMap<String, Option<String>>, ) -> CustomResult<Self, errors::ProcessTrackerError> { let mut entry = entry; let id = entry .remove("id") .flatten() .get_required_value("id") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let group_name = entry .remove("group_name") .flatten() .get_required_value("group_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let stream_name = entry .remove("stream_name") .flatten() .get_required_value("stream_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let connection_name = entry .remove("connection_name") .flatten() .get_required_value("connection_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let created_time = entry .remove("created_time") .flatten() .get_required_value("created_time") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; //make it parser error let created_time = { let offset_date_time = time::OffsetDateTime::from_unix_timestamp( created_time .as_str() .parse::<i64>() .change_context(errors::ParsingError::UnknownError) .change_context(errors::ProcessTrackerError::DeserializationFailed)?, ) .attach_printable_lazy(|| format!("Unable to parse time {}", &created_time)) .change_context(errors::ProcessTrackerError::MissingRequiredField)?; PrimitiveDateTime::new(offset_date_time.date(), offset_date_time.time()) }; let rule = entry .remove("rule") .flatten() .get_required_value("rule") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let trackers = entry .remove("trackers") .flatten() .get_required_value("trackers") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let trackers = serde_json::from_str::<Vec<ProcessTracker>>(trackers.as_str()) .change_context(errors::ParsingError::UnknownError) .attach_printable_lazy(|| { format!("Unable to parse trackers from JSON string: {trackers:?}") }) .change_context(errors::ProcessTrackerError::DeserializationFailed) .attach_printable("Error parsing ProcessTracker from redis stream entry")?; Ok(Self { id, group_name, stream_name, connection_name, created_time, rule, trackers, }) } }
crates/scheduler/src/consumer/types/batch.rs
scheduler
full_file
895
null
null
null
null
null
null
null
null
null
null
null
null
null
pub fn get_id(&self) -> &id_type::CustomerId { &self.customer_id }
crates/hyperswitch_domain_models/src/customer.rs
hyperswitch_domain_models
function_signature
22
rust
null
null
null
null
get_id
null
null
null
null
null
null
null
#[serde(deny_unknown_fields)] pub struct PayoutListConstraints { /// The identifier for customer #[schema(value_type = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub starting_after: Option<id_type::PayoutId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub ending_before: Option<id_type::PayoutId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The time at which payout is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListFilterConstraints { /// The identifier for payout #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: Option<id_type::PayoutId>, /// The merchant order reference ID for payout #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[schema(value_type = Option<String>,example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payouts list #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// The list of currencies to filter payouts list #[schema(value_type = Currency, example = "USD")] pub currency: Option<Vec<api_enums::Currency>>, /// The list of payout status to filter payouts list #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["pending", "failed"]))] pub status: Option<Vec<api_enums::PayoutStatus>>, /// The list of payout methods to filter payouts list #[schema(value_type = Option<Vec<PayoutType>>, example = json!(["bank", "card"]))] pub payout_method: Option<Vec<common_enums::PayoutType>>, /// Type of recipient #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: Option<common_enums::PayoutEntityType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListResponse { /// The number of payouts included in the list pub size: usize, /// The list of payouts response objects pub data: Vec<PayoutCreateResponse>, /// The total number of available payouts for given constraints #[serde(skip_serializing_if = "Option::is_none")] pub total_count: Option<i64>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListFilters { /// The list of available connector filters #[schema(value_type = Vec<PayoutConnectors>)] pub connector: Vec<api_enums::PayoutConnectors>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<common_enums::Currency>, /// The list of available payout status filters #[schema(value_type = Vec<PayoutStatus>)] pub status: Vec<common_enums::PayoutStatus>, /// The list of available payout method filters #[schema(value_type = Vec<PayoutType>)] pub payout_method: Vec<common_enums::PayoutType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutLinkResponse { pub payout_link_id: String, #[schema(value_type = String)] pub link: Secret<url::Url>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PayoutLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payout_id: id_type::PayoutId, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkDetails { pub publishable_key: Secret<String>, pub client_secret: Secret<String>, pub payout_link_id: String, pub payout_id: id_type::PayoutId, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, pub enabled_payment_methods_with_required_fields: Vec<PayoutEnabledPaymentMethodsInfo>, pub amount: common_utils::types::StringMajorUnit, pub currency: common_enums::Currency, pub locale: String, pub form_layout: Option<common_enums::UIWidgetFormLayout>, pub test_mode: bool, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutEnabledPaymentMethodsInfo { pub payment_method: common_enums::PaymentMethod, pub payment_method_types_info: Vec<PaymentMethodTypeInfo>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodTypeInfo { pub payment_method_type: common_enums::PaymentMethodType, pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, } #[derive(Clone, Debug, serde::Serialize, FlatStruct)] pub struct RequiredFieldsOverrideRequest { pub billing: Option<payments::Address>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkStatusDetails { pub payout_link_id: String, pub payout_id: id_type::PayoutId, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: api_enums::PayoutStatus, pub error_code: Option<UnifiedCode>, pub error_message: Option<UnifiedMessage>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub test_mode: bool, } impl From<Bank> for payout_method_utils::BankAdditionalData { fn from(bank_data: Bank) -> Self { match bank_data { Bank::Ach(AchBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_routing_number, }) => Self::Ach(Box::new( payout_method_utils::AchBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_routing_number: bank_routing_number.into(), }, )), Bank::Bacs(BacsBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_sort_code, }) => Self::Bacs(Box::new( payout_method_utils::BacsBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_sort_code: bank_sort_code.into(), }, )), Bank::Sepa(SepaBankTransfer { bank_name, bank_country_code, bank_city, iban, bic, }) => Self::Sepa(Box::new( payout_method_utils::SepaBankTransferAdditionalData { bank_name, bank_country_code, bank_city, iban: iban.into(), bic: bic.map(From::from), }, )), Bank::Pix(PixBankTransfer { bank_name, bank_branch, bank_account_number, pix_key, tax_id, }) => Self::Pix(Box::new( payout_method_utils::PixBankTransferAdditionalData { bank_name, bank_branch, bank_account_number: bank_account_number.into(), pix_key: pix_key.into(), tax_id: tax_id.map(From::from), }, )), } } } impl From<Wallet> for payout_method_utils::WalletAdditionalData { fn from(wallet_data: Wallet) -> Self { match wallet_data { Wallet::Paypal(Paypal { email, telephone_number, paypal_id, }) => Self::Paypal(Box::new(payout_method_utils::PaypalAdditionalData { email: email.map(ForeignFrom::foreign_from), telephone_number: telephone_number.map(From::from), paypal_id: paypal_id.map(From::from), })), Wallet::Venmo(Venmo { telephone_number }) => { Self::Venmo(Box::new(payout_method_utils::VenmoAdditionalData { telephone_number: telephone_number.map(From::from), })) } } } } impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataResponse { fn from(additional_data: payout_method_utils::AdditionalPayoutMethodData) -> Self { match additional_data { payout_method_utils::AdditionalPayoutMethodData::Card(card_data) => { Self::Card(card_data) } payout_method_utils::AdditionalPayoutMethodData::Bank(bank_data) => { Self::Bank(bank_data) } payout_method_utils::AdditionalPayoutMethodData::Wallet(wallet_data) => { Self::Wallet(wallet_data) } } } }
crates/api_models/src/payouts.rs#chunk1
api_models
chunk
2,552
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct PaymentsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, );
crates/api_models/src/payment_methods.rs
api_models
struct_definition
27
rust
PaymentsMandateReference
null
null
null
null
null
null
null
null
null
null
null
pub fn new( payment_intent: &revenue_recovery::RecoveryPaymentIntent, payment_attempt: &revenue_recovery::RecoveryPaymentAttempt, ) -> Self { Self(payment_intent.clone(), payment_attempt.clone()) }
crates/router/src/core/webhooks/recovery_incoming.rs
router
function_signature
49
rust
null
null
null
null
new
null
null
null
null
null
null
null
pub fn from_storage(dispute: &'a Dispute) -> Self { let currency = dispute.dispute_currency.unwrap_or( dispute .currency .to_uppercase() .parse_enum("Currency") .unwrap_or_default(), ); Self { dispute_id: &dispute.dispute_id, dispute_amount: StringMinorUnitForConnector::convert_back( &StringMinorUnitForConnector, dispute.amount.clone(), currency, ) .unwrap_or_else(|e| { router_env::logger::error!("Failed to convert dispute amount: {e:?}"); MinorUnit::new(0) }), currency, dispute_stage: &dispute.dispute_stage, dispute_status: &dispute.dispute_status, payment_id: &dispute.payment_id, attempt_id: &dispute.attempt_id, merchant_id: &dispute.merchant_id, connector_status: &dispute.connector_status, connector_dispute_id: &dispute.connector_dispute_id, connector_reason: dispute.connector_reason.as_ref(), connector_reason_code: dispute.connector_reason_code.as_ref(), challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()), connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()), connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()), created_at: dispute.created_at.assume_utc(), modified_at: dispute.modified_at.assume_utc(), connector: &dispute.connector, evidence: &dispute.evidence, profile_id: dispute.profile_id.as_ref(), merchant_connector_id: dispute.merchant_connector_id.as_ref(), organization_id: &dispute.organization_id, } }
crates/router/src/services/kafka/dispute_event.rs
router
function_signature
370
rust
null
null
null
null
from_storage
null
null
null
null
null
null
null
impl api::RefundSync for Zsl {}
crates/hyperswitch_connectors/src/connectors/zsl.rs
hyperswitch_connectors
impl_block
10
rust
null
Zsl
api::RefundSync for
impl api::RefundSync for for Zsl
null
null
null
null
null
null
null
null
pub fn validate_refund_list(limit: Option<i64>) -> CustomResult<i64, errors::ApiErrorResponse> { match limit { Some(limit_val) => { if !(LOWER_LIMIT..=UPPER_LIMIT).contains(&limit_val) { Err(errors::ApiErrorResponse::InvalidRequestData { message: "limit should be in between 1 and 100".to_string(), } .into()) } else { Ok(limit_val) } } None => Ok(DEFAULT_LIMIT), } }
crates/router/src/core/utils/refunds_validator.rs
router
function_signature
114
rust
null
null
null
null
validate_refund_list
null
null
null
null
null
null
null
impl UnifiedAuthenticationService for ExternalAuthentication { fn get_pre_authentication_request_data( payment_method_data: Option<&domain::PaymentMethodData>, _service_details: Option<payments::CtpServiceDetails>, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, ) -> RouterResult<UasPreAuthenticationRequestData> { let payment_method_data = payment_method_data .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("payment_method_data is missing")?; let payment_details = if let payment_method_data::PaymentMethodData::Card(card) = payment_method_data { Some(PaymentDetails { pan: card.card_number.clone(), digital_card_id: None, payment_data_type: None, encrypted_src_card_details: None, card_expiry_month: card.card_exp_month.clone(), card_expiry_year: card.card_exp_year.clone(), cardholder_name: card.card_holder_name.clone(), card_token_number: None, account_type: None, card_cvc: Some(card.card_cvc.clone()), }) } else { None }; let transaction_details = TransactionDetails { amount: Some(amount), currency, device_channel: None, message_category: None, }; Ok(UasPreAuthenticationRequestData { service_details: None, transaction_details: Some(transaction_details), payment_details, authentication_info: None, merchant_details: merchant_details.cloned(), billing_address: billing_address.cloned(), acquirer_bin, acquirer_merchant_id, }) } #[allow(clippy::too_many_arguments)] async fn pre_authentication( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, payment_id: Option<&common_utils::id_type::PaymentId>, payment_method_data: Option<&domain::PaymentMethodData>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, service_details: Option<payments::CtpServiceDetails>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, ) -> RouterResult<UasPreAuthenticationRouterData> { let pre_authentication_data = Self::get_pre_authentication_request_data( payment_method_data, service_details, amount, currency, merchant_details, billing_address, acquirer_bin, acquirer_merchant_id, )?; let pre_auth_router_data: UasPreAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, pre_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), pre_auth_router_data, )) .await } fn get_authentication_request_data( browser_details: Option<BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: MessageCategory, device_channel: payments::DeviceChannel, authentication: Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, ) -> RouterResult<UasAuthenticationRequestData> { Ok(UasAuthenticationRequestData { browser_details, transaction_details: TransactionDetails { amount, currency, device_channel: Some(device_channel), message_category: Some(message_category), }, pre_authentication_data: PreAuthenticationData { threeds_server_transaction_id: authentication.threeds_server_transaction_id.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "authentication.threeds_server_transaction_id", }, )?, message_version: authentication.message_version.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "authentication.message_version", }, )?, acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, acquirer_country_code: authentication.acquirer_country_code, connector_metadata: authentication.connector_metadata, }, return_url, sdk_information, email, threeds_method_comp_ind, webhook_url, }) } #[allow(clippy::too_many_arguments)] async fn authentication( state: &SessionState, business_profile: &domain::Profile, payment_method: &common_enums::PaymentMethod, browser_details: Option<BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: MessageCategory, device_channel: payments::DeviceChannel, authentication: Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_id: Option<common_utils::id_type::PaymentId>, ) -> RouterResult<UasAuthenticationRouterData> { let authentication_data = <Self as UnifiedAuthenticationService>::get_authentication_request_data( browser_details, amount, currency, message_category, device_channel, authentication.clone(), return_url, sdk_information, threeds_method_comp_ind, email, webhook_url, )?; let auth_router_data: UasAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method.to_owned(), business_profile.merchant_id.clone(), None, authentication_data, merchant_connector_account, Some(authentication.authentication_id.to_owned()), payment_id, )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), auth_router_data, )) .await } fn get_post_authentication_request_data( authentication: Option<Authentication>, ) -> RouterResult<UasPostAuthenticationRequestData> { Ok(UasPostAuthenticationRequestData { // authentication.threeds_server_transaction_id is mandatory for post-authentication in ExternalAuthentication threeds_server_transaction_id: Some( authentication .and_then(|auth| auth.threeds_server_transaction_id) .ok_or(ApiErrorResponse::MissingRequiredField { field_name: "authentication.threeds_server_transaction_id", })?, ), }) } async fn post_authentication( state: &SessionState, business_profile: &domain::Profile, payment_id: Option<&common_utils::id_type::PaymentId>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, _merchant_id: &common_utils::id_type::MerchantId, authentication: Option<&Authentication>, ) -> RouterResult<UasPostAuthenticationRouterData> { let authentication_data = <Self as UnifiedAuthenticationService>::get_post_authentication_request_data( authentication.cloned(), )?; let auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, business_profile.merchant_id.clone(), None, authentication_data, merchant_connector_account, Some(authentication_id.clone()), payment_id.cloned(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), auth_router_data, ) .await } }
crates/router/src/core/unified_authentication_service.rs
router
impl_block
1,827
rust
null
ExternalAuthentication
UnifiedAuthenticationService for
impl UnifiedAuthenticationService for for ExternalAuthentication
null
null
null
null
null
null
null
null
impl api::PaymentToken for Trustpay {}
crates/hyperswitch_connectors/src/connectors/trustpay.rs
hyperswitch_connectors
impl_block
9
rust
null
Trustpay
api::PaymentToken for
impl api::PaymentToken for for Trustpay
null
null
null
null
null
null
null
null
impl api::ConnectorAccessToken for HyperswitchVault {}
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
hyperswitch_connectors
impl_block
11
rust
null
HyperswitchVault
api::ConnectorAccessToken for
impl api::ConnectorAccessToken for for HyperswitchVault
null
null
null
null
null
null
null
null
pub async fn vault_payment_method( state: &SessionState, pmd: &domain::PaymentMethodVaultingData, merchant_context: &domain::MerchantContext, profile: &domain::Profile, existing_vault_id: Option<domain::VaultId>, customer_id: &id_type::GlobalCustomerId, ) -> RouterResult<( pm_types::AddVaultResponse, Option<id_type::MerchantConnectorAccountId>, )> { let is_external_vault_enabled = profile.is_external_vault_enabled(); match is_external_vault_enabled { true => { let external_vault_source: id_type::MerchantConnectorAccountId = profile .external_vault_connector_details .clone() .map(|connector_details| connector_details.vault_connector_id.clone()) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("mca_id not present for external vault")?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( payments_core::helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), Some(&external_vault_source), ) .await .attach_printable( "failed to fetch merchant connector account for external vault insert", )?, )); vault_payment_method_external( state, pmd, merchant_context.get_merchant_account(), merchant_connector_account, ) .await .map(|value| (value, Some(external_vault_source))) } false => vault_payment_method_internal( state, pmd, merchant_context, existing_vault_id, customer_id, ) .await .map(|value| (value, None)), } }
crates/router/src/core/payment_methods.rs
router
function_signature
377
rust
null
null
null
null
vault_payment_method
null
null
null
null
null
null
null
File: crates/diesel_models/src/query/user/theme.rs Public functions: 8 use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::types::user::ThemeLineage; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, sql_types::{Bool, Nullable}, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use router_env::logger; use crate::{ errors::DatabaseError, query::generics::{ self, db_metrics::{track_database_call, DatabaseOperation}, }, schema::themes::dsl, user::theme::{Theme, ThemeNew, ThemeUpdate, ThemeUpdateInternal}, PgPooledConn, StorageResult, }; impl ThemeNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Theme> { generics::generic_insert(conn, self).await } } impl Theme { fn lineage_filter( lineage: ThemeLineage, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { match lineage { ThemeLineage::Tenant { tenant_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.is_null()) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()) .nullable(), ), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()), ), ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.is_null()), ), ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)), ), } } /// Matches all themes that belong to the specified hierarchy level or below fn lineage_hierarchy_filter( lineage: ThemeLineage, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { match lineage { ThemeLineage::Tenant { tenant_id } => Box::new(dsl::tenant_id.eq(tenant_id).nullable()), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .nullable(), ), ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .nullable(), ), ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)) .nullable(), ), } } pub async fn find_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id.eq(theme_id), ) .await } pub async fn find_most_specific_theme_in_lineage( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Self> { let query = <Self as HasTable>::table().into_boxed(); let query = lineage .get_same_and_higher_lineages() .into_iter() .fold(query, |mut query, lineage| { query = query.or_filter(Self::lineage_filter(lineage)); query }); logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); let data: Vec<Self> = match track_database_call::<Self, _, _>( query.get_results_async(conn), DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound), _ => Err(report!(err)).change_context(DatabaseError::Others), }, }?; data.into_iter() .min_by_key(|theme| theme.entity_type) .ok_or(report!(DatabaseError::NotFound)) } pub async fn find_by_lineage( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, Self::lineage_filter(lineage), ) .await } pub async fn update_by_theme_id( conn: &PgPooledConn, theme_id: String, update: ThemeUpdate, ) -> StorageResult<Self> { let update_internal: ThemeUpdateInternal = update.into(); let predicate = dsl::theme_id.eq(theme_id); generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, predicate, update_internal) .await } pub async fn delete_by_theme_id_and_lineage( conn: &PgPooledConn, theme_id: String, lineage: ThemeLineage, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id .eq(theme_id) .and(Self::lineage_filter(lineage)), ) .await } pub async fn delete_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id.eq(theme_id), ) .await } /// Finds all themes that match the specified lineage hierarchy. pub async fn find_all_by_lineage_hierarchy( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Vec<Self>> { let filter = Self::lineage_hierarchy_filter(lineage); let query = <Self as HasTable>::table().filter(filter).into_boxed(); logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match track_database_call::<Self, _, _>( query.get_results_async(conn), DatabaseOperation::Filter, ) .await { Ok(themes) => Ok(themes), Err(err) => match err { DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound), _ => Err(report!(err)).change_context(DatabaseError::Others), }, } } }
crates/diesel_models/src/query/user/theme.rs
diesel_models
full_file
1,724
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct XenditSplitRequest { pub name: String, pub description: String, pub routes: Vec<XenditSplitRoute>, }
crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
hyperswitch_connectors
struct_definition
32
rust
XenditSplitRequest
null
null
null
null
null
null
null
null
null
null
null
File: crates/router/src/core/webhooks/utils.rs Public functions: 5 use std::marker::PhantomData; use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use error_stack::{Report, ResultExt}; use redis_interface as redis; use router_env::tracing; use super::MERCHANT_ID; use crate::{ core::{ errors::{self}, metrics, payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, errors::RouterResult, routes::app::SessionStateInfo, services::logger, types::{self, api, domain, PaymentAddress}, SessionState, }; const IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_attempt_id_in_source_verification_flow"; const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_connector_request_reference_id_in_source_verification_flow"; /// Check whether the merchant has configured to disable the webhook `event` for the `connector` /// First check for the key "whconf_{merchant_id}_{connector_id}" in redis, /// if not found, fetch from configs table in database pub async fn is_webhook_event_disabled( db: &dyn StorageInterface, connector_id: &str, merchant_id: &common_utils::id_type::MerchantId, event: &api::IncomingWebhookEvent, ) -> bool { let redis_key = merchant_id.get_webhook_config_disabled_events_key(connector_id); let merchant_webhook_disable_config_result: CustomResult< api::MerchantWebhookConfig, redis_interface::errors::RedisError, > = get_and_deserialize_key(db, &redis_key, "MerchantWebhookConfig").await; match merchant_webhook_disable_config_result { Ok(merchant_webhook_config) => merchant_webhook_config.contains(event), Err(..) => { //if failed to fetch from redis. fetch from db and populate redis db.find_config_by_key(&redis_key) .await .map(|config| { match serde_json::from_str::<api::MerchantWebhookConfig>(&config.config) { Ok(set) => set.contains(event), Err(err) => { logger::warn!(?err, "error while parsing merchant webhook config"); false } } }) .unwrap_or_else(|err| { logger::warn!(?err, "error while fetching merchant webhook config"); false }) } } } pub async fn construct_webhook_router_data( state: &SessionState, connector_name: &str, merchant_connector_account: domain::MerchantConnectorAccount, merchant_context: &domain::MerchantContext, connector_wh_secrets: &api_models::webhooks::ConnectorWebhookSecrets, request_details: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ApiErrorResponse> { let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(Box::new(merchant_connector_account.clone())) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector: connector_name.to_string(), customer_id: None, tenant_id: state.tenant.tenant_id.clone(), payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("source_verification_flow") .get_string_repr() .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(), status: diesel_models::enums::AttemptStatus::default(), payment_method: diesel_models::enums::PaymentMethod::default(), connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, minor_amount_captured: None, request: types::VerifyWebhookSourceRequestData { webhook_headers: request_details.headers.clone(), webhook_body: request_details.body.to_vec().clone(), merchant_secret: connector_wh_secrets.to_owned(), }, response: Err(types::ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, payment_method_balance: None, payment_method_status: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, }; Ok(router_data) } #[inline] pub(crate) fn get_idempotent_event_id( primary_object_id: &str, event_type: types::storage::enums::EventType, delivery_attempt: types::storage::enums::WebhookDeliveryAttempt, ) -> String { use crate::types::storage::enums::WebhookDeliveryAttempt; const EVENT_ID_SUFFIX_LENGTH: usize = 8; let common_prefix = format!("{primary_object_id}_{event_type}"); match delivery_attempt { WebhookDeliveryAttempt::InitialAttempt => common_prefix, WebhookDeliveryAttempt::AutomaticRetry | WebhookDeliveryAttempt::ManualRetry => { common_utils::generate_id(EVENT_ID_SUFFIX_LENGTH, &common_prefix) } } } #[inline] pub(crate) fn generate_event_id() -> String { common_utils::generate_time_ordered_id("evt") } pub fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) { metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), ) } pub fn increment_webhook_outgoing_not_received_count( merchant_id: &common_utils::id_type::MerchantId, ) { metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), ); } pub fn is_outgoing_webhook_disabled( state: &SessionState, webhook_url_result: &Result<String, Report<errors::WebhooksFlowError>>, business_profile: &domain::Profile, idempotent_event_id: &str, ) -> bool { if !state.conf.webhooks.outgoing_enabled || webhook_url_result.is_err() || webhook_url_result.as_ref().is_ok_and(String::is_empty) { logger::debug!( business_profile_id=?business_profile.get_id(), %idempotent_event_id, "Outgoing webhooks are disabled in application configuration, or merchant webhook URL \ could not be obtained; skipping outgoing webhooks for event" ); return true; } false } const WEBHOOK_LOCK_PREFIX: &str = "WEBHOOK_LOCK"; pub(super) async fn perform_redis_lock<A>( state: &A, unique_locking_key: &str, merchant_id: common_utils::id_type::MerchantId, ) -> RouterResult<Option<String>> where A: SessionStateInfo, { let lock_value: String = uuid::Uuid::new_v4().to_string(); let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error connecting to redis")?; let redis_locking_key = format!( "{}_{}_{}", WEBHOOK_LOCK_PREFIX, merchant_id.get_string_repr(), unique_locking_key ); let redis_lock_expiry_seconds = state.conf().webhooks.redis_lock_expiry_seconds; let redis_lock_result = redis_conn .set_key_if_not_exists_with_expiry( &redis_locking_key.as_str().into(), lock_value.clone(), Some(i64::from(redis_lock_expiry_seconds)), ) .await; match redis_lock_result { Ok(redis::SetnxReply::KeySet) => { logger::info!("Lock acquired for for {redis_locking_key}"); Ok(Some(lock_value)) } Ok(redis::SetnxReply::KeyNotSet) => { logger::info!("Lock already held for {redis_locking_key}"); Ok(None) } Err(err) => Err(err .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error acquiring redis lock")), } } pub(super) async fn free_redis_lock<A>( state: &A, unique_locking_key: &str, merchant_id: common_utils::id_type::MerchantId, lock_value: Option<String>, ) -> RouterResult<()> where A: SessionStateInfo, { let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error connecting to redis")?; let redis_locking_key = format!( "{}_{}_{}", WEBHOOK_LOCK_PREFIX, merchant_id.get_string_repr(), unique_locking_key ); match redis_conn .get_key::<Option<String>>(&redis_locking_key.as_str().into()) .await { Ok(val) => { if val == lock_value { match redis_conn .delete_key(&redis_locking_key.as_str().into()) .await { Ok(redis::types::DelReply::KeyDeleted) => { logger::info!("Lock freed {redis_locking_key}"); tracing::Span::current().record("redis_lock_released", redis_locking_key); Ok(()) } Ok(redis::types::DelReply::KeyNotDeleted) => Err( errors::ApiErrorResponse::InternalServerError, ) .attach_printable("Status release lock called but key is not found in redis"), Err(error) => Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while deleting redis key"), } } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("The redis value which acquired the lock is not equal to the redis value requesting for releasing the lock") } } Err(error) => Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while deleting redis key"), } }
crates/router/src/core/webhooks/utils.rs
router
full_file
2,426
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct FinalizeStatusDetails { state: FinalizeState, reason_code: Option<String>, reason_description: Option<String>, last_updated_timestamp: String, }
crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
hyperswitch_connectors
struct_definition
36
rust
FinalizeStatusDetails
null
null
null
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/chargebee.rs Public functions: 1 Public structs: 1 pub mod transformers; use base64::Engine; use common_enums::enums; use common_utils::{ consts::BASE64_ENGINE, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; #[cfg(feature = "v1")] use error_stack::report; use error_stack::ResultExt; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::{ revenue_recovery, router_flow_types::revenue_recovery::RecoveryRecordBack, router_request_types::revenue_recovery::RevenueRecoveryRecordBackRequest, router_response_types::revenue_recovery::RevenueRecoveryRecordBackResponse, types::RevenueRecoveryRecordBackRouterData, }; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ConnectorInfo, PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{Mask, PeekInterface, Secret}; use transformers as chargebee; use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Chargebee { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Chargebee { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } } impl api::Payment for Chargebee {} impl api::PaymentSession for Chargebee {} impl api::ConnectorAccessToken for Chargebee {} impl api::MandateSetup for Chargebee {} impl api::PaymentAuthorize for Chargebee {} impl api::PaymentSync for Chargebee {} impl api::PaymentCapture for Chargebee {} impl api::PaymentVoid for Chargebee {} impl api::Refund for Chargebee {} impl api::RefundExecute for Chargebee {} impl api::RefundSync for Chargebee {} impl api::PaymentToken for Chargebee {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl api::revenue_recovery::RevenueRecoveryRecordBack for Chargebee {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Chargebee { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Chargebee where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.common_get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Chargebee { fn id(&self) -> &'static str { "chargebee" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.chargebee.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = chargebee::ChargebeeAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let encoded_api_key = BASE64_ENGINE.encode(auth.full_access_key_v1.peek()); Ok(vec![( headers::AUTHORIZATION.to_string(), format!("Basic {encoded_api_key}").into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: chargebee::ChargebeeErrorResponse = res .response .parse_struct("ChargebeeErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.api_error_code.clone(), message: response.api_error_code.clone(), reason: Some(response.message), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Chargebee { //TODO: implement functions when support enabled } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Chargebee { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Chargebee {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Chargebee { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Chargebee { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = chargebee::ChargebeeRouterData::from((amount, req)); let connector_req = chargebee::ChargebeePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: chargebee::ChargebeePaymentsResponse = res .response .parse_struct("Chargebee PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Chargebee { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: chargebee::ChargebeePaymentsResponse = res .response .parse_struct("chargebee PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Chargebee { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: chargebee::ChargebeePaymentsResponse = res .response .parse_struct("Chargebee PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Chargebee {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Chargebee { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = chargebee::ChargebeeRouterData::from((refund_amount, req)); let connector_req = chargebee::ChargebeeRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: chargebee::RefundResponse = res .response .parse_struct("chargebee RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Chargebee { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: chargebee::RefundResponse = res .response .parse_struct("chargebee RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl ConnectorIntegration< RecoveryRecordBack, RevenueRecoveryRecordBackRequest, RevenueRecoveryRecordBackResponse, > for Chargebee { fn get_headers( &self, req: &RevenueRecoveryRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, req: &RevenueRecoveryRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let metadata: chargebee::ChargebeeMetadata = utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?; let url = self .base_url(connectors) .to_string() .replace("{{merchant_endpoint_prefix}}", metadata.site.peek()); let invoice_id = req .request .merchant_reference_id .get_string_repr() .to_string(); Ok(format!("{url}v2/invoices/{invoice_id}/record_payment")) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_request_body( &self, req: &RevenueRecoveryRecordBackRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.amount, req.request.currency, )?; let connector_router_data = chargebee::ChargebeeRouterData::from((amount, req)); let connector_req = chargebee::ChargebeeRecordPaymentRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &RevenueRecoveryRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::RevenueRecoveryRecordBackType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::RevenueRecoveryRecordBackType::get_headers( self, req, connectors, )?) .set_body(types::RevenueRecoveryRecordBackType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RevenueRecoveryRecordBackRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RevenueRecoveryRecordBackRouterData, errors::ConnectorError> { let response: chargebee::ChargebeeRecordbackResponse = res .response .parse_struct("chargebee ChargebeeRecordbackResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Chargebee { fn get_webhook_source_verification_signature( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = utils::get_header_key_value("authorization", request.headers)?; let signature = base64_signature.as_bytes().to_owned(); Ok(signature) } async fn verify_webhook_source( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let password = connector_webhook_secrets .additional_secret .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("Failed to get additional secrets")?; let username = String::from_utf8(connector_webhook_secrets.secret.to_vec()) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("Could not convert secret to UTF-8")?; let secret_auth = format!( "Basic {}", base64::engine::general_purpose::STANDARD.encode(format!( "{}:{}", username, password.peek() )) ); let signature_auth = String::from_utf8(signature.to_vec()) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("Could not convert secret to UTF-8")?; Ok(signature_auth == secret_auth) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_webhook_object_reference_id( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let webhook = chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api_models::webhooks::ObjectReferenceId::InvoiceId( api_models::webhooks::InvoiceIdType::ConnectorInvoiceId(webhook.content.invoice.id), )) } #[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))] fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let webhook = chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; let event = api_models::webhooks::IncomingWebhookEvent::from(webhook.event_type); Ok(event) } #[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))] fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let webhook = chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body) .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(webhook)) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_revenue_recovery_attempt_details( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError> { let webhook = transformers::ChargebeeWebhookBody::get_webhook_object_from_body(request.body)?; revenue_recovery::RevenueRecoveryAttemptData::try_from(webhook) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_revenue_recovery_invoice_details( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError> { let webhook = transformers::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)?; revenue_recovery::RevenueRecoveryInvoiceData::try_from(webhook) } } static CHARGEBEE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Chargebee", description: "Chargebee is a Revenue Growth Management (RGM) platform that helps subscription businesses manage subscriptions, billing, revenue recognition, collections, and customer retention, essentially streamlining the entire subscription lifecycle.", connector_type: enums::HyperswitchConnectorCategory::RevenueGrowthManagementPlatform, integration_status: enums::ConnectorIntegrationStatus::Alpha, }; static CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; impl ConnectorSpecifications for Chargebee { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&CHARGEBEE_CONNECTOR_INFO) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/chargebee.rs
hyperswitch_connectors
full_file
6,459
null
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/analytics/src/disputes/metrics.rs Public structs: 1 mod dispute_status_metric; mod sessionized_metrics; mod total_amount_disputed; mod total_dispute_lost_amount; use std::collections::HashSet; use api_models::analytics::{ disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier}, Granularity, }; use common_utils::types::TimeRange; use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; use self::{ dispute_status_metric::DisputeStatusMetric, total_amount_disputed::TotalAmountDisputed, total_dispute_lost_amount::TotalDisputeLostAmount, }; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; #[derive(Debug, Eq, PartialEq, serde::Deserialize, Hash)] pub struct DisputeMetricRow { pub dispute_stage: Option<DBEnumWrapper<storage_enums::DisputeStage>>, pub dispute_status: Option<DBEnumWrapper<storage_enums::DisputeStatus>>, pub connector: Option<String>, pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, 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>, } pub trait DisputeMetricAnalytics: LoadRow<DisputeMetricRow> {} #[async_trait::async_trait] pub trait DisputeMetric<T> where T: AnalyticsDataSource + DisputeMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>; } #[async_trait::async_trait] impl<T> DisputeMetric<T> for DisputeMetrics where T: AnalyticsDataSource + DisputeMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { match self { Self::TotalAmountDisputed => { TotalAmountDisputed::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::DisputeStatusMetric => { DisputeStatusMetric::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::TotalDisputeLostAmount => { TotalDisputeLostAmount::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedTotalAmountDisputed => { sessionized_metrics::TotalAmountDisputed::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedDisputeStatusMetric => { sessionized_metrics::DisputeStatusMetric::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedTotalDisputeLostAmount => { sessionized_metrics::TotalDisputeLostAmount::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } } } }
crates/analytics/src/disputes/metrics.rs
analytics
full_file
951
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn accept_dispute( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: disputes::DisputeId, ) -> RouterResponse<dispute_models::DisputeResponse> { let db = &state.store; let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &req.dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_id = dispute.dispute_id.clone(); common_utils::fp_utils::when( !core_utils::should_proceed_with_accept_dispute( dispute.dispute_stage, dispute.dispute_status, ), || { metrics::ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "This dispute cannot be accepted because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Accept, AcceptDisputeRequestData, AcceptDisputeResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_accept_dispute_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling accept dispute connector api")?; let accept_dispute_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, })?; let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate { dispute_status: accept_dispute_response.dispute_status, connector_status: accept_dispute_response.connector_status.clone(), }; let updated_dispute = db .update_dispute(dispute.clone(), update_dispute) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute); Ok(services::ApplicationResponse::Json(dispute_response)) }
crates/router/src/core/disputes.rs
router
function_signature
846
rust
null
null
null
null
accept_dispute
null
null
null
null
null
null
null
pub async fn list_countries_currencies_for_connector_payment_method_util( connector_filters: settings::ConnectorFilters, connector: api_enums::Connector, payment_method_type: api_enums::PaymentMethodType, ) -> ListCountriesCurrenciesResponse { let payment_method_type = settings::PaymentMethodFilterKey::PaymentMethodType(payment_method_type); let (currencies, country_codes) = connector_filters .0 .get(&connector.to_string()) .and_then(|filter| filter.0.get(&payment_method_type)) .map(|filter| (filter.currency.clone(), filter.country.clone())) .unwrap_or_else(|| { connector_filters .0 .get("default") .and_then(|filter| filter.0.get(&payment_method_type)) .map_or((None, None), |filter| { (filter.currency.clone(), filter.country.clone()) }) }); let currencies = currencies.unwrap_or_else(|| api_enums::Currency::iter().collect::<HashSet<_>>()); let country_codes = country_codes.unwrap_or_else(|| api_enums::CountryAlpha2::iter().collect::<HashSet<_>>()); ListCountriesCurrenciesResponse { currencies, countries: country_codes .into_iter() .map(|country_code| CountryCodeWithName { code: country_code, name: common_enums::Country::from_alpha2(country_code), }) .collect(), } }
crates/router/src/core/payment_methods/cards.rs
router
function_signature
307
rust
null
null
null
null
list_countries_currencies_for_connector_payment_method_util
null
null
null
null
null
null
null
impl crate::events::ApiEventMetric for GlobalTokenId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Token { token_id: Some(self.clone()), }) } }
crates/common_utils/src/id_type/global_id/token.rs
common_utils
impl_block
59
rust
null
GlobalTokenId
crate::events::ApiEventMetric for
impl crate::events::ApiEventMetric for for GlobalTokenId
null
null
null
null
null
null
null
null
File: crates/router/src/core/payment_methods/tokenize/card_executor.rs Public functions: 15 Public structs: 8 use std::str::FromStr; use ::payment_methods::{controller::PaymentMethodsController, core::migration}; use api_models::{enums as api_enums, payment_methods as payment_methods_api}; use common_utils::{ consts, ext_traits::OptionExt, generate_customer_id_of_default_length, id_type, pii::Email, type_name, types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{ExposeInterface, PeekInterface, SwitchStrategy}; use router_env::logger; use super::{ CardNetworkTokenizeExecutor, NetworkTokenizationBuilder, NetworkTokenizationProcess, NetworkTokenizationResponse, State, StoreLockerResponse, TransitionTo, }; use crate::{ core::payment_methods::{ cards::{add_card_to_hs_locker, PmCards}, transformers as pm_transformers, }, errors::{self, RouterResult}, types::{api, domain}, utils, }; // Available states for card tokenization pub struct TokenizeWithCard; pub struct CardRequestValidated; pub struct CardDetailsAssigned; pub struct CustomerAssigned; pub struct CardTokenized; pub struct CardStored; pub struct CardTokenStored; pub struct PaymentMethodCreated; impl State for TokenizeWithCard {} impl State for CustomerAssigned {} impl State for CardRequestValidated {} impl State for CardDetailsAssigned {} impl State for CardTokenized {} impl State for CardStored {} impl State for CardTokenStored {} impl State for PaymentMethodCreated {} // State transitions for card tokenization impl TransitionTo<CardRequestValidated> for TokenizeWithCard {} impl TransitionTo<CardDetailsAssigned> for CardRequestValidated {} impl TransitionTo<CustomerAssigned> for CardDetailsAssigned {} impl TransitionTo<CardTokenized> for CustomerAssigned {} impl TransitionTo<CardTokenStored> for CardTokenized {} impl TransitionTo<PaymentMethodCreated> for CardTokenStored {} impl Default for NetworkTokenizationBuilder<'_, TokenizeWithCard> { fn default() -> Self { Self::new() } } impl<'a> NetworkTokenizationBuilder<'a, TokenizeWithCard> { pub fn new() -> Self { Self { state: std::marker::PhantomData, customer: None, card: None, card_cvc: None, network_token: None, stored_card: None, stored_token: None, payment_method_response: None, card_tokenized: false, error_code: None, error_message: None, } } pub fn set_validate_result(self) -> NetworkTokenizationBuilder<'a, CardRequestValidated> { NetworkTokenizationBuilder { state: std::marker::PhantomData, customer: self.customer, card: self.card, card_cvc: self.card_cvc, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } } impl<'a> NetworkTokenizationBuilder<'a, CardRequestValidated> { pub fn set_card_details( self, card_req: &'a domain::TokenizeCardRequest, optional_card_info: Option<diesel_models::CardInfo>, ) -> NetworkTokenizationBuilder<'a, CardDetailsAssigned> { let card = domain::CardDetail { card_number: card_req.raw_card_number.clone(), card_exp_month: card_req.card_expiry_month.clone(), card_exp_year: card_req.card_expiry_year.clone(), bank_code: optional_card_info .as_ref() .and_then(|card_info| card_info.bank_code.clone()), nick_name: card_req.nick_name.clone(), card_holder_name: card_req.card_holder_name.clone(), card_issuer: optional_card_info .as_ref() .map_or(card_req.card_issuer.clone(), |card_info| { card_info.card_issuer.clone() }), card_network: optional_card_info .as_ref() .map_or(card_req.card_network.clone(), |card_info| { card_info.card_network.clone() }), card_type: optional_card_info.as_ref().map_or( card_req .card_type .as_ref() .map(|card_type| card_type.to_string()), |card_info| card_info.card_type.clone(), ), card_issuing_country: optional_card_info .as_ref() .map_or(card_req.card_issuing_country.clone(), |card_info| { card_info.card_issuing_country.clone() }), co_badged_card_data: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, card: Some(card), card_cvc: card_req.card_cvc.clone(), customer: self.customer, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } } impl<'a> NetworkTokenizationBuilder<'a, CardDetailsAssigned> { pub fn set_customer( self, customer: &'a api::CustomerDetails, ) -> NetworkTokenizationBuilder<'a, CustomerAssigned> { NetworkTokenizationBuilder { state: std::marker::PhantomData, customer: Some(customer), card: self.card, card_cvc: self.card_cvc, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } } impl<'a> NetworkTokenizationBuilder<'a, CustomerAssigned> { pub fn get_optional_card_and_cvc( &self, ) -> (Option<domain::CardDetail>, Option<masking::Secret<String>>) { (self.card.clone(), self.card_cvc.clone()) } pub fn set_token_details( self, network_token: &'a NetworkTokenizationResponse, ) -> NetworkTokenizationBuilder<'a, CardTokenized> { NetworkTokenizationBuilder { state: std::marker::PhantomData, network_token: Some(&network_token.0), customer: self.customer, card: self.card, card_cvc: self.card_cvc, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } } impl<'a> NetworkTokenizationBuilder<'a, CardTokenized> { pub fn set_stored_card_response( self, store_card_response: &'a StoreLockerResponse, ) -> NetworkTokenizationBuilder<'a, CardStored> { NetworkTokenizationBuilder { state: std::marker::PhantomData, stored_card: Some(&store_card_response.store_card_resp), customer: self.customer, card: self.card, card_cvc: self.card_cvc, network_token: self.network_token, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } } 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, } } } impl<'a> NetworkTokenizationBuilder<'a, CardTokenStored> { pub fn set_payment_method_response( self, payment_method: &'a domain::PaymentMethod, ) -> NetworkTokenizationBuilder<'a, PaymentMethodCreated> { let card_detail_from_locker = self.card.as_ref().map(|card| api::CardDetailFromLocker { scheme: None, issuer_country: card.card_issuing_country.clone(), last4_digits: Some(card.card_number.clone().get_last4()), card_number: None, expiry_month: Some(card.card_exp_month.clone().clone()), expiry_year: Some(card.card_exp_year.clone().clone()), card_token: None, card_holder_name: card.card_holder_name.clone(), card_fingerprint: None, nick_name: card.nick_name.clone(), card_network: card.card_network.clone(), card_isin: Some(card.card_number.clone().get_card_isin()), card_issuer: card.card_issuer.clone(), card_type: card.card_type.clone(), saved_to_locker: true, }); let payment_method_response = api::PaymentMethodResponse { merchant_id: payment_method.merchant_id.clone(), customer_id: Some(payment_method.customer_id.clone()), payment_method_id: payment_method.payment_method_id.clone(), payment_method: payment_method.payment_method, payment_method_type: payment_method.payment_method_type, card: card_detail_from_locker, recurring_enabled: Some(true), installment_payment_enabled: Some(false), metadata: payment_method.metadata.clone(), created: Some(payment_method.created_at), last_used_at: Some(payment_method.last_used_at), client_secret: payment_method.client_secret.clone(), bank_transfer: None, payment_experience: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, payment_method_response: Some(payment_method_response), customer: self.customer, card: self.card, card_cvc: self.card_cvc, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } } impl NetworkTokenizationBuilder<'_, PaymentMethodCreated> { pub fn build(self) -> api::CardNetworkTokenizeResponse { api::CardNetworkTokenizeResponse { payment_method_response: self.payment_method_response, customer: self.customer.cloned(), card_tokenized: self.card_tokenized, error_code: self.error_code.cloned(), error_message: self.error_message.cloned(), // Below field is mutated by caller functions for batched API operations tokenization_data: None, } } } // Specific executor for card tokenization impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> { pub async fn validate_request_and_fetch_optional_customer( &self, ) -> RouterResult<Option<api::CustomerDetails>> { // Validate card's expiry migration::validate_card_expiry(&self.data.card_expiry_month, &self.data.card_expiry_year)?; // Validate customer ID let customer_id = self .customer .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "customer.customer_id", })?; // Fetch customer details if present let db = &*self.state.store; let key_manager_state: &KeyManagerState = &self.state.into(); db.find_customer_optional_by_customer_id_merchant_id( key_manager_state, customer_id, self.merchant_account.get_id(), self.key_store, self.merchant_account.storage_scheme, ) .await .inspect_err(|err| logger::info!("Error fetching customer: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) .map_or( // Validate if customer creation is feasible if self.customer.name.is_some() || self.customer.email.is_some() || self.customer.phone.is_some() { Ok(None) } else { Err(report!(errors::ApiErrorResponse::MissingRequiredFields { field_names: vec!["customer.name", "customer.email", "customer.phone"], })) }, // If found, send back CustomerDetails from DB |optional_customer| { Ok(optional_customer.map(|customer| api::CustomerDetails { id: customer.customer_id.clone(), name: customer.name.clone().map(|name| name.into_inner()), email: customer.email.clone().map(Email::from), phone: customer.phone.clone().map(|phone| phone.into_inner()), phone_country_code: customer.phone_country_code.clone(), tax_registration_id: customer .tax_registration_id .clone() .map(|tax_registration_id| tax_registration_id.into_inner()), })) }, ) } pub async fn create_customer(&self) -> RouterResult<api::CustomerDetails> { let db = &*self.state.store; let customer_id = self .customer .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "customer_id", })?; let key_manager_state: &KeyManagerState = &self.state.into(); let encrypted_data = crypto_operation( key_manager_state, type_name!(domain::Customer), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.customer.name.clone(), email: self .customer .email .clone() .map(|email| email.expose().switch_strategy()), phone: self.customer.phone.clone(), tax_registration_id: self.customer.tax_registration_id.clone(), }, )), Identifier::Merchant(self.merchant_account.get_id().clone()), self.key_store.key.get_inner().peek(), ) .await .inspect_err(|err| logger::info!("Error encrypting customer: {:?}", err)) .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form EncryptableCustomer")?; let new_customer_id = generate_customer_id_of_default_length(); let domain_customer = domain::Customer { customer_id: new_customer_id.clone(), merchant_id: self.merchant_account.get_id().clone(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { utils::Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ) }), phone: encryptable_customer.phone, description: None, phone_country_code: self.customer.phone_country_code.to_owned(), metadata: None, connector_customer: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), address_id: None, default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, tax_registration_id: encryptable_customer.tax_registration_id, }; db.insert_customer( domain_customer, key_manager_state, self.key_store, self.merchant_account.storage_scheme, ) .await .inspect_err(|err| logger::info!("Error creating a customer: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to insert customer [id - {:?}] for merchant [id - {:?}]", customer_id, self.merchant_account.get_id() ) })?; Ok(api::CustomerDetails { id: new_customer_id, name: self.customer.name.clone(), email: self.customer.email.clone(), phone: self.customer.phone.clone(), phone_country_code: self.customer.phone_country_code.clone(), tax_registration_id: self.customer.tax_registration_id.clone(), }) } pub async fn store_card_and_token_in_locker( &self, network_token: &NetworkTokenizationResponse, card: &domain::CardDetail, customer_id: &id_type::CustomerId, ) -> RouterResult<StoreLockerResponse> { let stored_card_resp = self.store_card_in_locker(card, customer_id).await?; let stored_token_resp = self .store_network_token_in_locker( network_token, customer_id, card.card_holder_name.clone(), card.nick_name.clone(), ) .await?; let store_locker_response = StoreLockerResponse { store_card_resp: stored_card_resp, store_token_resp: stored_token_resp, }; Ok(store_locker_response) } pub async fn store_card_in_locker( &self, card: &domain::CardDetail, customer_id: &id_type::CustomerId, ) -> RouterResult<pm_transformers::StoreCardRespPayload> { let merchant_id = self.merchant_account.get_id(); let locker_req = pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq { merchant_id: merchant_id.clone(), merchant_customer_id: customer_id.clone(), card: payment_methods_api::Card { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_isin: Some(card.card_number.get_card_isin().clone()), name_on_card: card.card_holder_name.clone(), nick_name: card .nick_name .as_ref() .map(|nick_name| nick_name.clone().expose()), card_brand: None, }, requestor_card_reference: None, ttl: self.state.conf.locker.ttl_for_storage_in_secs, }); let stored_resp = add_card_to_hs_locker( self.state, &locker_req, customer_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(stored_resp) } pub async fn create_payment_method( &self, stored_locker_resp: &StoreLockerResponse, network_token_details: &NetworkTokenizationResponse, card_details: &domain::CardDetail, customer_id: &id_type::CustomerId, ) -> RouterResult<domain::PaymentMethod> { let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); // Form encrypted PM data (original card) let enc_pm_data = self.encrypt_card(card_details, true).await?; // Form encrypted network token data let enc_token_data = self .encrypt_network_token(network_token_details, card_details, true) .await?; // Form PM create entry let payment_method_create = api::PaymentMethodCreate { payment_method: Some(api_enums::PaymentMethod::Card), payment_method_type: card_details .card_type .as_ref() .and_then(|card_type| api_enums::PaymentMethodType::from_str(card_type).ok()), payment_method_issuer: card_details.card_issuer.clone(), payment_method_issuer_code: None, card: Some(api::CardDetail { card_number: card_details.card_number.clone(), card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_issuing_country: card_details.card_issuing_country.clone(), card_network: card_details.card_network.clone(), card_issuer: card_details.card_issuer.clone(), card_type: card_details.card_type.clone(), }), metadata: None, customer_id: Some(customer_id.clone()), card_network: card_details .card_network .as_ref() .map(|network| network.to_string()), bank_transfer: None, wallet: None, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; PmCards { state: self.state, merchant_context: &domain::MerchantContext::NormalMerchant(Box::new(domain::Context( self.merchant_account.clone(), self.key_store.clone(), ))), } .create_payment_method( &payment_method_create, customer_id, &payment_method_id, Some(stored_locker_resp.store_card_resp.card_reference.clone()), self.merchant_account.get_id(), None, None, Some(enc_pm_data), None, None, None, None, None, network_token_details.1.clone(), Some(stored_locker_resp.store_token_resp.card_reference.clone()), Some(enc_token_data), ) .await } }
crates/router/src/core/payment_methods/tokenize/card_executor.rs
router
full_file
4,693
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct ThunesPaymentsRequest { amount: StringMinorUnit, card: ThunesCard, }
crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs
hyperswitch_connectors
struct_definition
22
rust
ThunesPaymentsRequest
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.AmazonPayDeliveryOptions { "type": "object", "required": [ "id", "price", "shipping_method", "is_default" ], "properties": { "id": { "type": "string", "description": "Delivery Option identifier" }, "price": { "$ref": "#/components/schemas/AmazonPayDeliveryPrice" }, "shipping_method": { "$ref": "#/components/schemas/AmazonPayShippingMethod" }, "is_default": { "type": "boolean", "description": "Specifies if this delivery option is the default" } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
153
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "AmazonPayDeliveryOptions" ]
null
null
null
null
impl api::Payment for Authipay {}
crates/hyperswitch_connectors/src/connectors/authipay.rs
hyperswitch_connectors
impl_block
8
rust
null
Authipay
api::Payment for
impl api::Payment for for Authipay
null
null
null
null
null
null
null
null
File: crates/router/src/types/storage/routing_algorithm.rs pub use diesel_models::routing_algorithm::{ RoutingAlgorithm, RoutingAlgorithmMetadata, RoutingProfileMetadata, };
crates/router/src/types/storage/routing_algorithm.rs
router
full_file
33
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct PaymentResponse;
crates/router/src/core/payments/operations/payment_response.rs
router
struct_definition
5
rust
PaymentResponse
null
null
null
null
null
null
null
null
null
null
null
File: crates/api_models/src/refunds.rs Public functions: 2 Public structs: 19 use std::collections::HashMap; pub use common_utils::types::MinorUnit; use common_utils::{pii, types::TimeRange}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::payments::AmountFilter; #[cfg(feature = "v1")] use crate::admin; use crate::{admin::MerchantConnectorInfo, enums}; #[cfg(feature = "v1")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundRequest { /// The payment id against which refund is to be initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::PaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: Option<String>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. In case the payment went through Stripe, this field needs to be passed with one of these enums: `duplicate`, `fraudulent`, or `requested_by_customer` #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// 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#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>)] pub split_refunds: Option<common_types::refunds::SplitRefund>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundsCreateRequest { /// The payment id against which refund is initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund given by the Merchant. #[schema( max_length = 64, min_length = 1, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub merchant_reference_id: common_utils::id_type::RefundReferenceId, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrievePayload { /// `force_sync` with the connector to get refund details pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: String, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: common_utils::id_type::GlobalRefundId, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundUpdateRequest { #[serde(skip)] pub refund_id: String, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// 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#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundMetadataUpdateRequest { /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// 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#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundManualUpdateRequest { #[serde(skip)] pub refund_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The status for refund pub status: Option<RefundStatus>, /// The code for the error pub error_code: Option<String>, /// The error message pub error_message: Option<String>, } #[cfg(feature = "v1")] /// To indicate whether to refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { Scheduled, #[default] Instant, } #[cfg(feature = "v2")] /// To indicate whether the refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { Scheduled, #[default] Instant, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Unique Identifier for the refund pub refund_id: String, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code pub currency: String, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive pub reason: Option<String>, /// 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>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error message pub error_message: Option<String>, /// The code for the error pub error_code: Option<String>, /// Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601::option")] pub updated_at: Option<PrimitiveDateTime>, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe")] pub connector: String, /// The id of business profile for this refund #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>,)] pub split_refunds: Option<common_types::refunds::SplitRefund>, /// Error code received from the issuer in case of failed refunds pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed refunds pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.refund_id.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Global Refund Id for the refund #[schema(value_type = String)] pub id: common_utils::id_type::GlobalRefundId, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = Option<String>, )] pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>, /// The refund amount #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object pub reason: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error details for the refund pub error_details: Option<RefundErrorDetails>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601")] pub updated_at: PrimitiveDateTime, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe", value_type = Connector)] pub connector: enums::Connector, /// The id of business profile for this refund #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = String)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The reference id of the connector for the refund pub connector_refund_reference_id: Option<String>, } #[cfg(feature = "v2")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.id.get_string_repr().to_owned() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundErrorDetails { pub code: String, pub message: String, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::PaymentId>, /// The identifier for the refund pub refund_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, /// The identifier for the refund #[schema(value_type = String)] pub refund_id: Option<common_utils::id_type::GlobalRefundId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)] pub struct RefundListResponse { /// The number of refunds included in the list pub count: usize, /// The total number of refunds in the list pub total_count: i64, /// The List of refund response object pub data: Vec<RefundResponse>, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, ToSchema)] pub struct RefundListMetaData { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RefundListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, } /// The status for refunds #[derive( Debug, Eq, Clone, Copy, PartialEq, Default, Deserialize, Serialize, ToSchema, strum::Display, strum::EnumIter, )] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, } impl From<enums::RefundStatus> for RefundStatus { fn from(status: enums::RefundStatus) -> Self { match status { enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => Self::Failed, enums::RefundStatus::ManualReview => Self::Review, enums::RefundStatus::Pending => Self::Pending, enums::RefundStatus::Success => Self::Succeeded, } } } impl From<RefundStatus> for enums::RefundStatus { fn from(status: RefundStatus) -> Self { match status { RefundStatus::Failed => Self::Failure, RefundStatus::Review => Self::ManualReview, RefundStatus::Pending => Self::Pending, RefundStatus::Succeeded => Self::Success, } } }
crates/api_models/src/refunds.rs
api_models
full_file
5,320
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct ClickhouseConfig { username: String, password: Option<String>, host: String, }
crates/analytics/src/clickhouse.rs
analytics
struct_definition
23
rust
ClickhouseConfig
null
null
null
null
null
null
null
null
null
null
null
pub fn validate(&self) -> Result<(), String> { if let Some(payment_statuses) = &self.payment_statuses_enabled { Self::validate_statuses(payment_statuses, "payment")?; } if let Some(refund_statuses) = &self.refund_statuses_enabled { Self::validate_statuses(refund_statuses, "refund")?; } #[cfg(feature = "payouts")] { if let Some(payout_statuses) = &self.payout_statuses_enabled { Self::validate_statuses(payout_statuses, "payout")?; } } Ok(()) }
crates/api_models/src/admin.rs
api_models
function_signature
122
rust
null
null
null
null
validate
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs Public structs: 34 use std::collections::HashMap; use cards::CardNumber; use common_enums::{enums, PaymentMethod}; use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ payments::{Authorize, Capture, CompleteAuthorize, PSync}, refunds::{Execute, RSync}, }, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, ResponseId, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{consts, errors}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData, }, }; pub struct DeutschebankRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for DeutschebankRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } pub struct DeutschebankAuthType { pub(super) client_id: Secret<String>, pub(super) merchant_id: Secret<String>, pub(super) client_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { client_id: api_key.to_owned(), merchant_id: key1.to_owned(), client_key: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Default, Debug, Serialize, PartialEq)] pub struct DeutschebankAccessTokenRequest { pub grant_type: String, pub client_id: Secret<String>, pub client_secret: Secret<String>, pub scope: String, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct DeutschebankAccessTokenResponse { pub access_token: Secret<String>, pub expires_in: i64, pub expires_on: i64, pub scope: String, pub token_type: String, } impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum DeutschebankSEPAApproval { Click, Email, Sms, Dynamic, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankMandatePostRequest { approval_by: DeutschebankSEPAApproval, email_address: Email, iban: Secret<String>, first_name: Secret<String>, last_name: Secret<String>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum DeutschebankPaymentsRequest { MandatePost(DeutschebankMandatePostRequest), DirectDebit(DeutschebankDirectDebitRequest), CreditCard(Box<DeutschebankThreeDSInitializeRequest>), } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequest { means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment, tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data, amount_total: DeutschebankThreeDSInitializeRequestAmountTotal, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestMeansOfPayment { credit_card: DeutschebankThreeDSInitializeRequestCreditCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCreditCard { number: CardNumber, expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry, code: Secret<String>, cardholder: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCreditCardExpiry { year: Secret<String>, month: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestAmountTotal { amount: MinorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestTds20Data { communication_data: DeutschebankThreeDSInitializeRequestCommunicationData, customer_data: DeutschebankThreeDSInitializeRequestCustomerData, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCommunicationData { method_notification_url: String, cres_notification_url: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCustomerData { billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData, cardholder_email: Email, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCustomerBillingData { street: Secret<String>, postal_code: Secret<String>, city: String, state: Secret<String>, country: String, } impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> for DeutschebankPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item .router_data .request .mandate_id .clone() .and_then(|mandate_id| mandate_id.mandate_reference_id) { None => { // To facilitate one-off payments via SEPA with Deutsche Bank, we are considering not storing the connector mandate ID in our system if future usage is on-session. // We will only check for customer acceptance to make a one-off payment. we will be storing the connector mandate details only when setup future usage is off-session. match item.router_data.request.payment_method_data.clone() { PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => { if item.router_data.request.customer_acceptance.is_some() { let billing_address = item.router_data.get_billing_address()?; Ok(Self::MandatePost(DeutschebankMandatePostRequest { approval_by: DeutschebankSEPAApproval::Click, email_address: item.router_data.request.get_email()?, iban: Secret::from(iban.peek().replace(" ", "")), first_name: billing_address.get_first_name()?.clone(), last_name: billing_address.get_last_name()?.clone(), })) } else { Err(errors::ConnectorError::MissingRequiredField { field_name: "customer_acceptance", } .into()) } } PaymentMethodData::Card(ccard) => { if !item.router_data.clone().is_three_ds() { Err(errors::ConnectorError::NotSupported { message: "Non-ThreeDs".to_owned(), connector: "deutschebank", } .into()) } else { let billing_address = item.router_data.get_billing_address()?; Ok(Self::CreditCard(Box::new(DeutschebankThreeDSInitializeRequest { means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment { credit_card: DeutschebankThreeDSInitializeRequestCreditCard { number: ccard.clone().card_number, expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry { year: ccard.get_expiry_year_4_digit(), month: ccard.card_exp_month, }, code: ccard.card_cvc, cardholder: item.router_data.get_billing_full_name()?, }}, amount_total: DeutschebankThreeDSInitializeRequestAmountTotal { amount: item.amount, currency: item.router_data.request.currency, }, tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data { communication_data: DeutschebankThreeDSInitializeRequestCommunicationData { method_notification_url: item.router_data.request.get_complete_authorize_url()?, cres_notification_url: item.router_data.request.get_complete_authorize_url()?, }, customer_data: DeutschebankThreeDSInitializeRequestCustomerData { billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData { street: billing_address.get_line1()?.clone(), postal_code: billing_address.get_zip()?.clone(), city: billing_address.get_city()?.to_string(), state: billing_address.get_state()?.clone(), country: item.router_data.get_billing_country()?.to_string(), }, cardholder_email: item.router_data.request.get_email()?, } } }))) } } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()), } } Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => { let mandate_metadata: DeutschebankMandateMetadata = mandate_data .get_mandate_metadata() .ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)? .clone() .parse_value("DeutschebankMandateMetadata") .change_context(errors::ConnectorError::ParsingFailed)?; Ok(Self::DirectDebit(DeutschebankDirectDebitRequest { amount_total: DeutschebankAmount { amount: item.amount, currency: item.router_data.request.currency, }, means_of_payment: DeutschebankMeansOfPayment { bank_account: DeutschebankBankAccount { account_holder: mandate_metadata.account_holder, iban: mandate_metadata.iban, }, }, mandate: DeutschebankMandate { reference: mandate_metadata.reference, signed_on: mandate_metadata.signed_on, }, })) } Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) | Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()) } } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankThreeDSInitializeResponse { outcome: DeutschebankThreeDSInitializeResponseOutcome, challenge_required: Option<DeutschebankThreeDSInitializeResponseChallengeRequired>, processed: Option<DeutschebankThreeDSInitializeResponseProcessed>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankThreeDSInitializeResponseProcessed { rc: String, message: String, tx_id: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DeutschebankThreeDSInitializeResponseOutcome { Processed, ChallengeRequired, MethodRequired, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankThreeDSInitializeResponseChallengeRequired { acs_url: String, creq: String, } impl TryFrom< ResponseRouterData< Authorize, DeutschebankThreeDSInitializeResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, DeutschebankThreeDSInitializeResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response.outcome { DeutschebankThreeDSInitializeResponseOutcome::Processed => { match item.response.processed { Some(processed) => Ok(Self { status: if is_response_success(&processed.rc) { match item.data.request.is_auto_capture()? { true => common_enums::AttemptStatus::Charged, false => common_enums::AttemptStatus::Authorized, } } else { common_enums::AttemptStatus::AuthenticationFailed }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( processed.tx_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(processed.tx_id.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }), None => { let response_string = format!("{:?}", item.response); Err( errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from( response_string, )) .into(), ) } } } DeutschebankThreeDSInitializeResponseOutcome::ChallengeRequired => { match item.response.challenge_required { Some(challenge) => Ok(Self { status: common_enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some( RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url: challenge.acs_url, creq: challenge.creq, }, )), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), None => { let response_string = format!("{:?}", item.response); Err( errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from( response_string, )) .into(), ) } } } DeutschebankThreeDSInitializeResponseOutcome::MethodRequired => Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: consts::NO_ERROR_CODE.to_owned(), message: "METHOD_REQUIRED Flow not supported for deutschebank 3ds payments".to_owned(), reason: Some("METHOD_REQUIRED Flow is not currently supported for deutschebank 3ds payments".to_owned()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None,network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DeutschebankSEPAMandateStatus { Created, PendingApproval, PendingSecondaryApproval, PendingReview, PendingSubmission, Submitted, Active, Failed, Discarded, Expired, Replaced, } impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus { fn from(item: DeutschebankSEPAMandateStatus) -> Self { match item { DeutschebankSEPAMandateStatus::Active | DeutschebankSEPAMandateStatus::Created | DeutschebankSEPAMandateStatus::PendingApproval | DeutschebankSEPAMandateStatus::PendingSecondaryApproval | DeutschebankSEPAMandateStatus::PendingReview | DeutschebankSEPAMandateStatus::PendingSubmission | DeutschebankSEPAMandateStatus::Submitted => Self::AuthenticationPending, DeutschebankSEPAMandateStatus::Failed | DeutschebankSEPAMandateStatus::Discarded | DeutschebankSEPAMandateStatus::Expired | DeutschebankSEPAMandateStatus::Replaced => Self::Failure, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankMandateMetadata { account_holder: Secret<String>, iban: Secret<String>, reference: Secret<String>, signed_on: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankMandatePostResponse { rc: String, message: String, mandate_id: Option<String>, reference: Option<String>, approval_date: Option<String>, language: Option<String>, approval_by: Option<DeutschebankSEPAApproval>, state: Option<DeutschebankSEPAMandateStatus>, } fn get_error_response(error_code: String, error_reason: String, status_code: u16) -> ErrorResponse { ErrorResponse { code: error_code.to_string(), message: error_reason.clone(), reason: Some(error_reason), status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } fn is_response_success(rc: &String) -> bool { rc == "0" } impl TryFrom< ResponseRouterData< Authorize, DeutschebankMandatePostResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, DeutschebankMandatePostResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let signed_on = match item.response.approval_date.clone() { Some(date) => date.chars().take(10).collect(), None => time::OffsetDateTime::now_utc().date().to_string(), }; let response_code = item.response.rc.clone(); let is_response_success = is_response_success(&response_code); match ( item.response.reference.clone(), item.response.state.clone(), is_response_success, ) { (Some(reference), Some(state), true) => Ok(Self { status: common_enums::AttemptStatus::from(state), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some(RedirectForm::Form { endpoint: item.data.request.get_complete_authorize_url()?, method: common_utils::request::Method::Get, form_fields: HashMap::from([ ("reference".to_string(), reference.clone()), ("signed_on".to_string(), signed_on.clone()), ]), })), mandate_reference: if item.data.request.is_mandate_payment() { Box::new(Some(MandateReference { connector_mandate_id: item.response.mandate_id, payment_method_id: None, mandate_metadata: Some(Secret::new( serde_json::json!(DeutschebankMandateMetadata { account_holder: item.data.get_billing_address()?.get_full_name()?, iban: match item.data.request.payment_method_data.clone() { PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => Ok(Secret::from(iban.peek().replace(" ", ""))), _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_data.bank_debit.sepa_bank_debit.iban" }), }?, reference: Secret::from(reference.clone()), signed_on, }), )), connector_mandate_request_reference_id: None, })) } else { Box::new(None) }, connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), _ => Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }), } } } impl TryFrom< ResponseRouterData< Authorize, DeutschebankPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, DeutschebankPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { status: match item.data.request.is_auto_capture()? { true => common_enums::AttemptStatus::Charged, false => common_enums::AttemptStatus::Authorized, }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct DeutschebankAmount { amount: MinorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankMeansOfPayment { bank_account: DeutschebankBankAccount, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankBankAccount { account_holder: Secret<String>, iban: Secret<String>, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankMandate { reference: Secret<String>, signed_on: String, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankDirectDebitRequest { amount_total: DeutschebankAmount, means_of_payment: DeutschebankMeansOfPayment, mandate: DeutschebankMandate, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum DeutschebankCompleteAuthorizeRequest { DeutschebankDirectDebitRequest(DeutschebankDirectDebitRequest), DeutschebankThreeDSCompleteAuthorizeRequest(DeutschebankThreeDSCompleteAuthorizeRequest), } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankThreeDSCompleteAuthorizeRequest { cres: String, } impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> for DeutschebankCompleteAuthorizeRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if matches!(item.router_data.payment_method, PaymentMethod::Card) { let redirect_response_payload = item .router_data .request .get_redirect_response_payload()? .expose(); let cres = redirect_response_payload .get("cres") .and_then(|v| v.as_str()) .map(String::from) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "cres" })?; Ok(Self::DeutschebankThreeDSCompleteAuthorizeRequest( DeutschebankThreeDSCompleteAuthorizeRequest { cres }, )) } else { match item.router_data.request.payment_method_data.clone() { Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. })) => { let account_holder = item.router_data.get_billing_address()?.get_full_name()?; let redirect_response = item.router_data.request.redirect_response.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", }, )?; let queries_params = redirect_response .params .map(|param| { let mut queries = HashMap::<String, String>::new(); let values = param.peek().split('&').collect::<Vec<&str>>(); for value in values { let pair = value.split('=').collect::<Vec<&str>>(); queries.insert( pair.first() .ok_or( errors::ConnectorError::ResponseDeserializationFailed, )? .to_string(), pair.get(1) .ok_or( errors::ConnectorError::ResponseDeserializationFailed, )? .to_string(), ); } Ok::<_, errors::ConnectorError>(queries) }) .transpose()? .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let reference = Secret::from( queries_params .get("reference") .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "reference", })? .to_owned(), ); let signed_on = queries_params .get("signed_on") .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "signed_on", })? .to_owned(); Ok(Self::DeutschebankDirectDebitRequest( DeutschebankDirectDebitRequest { amount_total: DeutschebankAmount { amount: item.amount, currency: item.router_data.request.currency, }, means_of_payment: DeutschebankMeansOfPayment { bank_account: DeutschebankBankAccount { account_holder, iban: Secret::from(iban.peek().replace(" ", "")), }, }, mandate: { DeutschebankMandate { reference, signed_on, } }, }, )) } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()), } } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum DeutschebankTXAction { Authorization, Capture, Credit, Preauthorization, Refund, Reversal, RiskCheck, #[serde(rename = "verify-mop")] VerifyMop, Payment, AccountInformation, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct BankAccount { account_holder: Option<Secret<String>>, bank_name: Option<Secret<String>>, bic: Option<Secret<String>>, iban: Option<Secret<String>>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct TransactionBankAccountInfo { bank_account: Option<BankAccount>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct DeutschebankTransactionInfo { back_state: Option<String>, ip_address: Option<Secret<String>>, #[serde(rename = "type")] pm_type: Option<String>, transaction_bankaccount_info: Option<TransactionBankAccountInfo>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct DeutschebankPaymentsResponse { rc: String, message: String, timestamp: String, back_ext_id: Option<String>, back_rc: Option<String>, event_id: Option<String>, kind: Option<String>, tx_action: Option<DeutschebankTXAction>, tx_id: String, amount_total: Option<DeutschebankAmount>, transaction_info: Option<DeutschebankTransactionInfo>, } impl TryFrom< ResponseRouterData< CompleteAuthorize, DeutschebankPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, > for RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< CompleteAuthorize, DeutschebankPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { status: match item.data.request.is_auto_capture()? { true => common_enums::AttemptStatus::Charged, false => common_enums::AttemptStatus::Authorized, }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum DeutschebankTransactionKind { Directdebit, #[serde(rename = "CREDITCARD_3DS20")] Creditcard3ds20, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankCaptureRequest { changed_amount: MinorUnit, kind: DeutschebankTransactionKind, } impl TryFrom<&DeutschebankRouterData<&PaymentsCaptureRouterData>> for DeutschebankCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DeutschebankRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) { Ok(Self { changed_amount: item.amount, kind: DeutschebankTransactionKind::Directdebit, }) } else if item.router_data.is_three_ds() && matches!(item.router_data.payment_method, PaymentMethod::Card) { Ok(Self { changed_amount: item.amount, kind: DeutschebankTransactionKind::Creditcard3ds20, }) } else { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()) } } } impl TryFrom< ResponseRouterData< Capture, DeutschebankPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, > for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Capture, DeutschebankPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { status: common_enums::AttemptStatus::Charged, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } impl TryFrom< ResponseRouterData< PSync, DeutschebankPaymentsResponse, PaymentsSyncData, PaymentsResponseData, >, > for RouterData<PSync, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< PSync, DeutschebankPaymentsResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); let status = if is_response_success(&response_code) { item.response .tx_action .and_then(|tx_action| match tx_action { DeutschebankTXAction::Preauthorization => { Some(common_enums::AttemptStatus::Authorized) } DeutschebankTXAction::Authorization | DeutschebankTXAction::Capture => { Some(common_enums::AttemptStatus::Charged) } DeutschebankTXAction::Credit | DeutschebankTXAction::Refund | DeutschebankTXAction::Reversal | DeutschebankTXAction::RiskCheck | DeutschebankTXAction::VerifyMop | DeutschebankTXAction::Payment | DeutschebankTXAction::AccountInformation => None, }) } else { Some(common_enums::AttemptStatus::Failure) }; match status { Some(common_enums::AttemptStatus::Failure) => Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }), Some(status) => Ok(Self { status, ..item.data }), None => Ok(Self { ..item.data }), } } } #[derive(Debug, Serialize)] pub struct DeutschebankReversalRequest { kind: DeutschebankTransactionKind, } impl TryFrom<&PaymentsCancelRouterData> for DeutschebankReversalRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { if matches!(item.payment_method, PaymentMethod::BankDebit) { Ok(Self { kind: DeutschebankTransactionKind::Directdebit, }) } else if item.is_three_ds() && matches!(item.payment_method, PaymentMethod::Card) { Ok(Self { kind: DeutschebankTransactionKind::Creditcard3ds20, }) } else { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()) } } } impl TryFrom<PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>> for PaymentsCancelRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { status: common_enums::AttemptStatus::Voided, ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::VoidFailed, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } #[derive(Debug, Serialize)] pub struct DeutschebankRefundRequest { changed_amount: MinorUnit, kind: DeutschebankTransactionKind, } impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &DeutschebankRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) { Ok(Self { changed_amount: item.amount, kind: DeutschebankTransactionKind::Directdebit, }) } else if item.router_data.is_three_ds() && matches!(item.router_data.payment_method, PaymentMethod::Card) { Ok(Self { changed_amount: item.amount, kind: DeutschebankTransactionKind::Creditcard3ds20, }) } else { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()) } } } impl TryFrom<RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>;
crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs#chunk0
hyperswitch_connectors
chunk
8,192
null
null
null
null
null
null
null
null
null
null
null
null
null
/// Create a new merchant_id from unix timestamp, of the format `merchant_{timestamp}` pub fn new_from_unix_timestamp() -> Self { let merchant_id = format!("merchant_{}", date_time::now_unix_timestamp()); let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) }
crates/common_utils/src/id_type/merchant.rs
common_utils
function_signature
84
rust
null
null
null
null
new_from_unix_timestamp
null
null
null
null
null
null
null
pub struct Cashtocode { amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), }
crates/hyperswitch_connectors/src/connectors/cashtocode.rs
hyperswitch_connectors
struct_definition
28
rust
Cashtocode
null
null
null
null
null
null
null
null
null
null
null
pub struct NoonRefundResponseResult { transaction: NoonPaymentsTransactionResponse, }
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
hyperswitch_connectors
struct_definition
17
rust
NoonRefundResponseResult
null
null
null
null
null
null
null
null
null
null
null
Web Documentation: Payment Operations | Hyperswitch # Type: Web Doc Hyperswitch Control Center streamlines the complexities of managing payments, ensuring operational efficiency and control over every aspect of payment flow. From account management to real-time analytics, Hyperswitch empowers businesses with the tools to simplify operations, reduce errors, and enhance decision-making. With advanced features like dispute resolution, reconciliation, and multi-tenancy support, businesses can focus on growth while we handle the operational details. Managing Accounts and Profiles Manage Your Team Analytics & Operations Disputes / Chargebacks Reconciliation Surcharge Multi-Tenancy \ 11 months ago Was this helpful?
https://docs.hyperswitch.io/explore-hyperswitch/account-management
null
web_doc_file
140
doc
null
null
null
null
null
web
null
null
null
https://docs.hyperswitch.io/explore-hyperswitch/account-management
Payment Operations | Hyperswitch
null
pub struct Fraud { pub outcome: FraudOutcome, pub score: f32, }
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
hyperswitch_connectors
struct_definition
20
rust
Fraud
null
null
null
null
null
null
null
null
null
null
null
pub fn track_response_status_code<Q>(response: &ApplicationResponse<Q>) -> i64 { match response { ApplicationResponse::Json(_) | ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::Form(_) | ApplicationResponse::GenericLinkForm(_) | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) | ApplicationResponse::JsonWithHeaders(_) => 200, ApplicationResponse::JsonForRedirection(_) => 302, } }
crates/router/src/routes/metrics/request.rs
router
function_signature
118
rust
null
null
null
null
track_response_status_code
null
null
null
null
null
null
null
File: crates/hyperswitch_interfaces/src/api/refunds_v2.rs //! Refunds V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::RefundFlowData, router_flow_types::refunds::{Execute, RSync}, router_request_types::RefundsData, router_response_types::RefundsResponseData, }; use crate::api::{ConnectorCommon, ConnectorIntegrationV2}; /// trait RefundExecuteV2 pub trait RefundExecuteV2: ConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData> { } /// trait RefundSyncV2 pub trait RefundSyncV2: ConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData> { } /// trait RefundV2 pub trait RefundV2: ConnectorCommon + RefundExecuteV2 + RefundSyncV2 {}
crates/hyperswitch_interfaces/src/api/refunds_v2.rs
hyperswitch_interfaces
full_file
200
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct GlobepayPaymentsRequest { price: MinorUnit, description: String, currency: enums::Currency, channel: GlobepayChannel, }
crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
hyperswitch_connectors
struct_definition
35
rust
GlobepayPaymentsRequest
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentToken for Checkout {}
crates/hyperswitch_connectors/src/connectors/checkout.rs
hyperswitch_connectors
impl_block
8
rust
null
Checkout
api::PaymentToken for
impl api::PaymentToken for for Checkout
null
null
null
null
null
null
null
null
pub struct SaleQuery { sale_status: SaleStatus, sale_payme_id: String, sale_error_text: Option<String>, sale_error_code: Option<String>, }
crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
hyperswitch_connectors
struct_definition
37
rust
SaleQuery
null
null
null
null
null
null
null
null
null
null
null
pub struct BluecodeRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, }
crates/hyperswitch_connectors/src/connectors/bluecode/transformers.rs
hyperswitch_connectors
struct_definition
25
rust
BluecodeRouterData
null
null
null
null
null
null
null
null
null
null
null
pub fn get_optional_email(&self) -> Option<pii::Email> { Some(self.email.clone()) }
crates/api_models/src/customers.rs
api_models
function_signature
24
rust
null
null
null
null
get_optional_email
null
null
null
null
null
null
null
pub fn get_merchant_reference_id(&self) -> id_type::MerchantId { id_type::MerchantId::from_merchant_name(self.merchant_name.clone().expose()) }
crates/api_models/src/admin.rs
api_models
function_signature
39
rust
null
null
null
null
get_merchant_reference_id
null
null
null
null
null
null
null
impl Rapyd { pub fn new() -> &'static Self { &Self { amount_converter: &FloatMajorUnitForConnector, amount_converter_webhooks: &StringMinorUnitForConnector, } } }
crates/hyperswitch_connectors/src/connectors/rapyd.rs
hyperswitch_connectors
impl_block
48
rust
null
Rapyd
null
impl Rapyd
null
null
null
null
null
null
null
null
pub fn method(mut self, method: Method) -> Self { self.method = method; self }
crates/common_utils/src/request.rs
common_utils
function_signature
24
rust
null
null
null
null
method
null
null
null
null
null
null
null
impl api::PaymentVoid for Blackhawknetwork {}
crates/hyperswitch_connectors/src/connectors/blackhawknetwork.rs
hyperswitch_connectors
impl_block
10
rust
null
Blackhawknetwork
api::PaymentVoid for
impl api::PaymentVoid for for Blackhawknetwork
null
null
null
null
null
null
null
null
pub async fn list_profiles_for_user_in_org_and_merchant_account( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::ListProfilesForUserInOrgAndMerchantAccountResponse>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &user_from_token.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; let profiles = match role_info.get_entity_type() { EntityType::Tenant | EntityType::Organization | EntityType::Merchant => state .store .list_profile_by_merchant_id( key_manager_state, &key_store, &user_from_token.merchant_id, ) .await .change_context(UserErrors::InternalServerError)?, EntityType::Profile => { let profile_ids = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&user_from_token.merchant_id), profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .filter_map(|user_role| user_role.profile_id) .collect::<HashSet<_>>(); futures::future::try_join_all(profile_ids.iter().map(|profile_id| { state.store.find_business_profile_by_profile_id( key_manager_state, &key_store, profile_id, ) })) .await .change_context(UserErrors::InternalServerError)? } }; if profiles.is_empty() { Err(UserErrors::InternalServerError).attach_printable("No profile found for a user")?; } Ok(ApplicationResponse::Json( profiles .into_iter() .map( |profile| user_api::ListProfilesForUserInOrgAndMerchantAccountResponse { profile_id: profile.get_id().to_owned(), profile_name: profile.profile_name, }, ) .collect::<Vec<_>>(), )) }
crates/router/src/core/user.rs
router
function_signature
618
rust
null
null
null
null
list_profiles_for_user_in_org_and_merchant_account
null
null
null
null
null
null
null
impl api::MandateSetup for Moneris {}
crates/hyperswitch_connectors/src/connectors/moneris.rs
hyperswitch_connectors
impl_block
12
rust
null
Moneris
api::MandateSetup for
impl api::MandateSetup for for Moneris
null
null
null
null
null
null
null
null
impl api::PaymentsPreProcessing for Nmi {}
crates/hyperswitch_connectors/src/connectors/nmi.rs
hyperswitch_connectors
impl_block
10
rust
null
Nmi
api::PaymentsPreProcessing for
impl api::PaymentsPreProcessing for for Nmi
null
null
null
null
null
null
null
null
pub struct PayPalActionUrlResponse { pub action_url: String, }
crates/api_models/src/connector_onboarding.rs
api_models
struct_definition
15
rust
PayPalActionUrlResponse
null
null
null
null
null
null
null
null
null
null
null
pub struct PaypalSourceVerificationRequest { pub transmission_id: String, pub transmission_time: String, pub cert_url: String, pub transmission_sig: String, pub auth_algo: String, pub webhook_id: String, pub webhook_event: serde_json::Value, }
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
struct_definition
60
rust
PaypalSourceVerificationRequest
null
null
null
null
null
null
null
null
null
null
null