id stringlengths 20 153 | type stringclasses 1
value | granularity stringclasses 14
values | content stringlengths 16 84.3k | metadata dict |
|---|---|---|---|---|
connector-service_mini_connector-integration_-4518715165494810008_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/mifinity/transformers.rs
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::RevolutPay(_) => Err(ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Mifinity"),
)
.into()),
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Mifinity"),
)
.into())
}
}
}
}
// Auth Struct
pub struct MifinityAuthType {
pub(super) key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for MifinityAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MifinityPaymentsResponse {
payload: Vec<MifinityPayload>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MifinityPayload {
trace_id: String,
initialization_token: Secret<String>,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<MifinityPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<MifinityPaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let payload = item.response.payload.first();
match payload {
Some(payload) => {
let trace_id = payload.trace_id.clone();
let initialization_token = payload.initialization_token.clone();
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(trace_id.clone()),
redirection_data: Some(Box::new(RedirectForm::Mifinity {
initialization_token: initialization_token.expose(),
})),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(trace_id),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
resource_common_data: PaymentFlowData {
status: enums::AttemptStatus::AuthenticationPending,
| {
"chunk": 2,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-4518715165494810008_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/mifinity/transformers.rs
..item.router_data.resource_common_data
},
..item.router_data
})
}
None => Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
resource_common_data: PaymentFlowData {
status: enums::AttemptStatus::AuthenticationPending,
..item.router_data.resource_common_data
},
..item.router_data
}),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MifinityPsyncResponse {
payload: Vec<MifinityPsyncPayload>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MifinityPsyncPayload {
status: MifinityPaymentStatus,
payment_response: Option<PaymentResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentResponse {
trace_id: Option<String>,
client_reference: Option<String>,
validation_key: Option<String>,
transaction_reference: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MifinityPaymentStatus {
Successful,
Pending,
Failed,
NotCompleted,
}
impl<F> TryFrom<ResponseRouterData<MifinityPsyncResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<MifinityPsyncResponse, Self>,
) -> Result<Self, Self::Error> {
let payload = item.response.payload.first();
match payload {
Some(payload) => {
let status = payload.status.clone();
let payment_response = payload.payment_response.clone();
match payment_response {
Some(payment_response) => {
let transaction_reference = payment_response.transaction_reference.clone();
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction_reference,
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
resource_common_data: PaymentFlowData {
status: enums::AttemptStatus::from(status),
..item.router_data.resource_common_data
},
..item.router_data
})
}
None => Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
resource_common_data: PaymentFlowData {
| {
"chunk": 3,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-4518715165494810008_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/mifinity/transformers.rs
status: enums::AttemptStatus::from(status),
..item.router_data.resource_common_data
},
..item.router_data
}),
}
}
None => Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
resource_common_data: PaymentFlowData {
status: item.router_data.resource_common_data.status,
..item.router_data.resource_common_data
},
..item.router_data
}),
}
}
}
impl From<MifinityPaymentStatus> for enums::AttemptStatus {
fn from(item: MifinityPaymentStatus) -> Self {
match item {
MifinityPaymentStatus::Successful => Self::Charged,
MifinityPaymentStatus::Failed => Self::Failure,
MifinityPaymentStatus::NotCompleted => Self::AuthenticationPending,
MifinityPaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct MifinityErrorResponse {
pub errors: Vec<MifinityErrorList>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MifinityErrorList {
#[serde(rename = "type")]
pub error_type: String,
pub error_code: String,
pub message: String,
pub field: Option<String>,
}
| {
"chunk": 4,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
use std::{collections::HashMap, fmt::Debug, ops::Deref, str::FromStr};
use common_utils::{
collect_missing_value_keys, consts, custom_serde,
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode, OptionExt},
pii::{self, Email},
request::Method,
types::MinorUnit,
};
use domain_types::{
connector_flow::{
Authorize, Capture, CreateConnectorCustomer, RepeatPayment, SetupMandate, Void,
},
connector_types::{
ConnectorCustomerData, ConnectorCustomerResponse, MandateReference, MandateReferenceId,
PaymentFlowData, PaymentVoidData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData,
RefundsResponseData, RepeatPaymentData, ResponseId, SetupMandateRequestData,
},
errors::{self, ConnectorError},
mandates::AcceptanceType,
payment_method_data::{
self, AchTransfer, BankRedirectData, BankTransferInstructions, BankTransferNextStepsData,
Card, CardRedirectData, GiftCardData, GooglePayWalletData, MultibancoTransferInstructions,
PayLaterData, PaymentMethodData, PaymentMethodDataTypes, RawCardNumber, VoucherData,
WalletData,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ExtendedAuthorizationResponseData,
},
router_data_v2::RouterDataV2,
router_request_types::{
AuthoriseIntegrityObject, BrowserInformation, CaptureIntegrityObject,
PaymentSynIntegrityObject, RefundIntegrityObject,
},
router_response_types::RedirectForm,
utils::{get_unimplemented_payment_method_error_message, is_payment_failure},
};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::PrimitiveDateTime;
use url::Url;
use crate::{
connectors::stripe::{
headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT, StripeAmountConvertor, StripeRouterData,
},
types::ResponseRouterData,
utils::{
convert_uppercase, deserialize_zero_minor_amount_as_none, is_refund_failure,
SplitPaymentData,
},
};
pub mod auth_headers {
pub const STRIPE_API_VERSION: &str = "stripe-version";
pub const STRIPE_VERSION: &str = "2022-11-15";
}
trait GetRequestIncrementalAuthorization {
fn get_request_incremental_authorization(&self) -> Option<bool>;
}
impl<T: PaymentMethodDataTypes> GetRequestIncrementalAuthorization for PaymentsAuthorizeData<T> {
fn get_request_incremental_authorization(&self) -> Option<bool> {
Some(self.request_incremental_authorization)
}
}
impl GetRequestIncrementalAuthorization for PaymentsCaptureData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
None
}
}
impl GetRequestIncrementalAuthorization for PaymentVoidData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
None
}
}
impl GetRequestIncrementalAuthorization for RepeatPaymentData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
None
}
}
pub struct StripeAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for StripeAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = item {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum StripeCaptureMethod {
Manual,
#[default]
Automatic,
}
impl From<Option<common_enums::CaptureMethod>> for StripeCaptureMethod {
fn from(item: Option<common_enums::CaptureMethod>) -> Self {
match item {
Some(p) => match p {
common_enums::CaptureMethod::ManualMultiple => Self::Manual,
common_enums::CaptureMethod::Manual => Self::Manual,
common_enums::CaptureMethod::Automatic
| common_enums::CaptureMethod::SequentialAutomatic => Self::Automatic,
| {
"chunk": 0,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
common_enums::CaptureMethod::Scheduled => Self::Manual,
},
None => Self::Automatic,
}
}
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Auth3ds {
#[default]
Automatic,
Any,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeCardNetwork {
CartesBancaires,
Mastercard,
Visa,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(
rename_all = "snake_case",
tag = "mandate_data[customer_acceptance][type]"
)]
pub enum StripeMandateType {
Online {
#[serde(rename = "mandate_data[customer_acceptance][online][ip_address]")]
ip_address: Secret<String, pii::IpAddress>,
#[serde(rename = "mandate_data[customer_acceptance][online][user_agent]")]
user_agent: String,
},
Offline,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeMandateRequest {
#[serde(flatten)]
mandate_type: StripeMandateType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ExpandableObjects {
LatestCharge,
Customer,
LatestAttempt,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeBrowserInformation {
#[serde(rename = "payment_method_data[ip]")]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
#[serde(rename = "payment_method_data[user_agent]")]
pub user_agent: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct PaymentIntentRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub amount: MinorUnit, //amount in cents, hence passed as integer
pub currency: String,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor: Option<String>,
#[serde(flatten)]
pub meta_data: HashMap<String, String>,
pub return_url: String,
pub confirm: bool,
pub payment_method: Option<Secret<String>>,
pub customer: Option<Secret<String>>,
#[serde(flatten)]
pub setup_mandate_details: Option<StripeMandateRequest>,
pub description: Option<String>,
#[serde(flatten)]
pub shipping: Option<StripeShippingAddress>,
#[serde(flatten)]
pub billing: StripeBillingAddress,
#[serde(flatten)]
pub payment_data: Option<StripePaymentMethodData<T>>,
pub capture_method: StripeCaptureMethod,
#[serde(flatten)]
pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated
pub setup_future_usage: Option<common_enums::FutureUsage>,
pub off_session: Option<bool>,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_types: Option<StripePaymentMethodType>,
#[serde(rename = "expand[0]")]
pub expand: Option<ExpandableObjects>,
#[serde(flatten)]
pub browser_info: Option<StripeBrowserInformation>,
#[serde(flatten)]
pub charges: Option<IntentCharges>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct IntentCharges {
pub application_fee_amount: Option<MinorUnit>,
#[serde(
rename = "transfer_data[destination]",
skip_serializing_if = "Option::is_none"
)]
pub destination_account_id: Option<Secret<String>>,
}
// Field rename is required only in case of serialization as it is passed in the request to the connector.
// Deserialization is happening only in case of webhooks, where fields name should be used as defined in the struct.
// Whenever adding new fields, Please ensure it doesn't break the webhook flow
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct StripeMetadata {
// merchant_reference_id
#[serde(rename(serialize = "metadata[order_id]"))]
pub order_id: Option<String>,
// to check whether the order_id is refund_id or payment_id
// before deployment, order id is set to payment_id in refunds but now it is set as refund_id
// it is set as string instead of bool because stripe pass it as string even if we set it as bool
#[serde(rename(serialize = "metadata[is_refund_id_as_reference]"))]
pub is_refund_id_as_reference: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct SetupMandateRequest<
T: PaymentMethodDataTypes
| {
"chunk": 1,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub confirm: bool,
pub usage: Option<common_enums::FutureUsage>,
pub customer: Option<Secret<String>>,
pub off_session: Option<bool>,
pub return_url: Option<String>,
#[serde(flatten)]
pub payment_data: StripePaymentMethodData<T>,
pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated
#[serde(flatten)]
pub meta_data: Option<HashMap<String, String>>,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_types: Option<StripePaymentMethodType>,
#[serde(rename = "expand[0]")]
pub expand: Option<ExpandableObjects>,
#[serde(flatten)]
pub browser_info: Option<StripeBrowserInformation>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeCardData<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[card][number]")]
pub payment_method_data_card_number: RawCardNumber<T>,
#[serde(rename = "payment_method_data[card][exp_month]")]
pub payment_method_data_card_exp_month: Secret<String>,
#[serde(rename = "payment_method_data[card][exp_year]")]
pub payment_method_data_card_exp_year: Secret<String>,
#[serde(rename = "payment_method_data[card][cvc]")]
pub payment_method_data_card_cvc: Option<Secret<String>>,
#[serde(rename = "payment_method_options[card][request_three_d_secure]")]
pub payment_method_auth_type: Option<Auth3ds>,
#[serde(rename = "payment_method_options[card][network]")]
pub payment_method_data_card_preferred_network: Option<StripeCardNetwork>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "payment_method_options[card][request_incremental_authorization]")]
pub request_incremental_authorization: Option<StripeRequestIncrementalAuthorization>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "payment_method_options[card][request_extended_authorization]")]
request_extended_authorization: Option<StripeRequestExtendedAuthorization>,
#[serde(rename = "payment_method_options[card][request_overcapture]")]
pub request_overcapture: Option<StripeRequestOvercaptureBool>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeRequestIncrementalAuthorization {
IfAvailable,
Never,
}
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripeRequestExtendedAuthorization {
IfAvailable,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeRequestOvercaptureBool {
IfAvailable,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripePayLaterData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct TokenRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
#[serde(flatten)]
pub token_data: StripePaymentMethodData<T>,
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeTokenResponse {
pub id: Secret<String>,
pub object: String,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct CreateConnectorCustomerRequest {
pub description: Option<String>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
pub source: Option<Secret<String>>,
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct CreateConnectorCustomerResponse {
pub id: String,
pub description: Option<String>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ChargesRequest {
pub amount: MinorUnit,
pub currency: String,
pub customer: Secret<String>,
pub source: Secret<String>,
#[serde(flatten)]
| {
"chunk": 2,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
pub meta_data: Option<HashMap<String, String>>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct ChargesResponse {
pub id: String,
pub amount: MinorUnit,
pub amount_captured: MinorUnit,
pub currency: String,
pub status: StripePaymentStatus,
pub source: StripeSourceResponse,
pub failure_code: Option<String>,
pub failure_message: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeBankName {
Eps {
#[serde(rename = "payment_method_data[eps][bank]")]
bank_name: Option<StripeBankNames>,
},
Ideal {
#[serde(rename = "payment_method_data[ideal][bank]")]
ideal_bank_name: Option<StripeBankNames>,
},
Przelewy24 {
#[serde(rename = "payment_method_data[p24][bank]")]
bank_name: Option<StripeBankNames>,
},
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeBankRedirectData {
StripeGiropay(Box<StripeGiropay>),
StripeIdeal(Box<StripeIdeal>),
StripeBancontactCard(Box<StripeBancontactCard>),
StripePrezelewy24(Box<StripePrezelewy24>),
StripeEps(Box<StripeEps>),
StripeBlik(Box<StripeBlik>),
StripeOnlineBankingFpx(Box<StripeOnlineBankingFpx>),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeGiropay {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeIdeal {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[ideal][bank]")]
ideal_bank_name: Option<StripeBankNames>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeBancontactCard {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripePrezelewy24 {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[p24][bank]")]
bank_name: Option<StripeBankNames>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeEps {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[eps][bank]")]
bank_name: Option<StripeBankNames>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeBlik {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[blik][code]")]
pub code: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeOnlineBankingFpx {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AchTransferData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")]
pub bank_transfer_type: StripeCreditTransferTypes,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[customer_balance][funding_type]")]
pub balance_funding_type: BankTransferType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct MultibancoTransferData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripeCreditTransferTypes,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_type: StripeCreditTransferTypes,
#[serde(rename = "payment_method_data[billing_details][email]")]
pub email: Email,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct BacsBankTransferData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")]
pub bank_transfer_type: BankTransferType,
#[serde(rename = "payment_method_options[customer_balance][funding_type]")]
pub balance_funding_type: BankTransferType,
#[serde(rename = "payment_method_types[0]")]
| {
"chunk": 3,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
pub payment_method_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct SepaBankTransferData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")]
pub bank_transfer_type: BankTransferType,
#[serde(rename = "payment_method_options[customer_balance][funding_type]")]
pub balance_funding_type: BankTransferType,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_type: StripePaymentMethodType,
#[serde(
rename = "payment_method_options[customer_balance][bank_transfer][eu_bank_transfer][country]"
)]
pub country: common_enums::CountryAlpha2,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeCreditTransferSourceRequest {
AchBankTransfer(AchCreditTransferSourceRequest),
MultibancoBankTransfer(MultibancoCreditTransferSourceRequest),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AchCreditTransferSourceRequest {
#[serde(rename = "type")]
pub transfer_type: StripeCreditTransferTypes,
#[serde(flatten)]
pub payment_method_data: AchTransferData,
pub currency: common_enums::Currency,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct MultibancoCreditTransferSourceRequest {
#[serde(rename = "type")]
pub transfer_type: StripeCreditTransferTypes,
#[serde(flatten)]
pub payment_method_data: MultibancoTransferData,
pub currency: common_enums::Currency,
pub amount: Option<MinorUnit>,
#[serde(rename = "redirect[return_url]")]
pub return_url: Option<String>,
}
// Remove untagged when Deserialize is added
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripePaymentMethodData<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
CardToken(StripeCardToken),
Card(StripeCardData<T>),
PayLater(StripePayLaterData),
Wallet(StripeWallet),
BankRedirect(StripeBankRedirectData),
BankDebit(StripeBankDebitData),
BankTransfer(StripeBankTransferData),
}
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize)]
pub struct StripeBillingAddressCardToken {
#[serde(rename = "billing_details[name]")]
pub name: Option<Secret<String>>,
#[serde(rename = "billing_details[email]")]
pub email: Option<Email>,
#[serde(rename = "billing_details[phone]")]
pub phone: Option<Secret<String>>,
#[serde(rename = "billing_details[address][line1]")]
pub address_line1: Option<Secret<String>>,
#[serde(rename = "billing_details[address][line2]")]
pub address_line2: Option<Secret<String>>,
#[serde(rename = "billing_details[address][state]")]
pub state: Option<Secret<String>>,
#[serde(rename = "billing_details[address][city]")]
pub city: Option<String>,
}
// Struct to call the Stripe tokens API to create a PSP token for the card details provided
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeCardToken {
#[serde(rename = "type")]
pub payment_method_type: Option<StripePaymentMethodType>,
#[serde(rename = "card[number]")]
pub token_card_number: cards::CardNumber,
#[serde(rename = "card[exp_month]")]
pub token_card_exp_month: Secret<String>,
#[serde(rename = "card[exp_year]")]
pub token_card_exp_year: Secret<String>,
#[serde(rename = "card[cvc]")]
pub token_card_cvc: Secret<String>,
#[serde(flatten)]
pub billing: StripeBillingAddressCardToken,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "payment_method_data[type]")]
pub enum BankDebitData {
#[serde(rename = "us_bank_account")]
Ach {
#[serde(rename = "payment_method_data[us_bank_account][account_holder_type]")]
account_holder_type: String,
#[serde(rename = "payment_method_data[us_bank_account][account_number]")]
account_number: Secret<String>,
#[serde(rename = "payment_method_data[us_bank_account][routing_number]")]
routing_number: Secret<String>,
},
#[serde(rename = "sepa_debit")]
Sepa {
#[serde(rename = "payment_method_data[sepa_debit][iban]")]
iban: Secret<String>,
},
#[serde(rename = "au_becs_debit")]
Becs {
| {
"chunk": 4,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
#[serde(rename = "payment_method_data[au_becs_debit][account_number]")]
account_number: Secret<String>,
#[serde(rename = "payment_method_data[au_becs_debit][bsb_number]")]
bsb_number: Secret<String>,
},
#[serde(rename = "bacs_debit")]
Bacs {
#[serde(rename = "payment_method_data[bacs_debit][account_number]")]
account_number: Secret<String>,
#[serde(rename = "payment_method_data[bacs_debit][sort_code]")]
sort_code: Secret<String>,
},
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeBankDebitData {
#[serde(flatten)]
pub bank_specific_data: BankDebitData,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct BankTransferData {
pub email: Email,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeBankTransferData {
AchBankTransfer(Box<AchTransferData>),
SepaBankTransfer(Box<SepaBankTransferData>),
BacsBankTransfers(Box<BacsBankTransferData>),
MultibancoBankTransfers(Box<MultibancoTransferData>),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeWallet {
ApplepayToken(StripeApplePay),
GooglepayToken(GooglePayToken),
ApplepayPayment(ApplepayPayment),
AmazonpayPayment(AmazonpayPayment),
WechatpayPayment(WechatpayPayment),
AlipayPayment(AlipayPayment),
Cashapp(CashappPayment),
RevolutPay(RevolutpayPayment),
ApplePayPredecryptToken(Box<StripeApplePayPredecrypt>),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeApplePayPredecrypt {
#[serde(rename = "card[number]")]
number: cards::CardNumber,
#[serde(rename = "card[exp_year]")]
exp_year: Secret<String>,
#[serde(rename = "card[exp_month]")]
exp_month: Secret<String>,
#[serde(rename = "card[cryptogram]")]
cryptogram: Secret<String>,
#[serde(rename = "card[eci]")]
eci: Option<String>,
#[serde(rename = "card[tokenization_method]")]
tokenization_method: String,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeApplePay {
pub pk_token: Secret<String>,
pub pk_token_instrument_name: String,
pub pk_token_payment_network: String,
pub pk_token_transaction_id: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct GooglePayToken {
#[serde(rename = "payment_method_data[type]")]
pub payment_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[card][token]")]
pub token: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ApplepayPayment {
#[serde(rename = "payment_method_data[card][token]")]
pub token: Secret<String>,
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AmazonpayPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct RevolutpayPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AlipayPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct CashappPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct WechatpayPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[wechat_pay][client]")]
pub client: WechatClient,
}
#[derive(Debug, Eq, PartialEq, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum WechatClient {
Web,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct GooglepayPayment {
#[serde(rename = "payment_method_data[card][token]")]
pub token: Secret<String>,
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
// All supported payment_method_types in stripe
// This enum goes in payment_method_types[] field in stripe request body
// https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_types
| {
"chunk": 5,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
#[derive(Eq, PartialEq, Serialize, Clone, Debug, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodType {
Affirm,
AfterpayClearpay,
Alipay,
#[serde(rename = "amazon_pay")]
AmazonPay,
#[serde(rename = "au_becs_debit")]
Becs,
#[serde(rename = "bacs_debit")]
Bacs,
Bancontact,
Blik,
Card,
CustomerBalance,
Eps,
Giropay,
Ideal,
Klarna,
#[serde(rename = "p24")]
Przelewy24,
#[serde(rename = "sepa_debit")]
Sepa,
Sofort,
#[serde(rename = "us_bank_account")]
Ach,
#[serde(rename = "wechat_pay")]
Wechatpay,
#[serde(rename = "cashapp")]
Cashapp,
RevolutPay,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[allow(dead_code)]
pub enum StripeCreditTransferTypes {
#[serde(rename = "us_bank_transfer")]
AchCreditTransfer,
Multibanco,
Blik,
}
impl TryFrom<common_enums::PaymentMethodType> for StripePaymentMethodType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: common_enums::PaymentMethodType) -> Result<Self, Self::Error> {
match value {
common_enums::PaymentMethodType::Credit => Ok(Self::Card),
common_enums::PaymentMethodType::Debit => Ok(Self::Card),
common_enums::PaymentMethodType::Klarna => Ok(Self::Klarna),
common_enums::PaymentMethodType::Affirm => Ok(Self::Affirm),
common_enums::PaymentMethodType::AfterpayClearpay => Ok(Self::AfterpayClearpay),
common_enums::PaymentMethodType::Eps => Ok(Self::Eps),
common_enums::PaymentMethodType::Giropay => Ok(Self::Giropay),
common_enums::PaymentMethodType::Ideal => Ok(Self::Ideal),
common_enums::PaymentMethodType::Sofort => Ok(Self::Sofort),
common_enums::PaymentMethodType::AmazonPay => Ok(Self::AmazonPay),
common_enums::PaymentMethodType::ApplePay => Ok(Self::Card),
common_enums::PaymentMethodType::Ach => Ok(Self::Ach),
common_enums::PaymentMethodType::Sepa => Ok(Self::Sepa),
common_enums::PaymentMethodType::Becs => Ok(Self::Becs),
common_enums::PaymentMethodType::Bacs => Ok(Self::Bacs),
common_enums::PaymentMethodType::BancontactCard => Ok(Self::Bancontact),
common_enums::PaymentMethodType::WeChatPay => Ok(Self::Wechatpay),
common_enums::PaymentMethodType::Blik => Ok(Self::Blik),
common_enums::PaymentMethodType::AliPay => Ok(Self::Alipay),
common_enums::PaymentMethodType::Przelewy24 => Ok(Self::Przelewy24),
common_enums::PaymentMethodType::RevolutPay => Ok(Self::RevolutPay),
// Stripe expects PMT as Card for Recurring Mandates Payments
common_enums::PaymentMethodType::GooglePay => Ok(Self::Card),
common_enums::PaymentMethodType::Boleto
| common_enums::PaymentMethodType::CardRedirect
| common_enums::PaymentMethodType::CryptoCurrency
| common_enums::PaymentMethodType::Multibanco
| common_enums::PaymentMethodType::OnlineBankingFpx
| common_enums::PaymentMethodType::Paypal
| common_enums::PaymentMethodType::Pix
| common_enums::PaymentMethodType::UpiCollect
| common_enums::PaymentMethodType::UpiIntent
| common_enums::PaymentMethodType::Cashapp
| common_enums::PaymentMethodType::Bluecode
| common_enums::PaymentMethodType::Oxxo => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
common_enums::PaymentMethodType::AliPayHk
| common_enums::PaymentMethodType::Atome
| common_enums::PaymentMethodType::Bizum
| common_enums::PaymentMethodType::Alma
| common_enums::PaymentMethodType::ClassicReward
| common_enums::PaymentMethodType::Dana
| common_enums::PaymentMethodType::DirectCarrierBilling
| common_enums::PaymentMethodType::Efecty
| common_enums::PaymentMethodType::Eft
| common_enums::PaymentMethodType::Evoucher
| common_enums::PaymentMethodType::GoPay
| {
"chunk": 6,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
| common_enums::PaymentMethodType::Gcash
| common_enums::PaymentMethodType::Interac
| common_enums::PaymentMethodType::KakaoPay
| common_enums::PaymentMethodType::LocalBankRedirect
| common_enums::PaymentMethodType::MbWay
| common_enums::PaymentMethodType::MobilePay
| common_enums::PaymentMethodType::Momo
| common_enums::PaymentMethodType::MomoAtm
| common_enums::PaymentMethodType::OnlineBankingThailand
| common_enums::PaymentMethodType::OnlineBankingCzechRepublic
| common_enums::PaymentMethodType::OnlineBankingFinland
| common_enums::PaymentMethodType::OnlineBankingPoland
| common_enums::PaymentMethodType::OnlineBankingSlovakia
| common_enums::PaymentMethodType::OpenBankingUk
| common_enums::PaymentMethodType::OpenBankingPIS
| common_enums::PaymentMethodType::PagoEfectivo
| common_enums::PaymentMethodType::PayBright
| common_enums::PaymentMethodType::Pse
| common_enums::PaymentMethodType::RedCompra
| common_enums::PaymentMethodType::RedPagos
| common_enums::PaymentMethodType::SamsungPay
| common_enums::PaymentMethodType::Swish
| common_enums::PaymentMethodType::TouchNGo
| common_enums::PaymentMethodType::Trustly
| common_enums::PaymentMethodType::Twint
| common_enums::PaymentMethodType::Vipps
| common_enums::PaymentMethodType::Venmo
| common_enums::PaymentMethodType::Alfamart
| common_enums::PaymentMethodType::BcaBankTransfer
| common_enums::PaymentMethodType::BniVa
| common_enums::PaymentMethodType::CimbVa
| common_enums::PaymentMethodType::BriVa
| common_enums::PaymentMethodType::DanamonVa
| common_enums::PaymentMethodType::Indomaret
| common_enums::PaymentMethodType::MandiriVa
| common_enums::PaymentMethodType::PermataBankTransfer
| common_enums::PaymentMethodType::PaySafeCard
| common_enums::PaymentMethodType::Paze
| common_enums::PaymentMethodType::Givex
| common_enums::PaymentMethodType::Benefit
| common_enums::PaymentMethodType::Knet
| common_enums::PaymentMethodType::SevenEleven
| common_enums::PaymentMethodType::Lawson
| common_enums::PaymentMethodType::MiniStop
| common_enums::PaymentMethodType::FamilyMart
| common_enums::PaymentMethodType::Seicomart
| common_enums::PaymentMethodType::PayEasy
| common_enums::PaymentMethodType::LocalBankTransfer
| common_enums::PaymentMethodType::InstantBankTransfer
| common_enums::PaymentMethodType::InstantBankTransferFinland
| common_enums::PaymentMethodType::InstantBankTransferPoland
| common_enums::PaymentMethodType::SepaBankTransfer
| common_enums::PaymentMethodType::Walley
| common_enums::PaymentMethodType::Fps
| common_enums::PaymentMethodType::DuitNow
| common_enums::PaymentMethodType::PromptPay
| common_enums::PaymentMethodType::VietQr
| common_enums::PaymentMethodType::Mifinity => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
}
}
}
#[derive(Debug, Eq, PartialEq, Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum BankTransferType {
GbBankTransfer,
EuBankTransfer,
#[serde(rename = "bank_transfer")]
BankTransfers,
}
#[derive(Debug, Eq, PartialEq, Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripeBankNames {
AbnAmro,
ArzteUndApothekerBank,
AsnBank,
AustrianAnadiBankAg,
BankAustria,
BankhausCarlSpangler,
BankhausSchelhammerUndSchatteraAg,
BawagPskAg,
BksBankAg,
BrullKallmusBankAg,
BtvVierLanderBank,
Bunq,
CapitalBankGraweGruppeAg,
CitiHandlowy,
Dolomitenbank,
EasybankAg,
ErsteBankUndSparkassen,
Handelsbanken,
HypoAlpeadriabankInternationalAg,
HypoNoeLbFurNiederosterreichUWien,
| {
"chunk": 7,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
HypoOberosterreichSalzburgSteiermark,
HypoTirolBankAg,
HypoVorarlbergBankAg,
HypoBankBurgenlandAktiengesellschaft,
Ing,
Knab,
MarchfelderBank,
OberbankAg,
RaiffeisenBankengruppeOsterreich,
SchoellerbankAg,
SpardaBankWien,
VolksbankGruppe,
VolkskreditbankAg,
VrBankBraunau,
Moneyou,
Rabobank,
Regiobank,
Revolut,
SnsBank,
TriodosBank,
VanLanschot,
PlusBank,
EtransferPocztowy24,
BankiSpbdzielcze,
BankNowyBfgSa,
GetinBank,
Blik,
NoblePay,
#[serde(rename = "ideabank")]
IdeaBank,
#[serde(rename = "envelobank")]
EnveloBank,
NestPrzelew,
MbankMtransfer,
Inteligo,
PbacZIpko,
BnpParibas,
BankPekaoSa,
VolkswagenBank,
AliorBank,
Boz,
}
impl TryFrom<&common_enums::BankNames> for StripeBankNames {
type Error = ConnectorError;
fn try_from(bank: &common_enums::BankNames) -> Result<Self, Self::Error> {
Ok(match bank {
common_enums::BankNames::AbnAmro => Self::AbnAmro,
common_enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank,
common_enums::BankNames::AsnBank => Self::AsnBank,
common_enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg,
common_enums::BankNames::BankAustria => Self::BankAustria,
common_enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler,
common_enums::BankNames::BankhausSchelhammerUndSchatteraAg => {
Self::BankhausSchelhammerUndSchatteraAg
}
common_enums::BankNames::BawagPskAg => Self::BawagPskAg,
common_enums::BankNames::BksBankAg => Self::BksBankAg,
common_enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg,
common_enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank,
common_enums::BankNames::Bunq => Self::Bunq,
common_enums::BankNames::CapitalBankGraweGruppeAg => Self::CapitalBankGraweGruppeAg,
common_enums::BankNames::Citi => Self::CitiHandlowy,
common_enums::BankNames::Dolomitenbank => Self::Dolomitenbank,
common_enums::BankNames::EasybankAg => Self::EasybankAg,
common_enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen,
common_enums::BankNames::Handelsbanken => Self::Handelsbanken,
common_enums::BankNames::HypoAlpeadriabankInternationalAg => {
Self::HypoAlpeadriabankInternationalAg
}
common_enums::BankNames::HypoNoeLbFurNiederosterreichUWien => {
Self::HypoNoeLbFurNiederosterreichUWien
}
common_enums::BankNames::HypoOberosterreichSalzburgSteiermark => {
Self::HypoOberosterreichSalzburgSteiermark
}
common_enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg,
common_enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg,
common_enums::BankNames::HypoBankBurgenlandAktiengesellschaft => {
Self::HypoBankBurgenlandAktiengesellschaft
}
common_enums::BankNames::Ing => Self::Ing,
common_enums::BankNames::Knab => Self::Knab,
common_enums::BankNames::MarchfelderBank => Self::MarchfelderBank,
common_enums::BankNames::OberbankAg => Self::OberbankAg,
common_enums::BankNames::RaiffeisenBankengruppeOsterreich => {
Self::RaiffeisenBankengruppeOsterreich
}
common_enums::BankNames::Rabobank => Self::Rabobank,
common_enums::BankNames::Regiobank => Self::Regiobank,
common_enums::BankNames::Revolut => Self::Revolut,
common_enums::BankNames::SnsBank => Self::SnsBank,
common_enums::BankNames::TriodosBank => Self::TriodosBank,
common_enums::BankNames::VanLanschot => Self::VanLanschot,
common_enums::BankNames::Moneyou => Self::Moneyou,
common_enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg,
common_enums::BankNames::SpardaBankWien => Self::SpardaBankWien,
common_enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe,
| {
"chunk": 8,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_9 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
common_enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg,
common_enums::BankNames::VrBankBraunau => Self::VrBankBraunau,
common_enums::BankNames::PlusBank => Self::PlusBank,
common_enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24,
common_enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze,
common_enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa,
common_enums::BankNames::GetinBank => Self::GetinBank,
common_enums::BankNames::Blik => Self::Blik,
common_enums::BankNames::NoblePay => Self::NoblePay,
common_enums::BankNames::IdeaBank => Self::IdeaBank,
common_enums::BankNames::EnveloBank => Self::EnveloBank,
common_enums::BankNames::NestPrzelew => Self::NestPrzelew,
common_enums::BankNames::MbankMtransfer => Self::MbankMtransfer,
common_enums::BankNames::Inteligo => Self::Inteligo,
common_enums::BankNames::PbacZIpko => Self::PbacZIpko,
common_enums::BankNames::BnpParibas => Self::BnpParibas,
common_enums::BankNames::BankPekaoSa => Self::BankPekaoSa,
common_enums::BankNames::VolkswagenBank => Self::VolkswagenBank,
common_enums::BankNames::AliorBank => Self::AliorBank,
common_enums::BankNames::Boz => Self::Boz,
_ => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
))?,
})
}
}
fn validate_shipping_address_against_payment_method(
shipping_address: &Option<StripeShippingAddress>,
payment_method: Option<&StripePaymentMethodType>,
) -> Result<(), error_stack::Report<ConnectorError>> {
match payment_method {
Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address {
Some(address) => {
let missing_fields = collect_missing_value_keys!(
("shipping.address.line1", address.line1),
("shipping.address.country", address.country),
("shipping.address.zip", address.zip)
);
if !missing_fields.is_empty() {
return Err(ConnectorError::MissingRequiredFields {
field_names: missing_fields,
}
.into());
}
Ok(())
}
None => Err(ConnectorError::MissingRequiredField {
field_name: "shipping.address",
}
.into()),
},
_ => Ok(()),
}
}
impl TryFrom<&PayLaterData> for StripePaymentMethodType {
type Error = ConnectorError;
fn try_from(pay_later_data: &PayLaterData) -> Result<Self, Self::Error> {
match pay_later_data {
PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna),
PayLaterData::AffirmRedirect {} => Ok(Self::Affirm),
PayLaterData::AfterpayClearpayRedirect { .. } => Ok(Self::AfterpayClearpay),
PayLaterData::KlarnaSdk { .. }
| PayLaterData::PayBrightRedirect {}
| PayLaterData::WalleyRedirect {}
| PayLaterData::AlmaRedirect {}
| PayLaterData::AtomeRedirect {} => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)),
}
}
}
impl TryFrom<&BankRedirectData> for StripePaymentMethodType {
type Error = ConnectorError;
fn try_from(bank_redirect_data: &BankRedirectData) -> Result<Self, Self::Error> {
match bank_redirect_data {
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24),
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Blik { .. } => Ok(Self::Blik),
BankRedirectData::OnlineBankingFpx { .. } => Err(ConnectorError::NotImplemented(
| {
"chunk": 9,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_10 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
get_unimplemented_payment_method_error_message("stripe"),
)),
BankRedirectData::Bizum {}
| BankRedirectData::Interac { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::LocalBankRedirect {} => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)),
}
}
}
fn get_stripe_payment_method_type_from_wallet_data(
wallet_data: &WalletData,
) -> Result<Option<StripePaymentMethodType>, ConnectorError> {
match wallet_data {
WalletData::AliPayRedirect(_) => Ok(Some(StripePaymentMethodType::Alipay)),
WalletData::ApplePay(_) => Ok(None),
WalletData::GooglePay(_) => Ok(Some(StripePaymentMethodType::Card)),
WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)),
WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)),
WalletData::AmazonPayRedirect(_) => Ok(Some(StripePaymentMethodType::AmazonPay)),
WalletData::RevolutPay(_) => Ok(Some(StripePaymentMethodType::RevolutPay)),
WalletData::MobilePayRedirect(_) => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)),
WalletData::PaypalRedirect(_)
| WalletData::AliPayQr(_)
| WalletData::BluecodeRedirect {}
| WalletData::AliPayHkRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::Mifinity(_) => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)),
}
}
impl From<&payment_method_data::BankDebitData> for StripePaymentMethodType {
fn from(bank_debit_data: &payment_method_data::BankDebitData) -> Self {
match bank_debit_data {
payment_method_data::BankDebitData::AchBankDebit { .. } => Self::Ach,
payment_method_data::BankDebitData::SepaBankDebit { .. } => Self::Sepa,
payment_method_data::BankDebitData::BecsBankDebit { .. } => Self::Becs,
payment_method_data::BankDebitData::BacsBankDebit { .. } => Self::Bacs,
}
}
}
fn get_bank_debit_data(
bank_debit_data: &payment_method_data::BankDebitData,
) -> (StripePaymentMethodType, BankDebitData) {
match bank_debit_data {
payment_method_data::BankDebitData::AchBankDebit {
account_number,
routing_number,
..
} => {
let ach_data = BankDebitData::Ach {
account_holder_type: "individual".to_string(),
account_number: account_number.to_owned(),
routing_number: routing_number.to_owned(),
};
(StripePaymentMethodType::Ach, ach_data)
}
payment_method_data::BankDebitData::SepaBankDebit { iban, .. } => {
let sepa_data: BankDebitData = BankDebitData::Sepa {
iban: iban.to_owned(),
};
(StripePaymentMethodType::Sepa, sepa_data)
}
payment_method_data::BankDebitData::BecsBankDebit {
account_number,
bsb_number,
..
} => {
let becs_data = BankDebitData::Becs {
| {
"chunk": 10,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_11 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
account_number: account_number.to_owned(),
bsb_number: bsb_number.to_owned(),
};
(StripePaymentMethodType::Becs, becs_data)
}
payment_method_data::BankDebitData::BacsBankDebit {
account_number,
sort_code,
..
} => {
let bacs_data = BankDebitData::Bacs {
account_number: account_number.to_owned(),
sort_code: Secret::new(sort_code.clone().expose().replace('-', "")),
};
(StripePaymentMethodType::Bacs, bacs_data)
}
}
}
pub struct PaymentRequestDetails {
pub auth_type: common_enums::AuthenticationType,
pub payment_method_token: Option<domain_types::router_data::PaymentMethodToken>,
pub is_customer_initiated_mandate_payment: Option<bool>,
pub billing_address: StripeBillingAddress,
pub request_incremental_authorization: bool,
pub request_extended_authorization: Option<bool>,
pub request_overcapture: Option<StripeRequestOvercaptureBool>,
}
fn create_stripe_payment_method<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
payment_method_data: &PaymentMethodData<T>,
payment_request_details: PaymentRequestDetails,
) -> Result<
(
StripePaymentMethodData<T>,
Option<StripePaymentMethodType>,
StripeBillingAddress,
),
error_stack::Report<ConnectorError>,
> {
match payment_method_data {
PaymentMethodData::Card(card_details) => {
let payment_method_auth_type = match payment_request_details.auth_type {
common_enums::AuthenticationType::ThreeDs => Auth3ds::Any,
common_enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic,
};
Ok((
StripePaymentMethodData::try_from((
card_details,
payment_method_auth_type,
payment_request_details.request_incremental_authorization,
payment_request_details.request_extended_authorization,
payment_request_details.request_overcapture,
))?,
Some(StripePaymentMethodType::Card),
payment_request_details.billing_address,
))
}
PaymentMethodData::PayLater(pay_later_data) => {
let stripe_pm_type = StripePaymentMethodType::try_from(pay_later_data)?;
Ok((
StripePaymentMethodData::PayLater(StripePayLaterData {
payment_method_data_type: stripe_pm_type,
}),
Some(stripe_pm_type),
payment_request_details.billing_address,
))
}
PaymentMethodData::BankRedirect(bank_redirect_data) => {
let billing_address =
if payment_request_details.is_customer_initiated_mandate_payment == Some(true) {
mandatory_parameters_for_sepa_bank_debit_mandates(
&Some(payment_request_details.billing_address.to_owned()),
payment_request_details.is_customer_initiated_mandate_payment,
)?
} else {
payment_request_details.billing_address
};
let pm_type = StripePaymentMethodType::try_from(bank_redirect_data)?;
let bank_redirect_data = StripePaymentMethodData::try_from(bank_redirect_data)?;
Ok((bank_redirect_data, Some(pm_type), billing_address))
}
PaymentMethodData::Wallet(wallet_data) => {
let pm_type = get_stripe_payment_method_type_from_wallet_data(wallet_data)?;
let wallet_specific_data = StripePaymentMethodData::try_from((
wallet_data,
payment_request_details.payment_method_token,
))?;
Ok((
wallet_specific_data,
pm_type,
StripeBillingAddress::default(),
))
}
PaymentMethodData::BankDebit(bank_debit_data) => {
let (pm_type, bank_debit_data) = get_bank_debit_data(bank_debit_data);
| {
"chunk": 11,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_12 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
let pm_data = StripePaymentMethodData::BankDebit(StripeBankDebitData {
bank_specific_data: bank_debit_data,
});
Ok((
pm_data,
Some(pm_type),
payment_request_details.billing_address,
))
}
PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data.deref() {
payment_method_data::BankTransferData::AchBankTransfer {} => Ok((
StripePaymentMethodData::BankTransfer(StripeBankTransferData::AchBankTransfer(
Box::new(AchTransferData {
payment_method_data_type: StripePaymentMethodType::CustomerBalance,
bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer,
payment_method_type: StripePaymentMethodType::CustomerBalance,
balance_funding_type: BankTransferType::BankTransfers,
}),
)),
None,
StripeBillingAddress::default(),
)),
payment_method_data::BankTransferData::MultibancoBankTransfer {} => Ok((
StripePaymentMethodData::BankTransfer(
StripeBankTransferData::MultibancoBankTransfers(Box::new(
MultibancoTransferData {
payment_method_data_type: StripeCreditTransferTypes::Multibanco,
payment_method_type: StripeCreditTransferTypes::Multibanco,
email: payment_request_details.billing_address.email.ok_or(
ConnectorError::MissingRequiredField {
field_name: "billing_address.email",
},
)?,
},
)),
),
None,
StripeBillingAddress::default(),
)),
payment_method_data::BankTransferData::SepaBankTransfer {} => Ok((
StripePaymentMethodData::BankTransfer(StripeBankTransferData::SepaBankTransfer(
Box::new(SepaBankTransferData {
payment_method_data_type: StripePaymentMethodType::CustomerBalance,
bank_transfer_type: BankTransferType::EuBankTransfer,
balance_funding_type: BankTransferType::BankTransfers,
payment_method_type: StripePaymentMethodType::CustomerBalance,
country: payment_request_details.billing_address.country.ok_or(
ConnectorError::MissingRequiredField {
field_name: "billing_address.country",
},
)?,
}),
)),
Some(StripePaymentMethodType::CustomerBalance),
payment_request_details.billing_address,
)),
payment_method_data::BankTransferData::BacsBankTransfer {} => Ok((
StripePaymentMethodData::BankTransfer(StripeBankTransferData::BacsBankTransfers(
Box::new(BacsBankTransferData {
payment_method_data_type: StripePaymentMethodType::CustomerBalance,
bank_transfer_type: BankTransferType::GbBankTransfer,
balance_funding_type: BankTransferType::BankTransfers,
payment_method_type: StripePaymentMethodType::CustomerBalance,
}),
)),
Some(StripePaymentMethodType::CustomerBalance),
payment_request_details.billing_address,
)),
payment_method_data::BankTransferData::Pix { .. } => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
"stripe",
))
.into(),
),
payment_method_data::BankTransferData::Pse {}
| payment_method_data::BankTransferData::LocalBankTransfer { .. }
| payment_method_data::BankTransferData::InstantBankTransfer {}
| {
"chunk": 12,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_13 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
| payment_method_data::BankTransferData::InstantBankTransferFinland { .. }
| payment_method_data::BankTransferData::InstantBankTransferPoland { .. }
| payment_method_data::BankTransferData::PermataBankTransfer { .. }
| payment_method_data::BankTransferData::BcaBankTransfer { .. }
| payment_method_data::BankTransferData::BniVaBankTransfer { .. }
| payment_method_data::BankTransferData::BriVaBankTransfer { .. }
| payment_method_data::BankTransferData::CimbVaBankTransfer { .. }
| payment_method_data::BankTransferData::DanamonVaBankTransfer { .. }
| payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
"stripe",
))
.into(),
),
},
PaymentMethodData::Crypto(_) => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() {
GiftCardData::Givex(_) | GiftCardData::PaySafeCard {} => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
"stripe",
))
.into(),
),
},
PaymentMethodData::CardRedirect(cardredirect_data) => match cardredirect_data {
CardRedirectData::Knet {}
| CardRedirectData::Benefit {}
| CardRedirectData::MomoAtm {}
| CardRedirectData::CardRedirect {} => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
},
PaymentMethodData::Reward => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
PaymentMethodData::Voucher(voucher_data) => match voucher_data {
VoucherData::Boleto(_) | VoucherData::Oxxo => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
VoucherData::Alfamart(_)
| VoucherData::Efecty
| VoucherData::PagoEfectivo
| VoucherData::RedCompra
| VoucherData::RedPagos
| VoucherData::Indomaret(_)
| VoucherData::SevenEleven(_)
| VoucherData::Lawson(_)
| VoucherData::MiniStop(_)
| VoucherData::FamilyMart(_)
| VoucherData::Seicomart(_)
| VoucherData::PayEasy(_) => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
},
PaymentMethodData::Upi(_)
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
"stripe",
))
.into(),
),
}
}
fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option<StripeCardNetwork> {
match card_network {
common_enums::CardNetwork::Visa => Some(StripeCardNetwork::Visa),
common_enums::CardNetwork::Mastercard => Some(StripeCardNetwork::Mastercard),
common_enums::CardNetwork::CartesBancaires => Some(StripeCardNetwork::CartesBancaires),
common_enums::CardNetwork::AmericanExpress
| common_enums::CardNetwork::JCB
| common_enums::CardNetwork::DinersClub
| common_enums::CardNetwork::Discover
| common_enums::CardNetwork::UnionPay
| common_enums::CardNetwork::Interac
| common_enums::CardNetwork::RuPay
| common_enums::CardNetwork::Maestro
| common_enums::CardNetwork::Star
| {
"chunk": 13,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_14 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
| common_enums::CardNetwork::Accel
| common_enums::CardNetwork::Pulse
| common_enums::CardNetwork::Nyce => None,
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&Card<T>,
Auth3ds,
bool,
Option<bool>,
Option<StripeRequestOvercaptureBool>,
)> for StripePaymentMethodData<T>
{
type Error = ConnectorError;
fn try_from(
(
card,
payment_method_auth_type,
request_incremental_authorization,
request_extended_authorization,
request_overcapture,
): (
&Card<T>,
Auth3ds,
bool,
Option<bool>,
Option<StripeRequestOvercaptureBool>,
),
) -> Result<Self, Self::Error> {
Ok(Self::Card(StripeCardData {
payment_method_data_type: StripePaymentMethodType::Card,
payment_method_data_card_number: card.card_number.clone(),
payment_method_data_card_exp_month: card.card_exp_month.clone(),
payment_method_data_card_exp_year: card.card_exp_year.clone(),
payment_method_data_card_cvc: Some(card.card_cvc.clone()),
payment_method_auth_type: Some(payment_method_auth_type),
payment_method_data_card_preferred_network: card
.card_network
.clone()
.and_then(get_stripe_card_network),
request_incremental_authorization: if request_incremental_authorization {
Some(StripeRequestIncrementalAuthorization::IfAvailable)
} else {
None
},
request_extended_authorization: if request_extended_authorization.unwrap_or(false) {
Some(StripeRequestExtendedAuthorization::IfAvailable)
} else {
None
},
request_overcapture,
}))
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&WalletData,
Option<domain_types::router_data::PaymentMethodToken>,
)> for StripePaymentMethodData<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(wallet_data, _payment_method_token): (
&WalletData,
Option<domain_types::router_data::PaymentMethodToken>,
),
) -> Result<Self, Self::Error> {
match wallet_data {
WalletData::WeChatPayQr(_) => Ok(Self::Wallet(StripeWallet::WechatpayPayment(
WechatpayPayment {
client: WechatClient::Web,
payment_method_data_type: StripePaymentMethodType::Wechatpay,
},
))),
WalletData::AliPayRedirect(_) => {
Ok(Self::Wallet(StripeWallet::AlipayPayment(AlipayPayment {
payment_method_data_type: StripePaymentMethodType::Alipay,
})))
}
WalletData::CashappQr(_) => Ok(Self::Wallet(StripeWallet::Cashapp(CashappPayment {
payment_method_data_type: StripePaymentMethodType::Cashapp,
}))),
WalletData::AmazonPayRedirect(_) => Ok(Self::Wallet(StripeWallet::AmazonpayPayment(
AmazonpayPayment {
payment_method_types: StripePaymentMethodType::AmazonPay,
},
))),
WalletData::RevolutPay(_) => {
Ok(Self::Wallet(StripeWallet::RevolutPay(RevolutpayPayment {
payment_method_types: StripePaymentMethodType::RevolutPay,
})))
}
WalletData::GooglePay(gpay_data) => Ok(Self::try_from(gpay_data)?),
WalletData::PaypalRedirect(_) | WalletData::MobilePayRedirect(_) => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
"stripe",
))
.into(),
),
WalletData::AliPayQr(_)
| WalletData::ApplePay(_)
| WalletData::BluecodeRedirect {}
| {
"chunk": 14,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_15 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
| WalletData::AliPayHkRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::Mifinity(_) => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<&BankRedirectData> for StripePaymentMethodData<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(bank_redirect_data: &BankRedirectData) -> Result<Self, Self::Error> {
let payment_method_data_type = StripePaymentMethodType::try_from(bank_redirect_data)?;
match bank_redirect_data {
BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeBancontactCard(Box::new(StripeBancontactCard {
payment_method_data_type,
})),
)),
BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeBlik(Box::new(StripeBlik {
payment_method_data_type,
code: Secret::new(blik_code.clone().ok_or(
ConnectorError::MissingRequiredField {
field_name: "blik_code",
},
)?),
})),
)),
BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeEps(Box::new(StripeEps {
payment_method_data_type,
bank_name: bank_name
.map(|bank_name| StripeBankNames::try_from(&bank_name))
.transpose()?,
})),
)),
BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeGiropay(Box::new(StripeGiropay {
payment_method_data_type,
})),
)),
BankRedirectData::Ideal { bank_name, .. } => {
let bank_name = bank_name
.map(|bank_name| StripeBankNames::try_from(&bank_name))
.transpose()?;
Ok(Self::BankRedirect(StripeBankRedirectData::StripeIdeal(
Box::new(StripeIdeal {
payment_method_data_type,
ideal_bank_name: bank_name,
}),
)))
}
BankRedirectData::Przelewy24 { bank_name, .. } => {
let bank_name = bank_name
.map(|bank_name| StripeBankNames::try_from(&bank_name))
.transpose()?;
Ok(Self::BankRedirect(
StripeBankRedirectData::StripePrezelewy24(Box::new(StripePrezelewy24 {
payment_method_data_type,
bank_name,
})),
))
}
BankRedirectData::OnlineBankingFpx { .. } => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
BankRedirectData::Bizum {}
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| {
"chunk": 15,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_16 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::LocalBankRedirect {} => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<&GooglePayWalletData> for StripePaymentMethodData<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(gpay_data: &GooglePayWalletData) -> Result<Self, Self::Error> {
Ok(Self::Wallet(StripeWallet::GooglepayToken(GooglePayToken {
token: Secret::new(
gpay_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.as_bytes()
.parse_struct::<StripeGpayToken>("StripeGpayToken")
.change_context(ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
})?
.id,
),
payment_type: StripePaymentMethodType::Card,
})))
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
StripeRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for PaymentIntentRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
value: StripeRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let item = value.router_data;
let (transfer_account_id, charge_type, application_fees) = (None, None, None);
let payment_method_token = match &item.request.split_payments {
Some(domain_types::connector_types::SplitPaymentsRequest::StripeSplitPayment(_)) => {
match item.resource_common_data.payment_method_token.clone() {
Some(domain_types::router_data::PaymentMethodToken::Token(secret)) => {
Some(secret)
}
_ => None,
}
}
_ => None,
};
let amount =
StripeAmountConvertor::convert(item.request.minor_amount, item.request.currency)?;
let order_id = item
.resource_common_data
.connector_request_reference_id
.clone();
let shipping_address = if payment_method_token.is_some() {
None
} else {
Some(StripeShippingAddress {
city: item.resource_common_data.get_optional_shipping_city(),
country: item.resource_common_data.get_optional_shipping_country(),
line1: item.resource_common_data.get_optional_shipping_line1(),
line2: item.resource_common_data.get_optional_shipping_line2(),
zip: item.resource_common_data.get_optional_shipping_zip(),
state: item.resource_common_data.get_optional_shipping_state(),
name: item.resource_common_data.get_optional_shipping_full_name(),
phone: item
.resource_common_data
.get_optional_shipping_phone_number(),
})
};
let billing_address = if payment_method_token.is_some() {
None
} else {
Some(StripeBillingAddress {
| {
"chunk": 16,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_17 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
city: item.resource_common_data.get_optional_billing_city(),
country: item.resource_common_data.get_optional_billing_country(),
address_line1: item.resource_common_data.get_optional_billing_line1(),
address_line2: item.resource_common_data.get_optional_billing_line2(),
zip_code: item.resource_common_data.get_optional_billing_zip(),
state: item.resource_common_data.get_optional_billing_state(),
name: item.resource_common_data.get_optional_billing_full_name(),
email: item.resource_common_data.get_optional_billing_email(),
phone: item
.resource_common_data
.get_optional_billing_phone_number(),
})
};
let payment_method_options = None;
let (
mut payment_data,
payment_method,
billing_address,
payment_method_types,
setup_future_usage,
) = if payment_method_token.is_some() {
(None, None, StripeBillingAddress::default(), None, None)
} else {
let (payment_method_data, payment_method_type, billing_address) =
create_stripe_payment_method(
&item.request.payment_method_data,
PaymentRequestDetails {
auth_type: item.resource_common_data.auth_type,
payment_method_token: item
.resource_common_data
.payment_method_token
.clone(),
is_customer_initiated_mandate_payment: Some(
PaymentsAuthorizeData::is_customer_initiated_mandate_payment(
&item.request,
),
),
billing_address: billing_address.ok_or_else(|| {
ConnectorError::MissingRequiredField {
field_name: "billing_address",
}
})?,
request_incremental_authorization: item
.request
.request_incremental_authorization,
request_extended_authorization: item.request.request_extended_authorization,
request_overcapture: item
.request
.enable_overcapture
.and_then(get_stripe_overcapture_request),
},
)?;
validate_shipping_address_against_payment_method(
&shipping_address,
payment_method_type.as_ref(),
)?;
(
Some(payment_method_data),
None,
billing_address,
payment_method_type,
item.request.setup_future_usage,
)
};
if payment_method_token.is_none() {
payment_data = match item.request.payment_method_data {
PaymentMethodData::Wallet(WalletData::ApplePay(_)) => {
let payment_method_token = item
.resource_common_data
.payment_method_token
.to_owned()
.get_required_value("payment_token")
.change_context(ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?;
let payment_method_token = match payment_method_token {
domain_types::router_data::PaymentMethodToken::Token(
payment_method_token,
) => payment_method_token,
domain_types::router_data::PaymentMethodToken::ApplePayDecrypt(_) => {
Err(ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?
}
domain_types::router_data::PaymentMethodToken::PazeDecrypt(_) => {
| {
"chunk": 17,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_18 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
Err(crate::unimplemented_payment_method!("Paze", "Stripe"))?
}
domain_types::router_data::PaymentMethodToken::GooglePayDecrypt(_) => {
Err(crate::unimplemented_payment_method!("Google Pay", "Stripe"))?
}
};
Some(StripePaymentMethodData::Wallet(
StripeWallet::ApplepayPayment(ApplepayPayment {
token: payment_method_token,
payment_method_types: StripePaymentMethodType::Card,
}),
))
}
_ => payment_data,
}
} else {
payment_data = None
};
let setup_mandate_details = item
.request
.setup_mandate_details
.as_ref()
.and_then(|mandate_details| {
mandate_details
.customer_acceptance
.as_ref()
.map(|customer_acceptance| {
Ok::<_, error_stack::Report<ConnectorError>>(
match customer_acceptance.acceptance_type {
AcceptanceType::Online => {
let online_mandate = customer_acceptance
.online
.clone()
.get_required_value("online")
.change_context(ConnectorError::MissingRequiredField {
field_name: "online",
})?;
StripeMandateRequest {
mandate_type: StripeMandateType::Online {
ip_address: online_mandate
.ip_address
.get_required_value("ip_address")
.change_context(
ConnectorError::MissingRequiredField {
field_name: "ip_address",
},
)?,
user_agent: online_mandate.user_agent,
},
}
}
AcceptanceType::Offline => StripeMandateRequest {
mandate_type: StripeMandateType::Offline,
},
},
)
})
})
.transpose()?
.or_else(|| {
//stripe requires us to send mandate_data while making recurring payment through saved bank debit
if payment_method.is_some() {
//check if payment is done through saved payment method
match &payment_method_types {
//check if payment method is bank debit
Some(
StripePaymentMethodType::Ach
| StripePaymentMethodType::Sepa
| StripePaymentMethodType::Becs
| StripePaymentMethodType::Bacs,
) => Some(StripeMandateRequest {
mandate_type: StripeMandateType::Offline,
}),
_ => None,
}
} else {
None
}
});
let meta_data =
get_transaction_metadata(item.request.metadata.clone().map(Into::into), order_id);
// We pass browser_info only when payment_data exists.
// Hence, we're pass Null during recurring payments as payment_method_data[type] is not passed
let browser_info = if payment_data.is_some() && payment_method_token.is_none() {
| {
"chunk": 18,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_19 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
item.request
.browser_info
.clone()
.map(StripeBrowserInformation::from)
} else {
None
};
let charges = match &item.request.split_payments {
Some(domain_types::connector_types::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) => match &stripe_split_payment.charge_type {
common_enums::PaymentChargeType::Stripe(charge_type) => match charge_type {
common_enums::StripeChargeType::Direct => Some(IntentCharges {
application_fee_amount: stripe_split_payment.application_fees,
destination_account_id: None,
}),
common_enums::StripeChargeType::Destination => Some(IntentCharges {
application_fee_amount: stripe_split_payment.application_fees,
destination_account_id: Some(Secret::new(
stripe_split_payment.transfer_account_id.clone(),
)),
}),
},
},
None => None,
};
let charges_in = if charges.is_none() {
match charge_type {
Some(common_enums::PaymentChargeType::Stripe(
common_enums::StripeChargeType::Direct,
)) => Some(IntentCharges {
application_fee_amount: application_fees, // default to 0 if None
destination_account_id: None,
}),
Some(common_enums::PaymentChargeType::Stripe(
common_enums::StripeChargeType::Destination,
)) => Some(IntentCharges {
application_fee_amount: application_fees,
destination_account_id: transfer_account_id,
}),
_ => None,
}
} else {
charges
};
let pm = match (payment_method, payment_method_token.clone()) {
(Some(method), _) => Some(Secret::new(method)),
(None, Some(token)) => Some(token),
(None, None) => None,
};
Ok(Self {
amount, //hopefully we don't loose some cents here
currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership
statement_descriptor_suffix: item.request.statement_descriptor_suffix.clone(),
statement_descriptor: item.request.statement_descriptor.clone(),
meta_data,
return_url: item
.request
.router_return_url
.clone()
.unwrap_or_else(|| "https://juspay.in/".to_string()),
confirm: true, // Stripe requires confirm to be true if return URL is present
description: item.resource_common_data.description.clone(),
shipping: shipping_address,
billing: billing_address,
capture_method: StripeCaptureMethod::from(item.request.capture_method),
payment_data,
payment_method_options,
payment_method: pm,
customer: item
.resource_common_data
.connector_customer
.clone()
.map(Secret::new),
setup_mandate_details,
off_session: item.request.off_session,
setup_future_usage: match (
item.request.split_payments.as_ref(),
item.request.setup_future_usage,
item.request.customer_acceptance.as_ref(),
) {
(Some(_), Some(usage), Some(_)) => Some(usage),
_ => setup_future_usage,
},
payment_method_types,
expand: Some(ExpandableObjects::LatestCharge),
browser_info,
charges: charges_in,
})
}
}
fn get_stripe_overcapture_request(
enable_overcapture: bool,
) -> Option<StripeRequestOvercaptureBool> {
match enable_overcapture {
true => Some(StripeRequestOvercaptureBool::IfAvailable),
false => None,
}
}
impl From<BrowserInformation> for StripeBrowserInformation {
fn from(item: BrowserInformation) -> Self {
| {
"chunk": 19,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_20 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
Self {
ip_address: item.ip_address.map(|ip| Secret::new(ip.to_string())),
user_agent: item.user_agent,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripeSplitPaymentRequest {
pub charge_type: Option<common_enums::PaymentChargeType>,
pub application_fees: Option<MinorUnit>,
pub transfer_account_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct StripeIncrementalAuthRequest {
pub amount: MinorUnit,
}
#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
#[serde(rename = "requires_action")]
RequiresCustomerAction,
#[serde(rename = "requires_payment_method")]
RequiresPaymentMethod,
RequiresConfirmation,
Canceled,
RequiresCapture,
Chargeable,
Consumed,
Pending,
}
impl From<StripePaymentStatus> for common_enums::AttemptStatus {
fn from(item: StripePaymentStatus) -> Self {
match item {
StripePaymentStatus::Succeeded => Self::Charged,
StripePaymentStatus::Failed => Self::Failure,
StripePaymentStatus::Processing => Self::Authorizing,
StripePaymentStatus::RequiresCustomerAction => Self::AuthenticationPending,
// Make the payment attempt status as failed
StripePaymentStatus::RequiresPaymentMethod => Self::Failure,
StripePaymentStatus::RequiresConfirmation => Self::ConfirmationAwaited,
StripePaymentStatus::Canceled => Self::Voided,
StripePaymentStatus::RequiresCapture => Self::Authorized,
StripePaymentStatus::Chargeable => Self::Authorizing,
StripePaymentStatus::Consumed => Self::Authorizing,
StripePaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentIntentResponse {
pub id: String,
pub object: String,
pub amount: MinorUnit,
#[serde(default, deserialize_with = "deserialize_zero_minor_amount_as_none")]
// stripe gives amount_captured as 0 for payment intents instead of null
pub amount_received: Option<MinorUnit>,
pub amount_capturable: Option<MinorUnit>,
pub currency: String,
pub status: StripePaymentStatus,
pub client_secret: Option<Secret<String>>,
pub created: i32,
pub customer: Option<Secret<String>>,
pub payment_method: Option<Secret<String>>,
pub description: Option<String>,
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub metadata: StripeMetadata,
pub next_action: Option<StripeNextActionResponse>,
pub payment_method_options: Option<StripePaymentMethodOptions>,
pub last_payment_error: Option<ErrorDetails>,
pub latest_attempt: Option<LatestAttempt>, //need a merchant to test this
pub latest_charge: Option<StripeChargeEnum>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeSourceResponse {
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub ach_credit_transfer: Option<AchCreditTransferResponse>,
#[serde(skip_serializing_if = "Option::is_none")]
pub multibanco: Option<MultibancoCreditTransferResponse>,
pub receiver: AchReceiverDetails,
pub status: StripePaymentStatus,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct AchCreditTransferResponse {
pub account_number: Secret<String>,
pub bank_name: Secret<String>,
pub routing_number: Secret<String>,
pub swift_code: Secret<String>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct MultibancoCreditTransferResponse {
pub reference: Secret<String>,
pub entity: Secret<String>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct AchReceiverDetails {
pub amount_received: MinorUnit,
pub amount_charged: MinorUnit,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct SepaAndBacsBankTransferInstructions {
pub bacs_bank_instructions: Option<BacsFinancialDetails>,
pub sepa_bank_instructions: Option<SepaFinancialDetails>,
| {
"chunk": 20,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_21 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
pub receiver: SepaAndBacsReceiver,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Serialize)]
pub struct QrCodeNextInstructions {
pub image_data_url: url::Url,
pub display_to_timestamp: Option<i64>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct SepaAndBacsReceiver {
pub amount_received: MinorUnit,
pub amount_remaining: MinorUnit,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaymentIntentSyncResponse {
#[serde(flatten)]
payment_intent_fields: PaymentIntentResponse,
pub latest_charge: Option<StripeChargeEnum>,
}
#[derive(Debug, Eq, PartialEq, Deserialize, Clone, Serialize)]
#[serde(untagged)]
pub enum StripeChargeEnum {
ChargeId(String),
ChargeObject(Box<StripeCharge>),
}
impl StripeChargeEnum {
pub fn get_overcapture_status(&self) -> Option<bool> {
match self {
Self::ChargeObject(charge_object) => charge_object
.payment_method_details
.as_ref()
.and_then(|payment_method_details| match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => card
.overcapture
.as_ref()
.and_then(|overcapture| match overcapture.status {
Some(StripeOvercaptureStatus::Available) => Some(true),
Some(StripeOvercaptureStatus::Unavailable) => Some(false),
None => None,
}),
_ => None,
}),
_ => None,
}
}
pub fn get_maximum_capturable_amount(&self) -> Option<MinorUnit> {
match self {
Self::ChargeObject(charge_object) => {
if let Some(payment_method_details) = charge_object.payment_method_details.as_ref()
{
match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => card
.overcapture
.as_ref()
.and_then(|overcapture| overcapture.maximum_amount_capturable),
_ => None,
}
} else {
None
}
}
_ => None,
}
}
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
pub struct StripeCharge {
pub id: String,
pub payment_method_details: Option<StripePaymentMethodDetailsResponse>,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
pub struct StripeBankRedirectDetails {
#[serde(rename = "generated_sepa_debit")]
attached_payment_method: Option<Secret<String>>,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
pub struct StripeCashappDetails {
buyer_id: Option<String>,
cashtag: Option<String>,
}
impl Deref for PaymentIntentSyncResponse {
type Target = PaymentIntentResponse;
fn deref(&self) -> &Self::Target {
&self.payment_intent_fields
}
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
pub struct StripeAdditionalCardDetails {
checks: Option<Value>,
three_d_secure: Option<Value>,
network_transaction_id: Option<String>,
extended_authorization: Option<StripeExtendedAuthorizationResponse>,
#[serde(default, with = "custom_serde::timestamp::option")]
capture_before: Option<PrimitiveDateTime>,
overcapture: Option<StripeOvercaptureResponse>,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
pub struct StripeExtendedAuthorizationResponse {
status: Option<StripeExtendedAuthorizationStatus>,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum StripeExtendedAuthorizationStatus {
Disabled,
Enabled,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
pub struct StripeOvercaptureResponse {
status: Option<StripeOvercaptureStatus>,
#[serde(default, deserialize_with = "deserialize_zero_minor_amount_as_none")]
// stripe gives amount_captured as 0 for payment intents instead of null
maximum_amount_capturable: Option<MinorUnit>,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
| {
"chunk": 21,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_22 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
pub enum StripeOvercaptureStatus {
Available,
Unavailable,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum StripePaymentMethodDetailsResponse {
//only ideal and bancontact is supported by stripe for recurring payment in bank redirect
Ideal {
ideal: StripeBankRedirectDetails,
},
Bancontact {
bancontact: StripeBankRedirectDetails,
},
//other payment method types supported by stripe. To avoid deserialization error.
Blik,
Eps,
Fpx,
Giropay,
#[serde(rename = "p24")]
Przelewy24,
Card {
card: StripeAdditionalCardDetails,
},
Cashapp {
cashapp: StripeCashappDetails,
},
Klarna,
Affirm,
AfterpayClearpay,
AmazonPay,
ApplePay,
#[serde(rename = "us_bank_account")]
Ach,
#[serde(rename = "sepa_debit")]
Sepa,
#[serde(rename = "au_becs_debit")]
Becs,
#[serde(rename = "bacs_debit")]
Bacs,
#[serde(rename = "wechat_pay")]
Wechatpay,
Alipay,
CustomerBalance,
RevolutPay,
}
pub struct AdditionalPaymentMethodDetails {
pub payment_checks: Option<Value>,
pub authentication_details: Option<Value>,
pub extended_authorization: Option<StripeExtendedAuthorizationResponse>,
pub capture_before: Option<PrimitiveDateTime>,
}
impl From<&AdditionalPaymentMethodDetails> for AdditionalPaymentMethodConnectorResponse {
fn from(item: &AdditionalPaymentMethodDetails) -> Self {
Self::Card {
authentication_data: item.authentication_details.clone(),
payment_checks: item.payment_checks.clone(),
card_network: None,
domestic_network: None,
}
}
}
impl From<&AdditionalPaymentMethodDetails> for ExtendedAuthorizationResponseData {
fn from(item: &AdditionalPaymentMethodDetails) -> Self {
Self {
extended_authentication_applied: item.extended_authorization.as_ref().map(
|extended_authorization| {
matches!(
extended_authorization.status,
Some(StripeExtendedAuthorizationStatus::Enabled)
)
},
),
capture_before: item.capture_before,
}
}
}
impl StripePaymentMethodDetailsResponse {
pub fn get_additional_payment_method_data(&self) -> Option<AdditionalPaymentMethodDetails> {
match self {
Self::Card { card } => Some(AdditionalPaymentMethodDetails {
payment_checks: card.checks.clone(),
authentication_details: card.three_d_secure.clone(),
extended_authorization: card.extended_authorization.clone(),
capture_before: card.capture_before,
}),
Self::Ideal { .. }
| Self::Bancontact { .. }
| Self::Blik
| Self::Eps
| Self::Fpx
| Self::Giropay
| Self::Przelewy24
| Self::Klarna
| Self::Affirm
| Self::AfterpayClearpay
| Self::AmazonPay
| Self::ApplePay
| Self::Ach
| Self::Sepa
| Self::Becs
| Self::Bacs
| Self::Wechatpay
| Self::Alipay
| Self::CustomerBalance
| Self::RevolutPay
| Self::Cashapp { .. } => None,
}
}
}
#[derive(Deserialize)]
pub struct SetupIntentSyncResponse {
#[serde(flatten)]
setup_intent_fields: SetupMandateResponse,
}
impl Deref for SetupIntentSyncResponse {
type Target = SetupMandateResponse;
fn deref(&self) -> &Self::Target {
&self.setup_intent_fields
}
}
impl From<SetupIntentSyncResponse> for PaymentIntentSyncResponse {
fn from(value: SetupIntentSyncResponse) -> Self {
Self {
payment_intent_fields: value.setup_intent_fields.into(),
latest_charge: None,
}
}
}
impl From<SetupMandateResponse> for PaymentIntentResponse {
fn from(value: SetupMandateResponse) -> Self {
Self {
id: value.id,
object: value.object,
status: value.status,
client_secret: Some(value.client_secret),
customer: value.customer,
description: None,
statement_descriptor: value.statement_descriptor,
| {
"chunk": 22,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_23 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
statement_descriptor_suffix: value.statement_descriptor_suffix,
metadata: value.metadata,
next_action: value.next_action,
payment_method_options: value.payment_method_options,
last_payment_error: value.last_setup_error,
..Default::default()
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct SetupMandateResponse {
pub id: String,
pub object: String,
pub status: StripePaymentStatus, // Change to SetupStatus
pub client_secret: Secret<String>,
pub customer: Option<Secret<String>>,
pub payment_method: Option<String>,
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub metadata: StripeMetadata,
pub next_action: Option<StripeNextActionResponse>,
pub payment_method_options: Option<StripePaymentMethodOptions>,
pub latest_attempt: Option<LatestAttempt>,
pub last_setup_error: Option<ErrorDetails>,
}
fn extract_payment_method_connector_response_from_latest_charge(
stripe_charge_enum: &StripeChargeEnum,
) -> Option<ConnectorResponseData> {
let is_overcapture_enabled = stripe_charge_enum.get_overcapture_status();
let additional_payment_method_details =
if let StripeChargeEnum::ChargeObject(charge_object) = stripe_charge_enum {
charge_object
.payment_method_details
.as_ref()
.and_then(StripePaymentMethodDetailsResponse::get_additional_payment_method_data)
} else {
None
};
let additional_payment_method_data = additional_payment_method_details
.as_ref()
.map(AdditionalPaymentMethodConnectorResponse::from);
let extended_authorization_data = additional_payment_method_details
.as_ref()
.map(ExtendedAuthorizationResponseData::from);
if additional_payment_method_data.is_some()
|| extended_authorization_data.is_some()
|| is_overcapture_enabled.is_some()
{
Some(ConnectorResponseData::new(
additional_payment_method_data,
is_overcapture_enabled,
extended_authorization_data,
))
} else {
None
}
}
impl<F, T> TryFrom<ResponseRouterData<PaymentIntentResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
where
T: SplitPaymentData + GetRequestIncrementalAuthorization,
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<PaymentIntentResponse, Self>,
) -> Result<Self, Self::Error> {
let redirect_data = item.response.next_action.clone();
let redirection_data = redirect_data
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| RedirectForm::from((redirection_url, Method::Get)));
let mandate_reference = item.response.payment_method.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
// For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
let connector_mandate_id = Some(payment_method_id.clone().expose());
let payment_method_id = Some(payment_method_id.expose());
let _mandate_metadata: Option<Secret<Value>> =
match item.router_data.request.get_split_payment_data() {
Some(
domain_types::connector_types::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_data,
),
) => Some(Secret::new(serde_json::json!({
"transfer_account_id": stripe_split_data.transfer_account_id,
"charge_type": stripe_split_data.charge_type,
"application_fees": stripe_split_data.application_fees,
}))),
_ => None,
};
MandateReference {
connector_mandate_id,
payment_method_id,
//mandate_metadata,
}
});
| {
"chunk": 23,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_24 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
//Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse
// Or we identify the mandate txns before hand and always call SetupIntent in case of mandate payment call
let network_txn_id = match item.response.latest_charge.as_ref() {
Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
.payment_method_details
.as_ref()
.and_then(|payment_method_details| match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => {
card.network_transaction_id.clone()
}
_ => None,
}),
_ => None,
};
let connector_metadata =
get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;
let status = common_enums::AttemptStatus::from(item.response.status);
let response = if is_payment_failure(status) {
*get_stripe_payments_response_data(
&item.response.last_payment_error,
item.http_code,
item.response.id.clone(),
)
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: redirection_data.map(Box::new),
mandate_reference: mandate_reference.map(Box::new),
connector_metadata,
network_txn_id,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: item
.router_data
.request
.get_request_incremental_authorization(),
status_code: item.http_code,
})
};
let connector_response_data = item
.response
.latest_charge
.as_ref()
.and_then(extract_payment_method_connector_response_from_latest_charge);
let minor_amount_capturable = item
.response
.latest_charge
.as_ref()
.and_then(StripeChargeEnum::get_maximum_capturable_amount);
Ok(Self {
resource_common_data: PaymentFlowData {
status,
amount_captured: item
.response
.amount_received
.map(|amount| amount.get_amount_as_i64()),
minor_amount_captured: item.response.amount_received,
connector_response: connector_response_data,
minor_amount_capturable,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
impl From<StripePaymentStatus> for common_enums::AuthorizationStatus {
fn from(item: StripePaymentStatus) -> Self {
match item {
StripePaymentStatus::Succeeded
| StripePaymentStatus::RequiresCapture
| StripePaymentStatus::Chargeable
| StripePaymentStatus::RequiresCustomerAction
| StripePaymentStatus::RequiresConfirmation
| StripePaymentStatus::Consumed => Self::Success,
StripePaymentStatus::Processing | StripePaymentStatus::Pending => Self::Processing,
StripePaymentStatus::Failed
| StripePaymentStatus::Canceled
| StripePaymentStatus::RequiresPaymentMethod => Self::Failure,
}
}
}
pub fn get_connector_metadata(
next_action: Option<&StripeNextActionResponse>,
amount: MinorUnit,
) -> CustomResult<Option<Value>, ConnectorError> {
let next_action_response = next_action
.and_then(|next_action_response| match next_action_response {
StripeNextActionResponse::DisplayBankTransferInstructions(response) => {
match response.financial_addresses.clone() {
FinancialInformation::StripeFinancialInformation(financial_addresses) => {
let bank_instructions = financial_addresses.first();
let (sepa_bank_instructions, bacs_bank_instructions) = bank_instructions
| {
"chunk": 24,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_25 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
.map_or((None, None), |financial_address| {
(
financial_address.iban.to_owned().map(
|sepa_financial_details| SepaFinancialDetails {
account_holder_name: sepa_financial_details
.account_holder_name,
bic: sepa_financial_details.bic,
country: sepa_financial_details.country,
iban: sepa_financial_details.iban,
reference: response.reference.to_owned(),
},
),
financial_address.sort_code.to_owned(),
)
});
let bank_transfer_instructions = SepaAndBacsBankTransferInstructions {
sepa_bank_instructions,
bacs_bank_instructions,
receiver: SepaAndBacsReceiver {
amount_received: amount - response.amount_remaining,
amount_remaining: response.amount_remaining,
},
};
Some(bank_transfer_instructions.encode_to_value())
}
FinancialInformation::AchFinancialInformation(financial_addresses) => {
let mut ach_financial_information = HashMap::new();
for address in financial_addresses {
match address.financial_details {
AchFinancialDetails::Aba(aba_details) => {
ach_financial_information
.insert("account_number", aba_details.account_number);
ach_financial_information
.insert("bank_name", aba_details.bank_name);
ach_financial_information
.insert("routing_number", aba_details.routing_number);
}
AchFinancialDetails::Swift(swift_details) => {
ach_financial_information
.insert("swift_code", swift_details.swift_code);
}
}
}
let ach_financial_information_value =
serde_json::to_value(ach_financial_information).ok()?;
let ach_transfer_instruction =
serde_json::from_value::<AchTransfer>(ach_financial_information_value)
.ok()?;
let bank_transfer_instructions = BankTransferNextStepsData {
bank_transfer_instructions: BankTransferInstructions::AchCreditTransfer(
Box::new(ach_transfer_instruction),
),
receiver: None,
};
Some(bank_transfer_instructions.encode_to_value())
}
}
}
StripeNextActionResponse::WechatPayDisplayQrCode(response) => {
let wechat_pay_instructions = QrCodeNextInstructions {
image_data_url: response.image_data_url.to_owned(),
display_to_timestamp: None,
};
Some(wechat_pay_instructions.encode_to_value())
}
StripeNextActionResponse::CashappHandleRedirectOrDisplayQrCode(response) => {
let cashapp_qr_instructions: QrCodeNextInstructions = QrCodeNextInstructions {
image_data_url: response.qr_code.image_url_png.to_owned(),
display_to_timestamp: response.qr_code.expires_at.to_owned(),
| {
"chunk": 25,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_26 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
};
Some(cashapp_qr_instructions.encode_to_value())
}
StripeNextActionResponse::MultibancoDisplayDetails(response) => {
let multibanco_bank_transfer_instructions = BankTransferNextStepsData {
bank_transfer_instructions: BankTransferInstructions::Multibanco(Box::new(
MultibancoTransferInstructions {
reference: response.clone().reference,
entity: response.clone().entity.expose(),
},
)),
receiver: None,
};
Some(multibanco_bank_transfer_instructions.encode_to_value())
}
_ => None,
})
.transpose()
.change_context(ConnectorError::ResponseHandlingFailed)?;
Ok(next_action_response)
}
pub fn get_payment_method_id(
latest_charge: Option<StripeChargeEnum>,
payment_method_id_from_intent_root: Secret<String>,
) -> String {
match latest_charge {
Some(StripeChargeEnum::ChargeObject(charge)) => match charge.payment_method_details {
Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => bancontact
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
.unwrap_or(payment_method_id_from_intent_root.expose()),
Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
.unwrap_or(payment_method_id_from_intent_root.expose()),
Some(StripePaymentMethodDetailsResponse::Blik)
| Some(StripePaymentMethodDetailsResponse::Eps)
| Some(StripePaymentMethodDetailsResponse::Fpx)
| Some(StripePaymentMethodDetailsResponse::Giropay)
| Some(StripePaymentMethodDetailsResponse::Przelewy24)
| Some(StripePaymentMethodDetailsResponse::Card { .. })
| Some(StripePaymentMethodDetailsResponse::Klarna)
| Some(StripePaymentMethodDetailsResponse::Affirm)
| Some(StripePaymentMethodDetailsResponse::AfterpayClearpay)
| Some(StripePaymentMethodDetailsResponse::AmazonPay)
| Some(StripePaymentMethodDetailsResponse::ApplePay)
| Some(StripePaymentMethodDetailsResponse::Ach)
| Some(StripePaymentMethodDetailsResponse::Sepa)
| Some(StripePaymentMethodDetailsResponse::Becs)
| Some(StripePaymentMethodDetailsResponse::Bacs)
| Some(StripePaymentMethodDetailsResponse::Wechatpay)
| Some(StripePaymentMethodDetailsResponse::Alipay)
| Some(StripePaymentMethodDetailsResponse::CustomerBalance)
| Some(StripePaymentMethodDetailsResponse::Cashapp { .. })
| Some(StripePaymentMethodDetailsResponse::RevolutPay)
| None => payment_method_id_from_intent_root.expose(),
},
Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id_from_intent_root.expose(),
}
}
impl<F> TryFrom<ResponseRouterData<PaymentIntentSyncResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<PaymentIntentSyncResponse, Self>,
) -> Result<Self, Self::Error> {
let redirect_data = item.response.next_action.clone();
let redirection_data = redirect_data
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| RedirectForm::from((redirection_url, Method::Get)));
let mandate_reference = item
.response
.payment_method
.clone()
.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
// For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
| {
"chunk": 26,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_27 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
let payment_method_id =
get_payment_method_id(item.response.latest_charge.clone(), payment_method_id);
MandateReference {
connector_mandate_id: Some(payment_method_id.clone()),
payment_method_id: Some(payment_method_id),
}
});
let connector_metadata =
get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;
let status = common_enums::AttemptStatus::from(item.response.status.to_owned());
let connector_response_data = item
.response
.latest_charge
.as_ref()
.and_then(extract_payment_method_connector_response_from_latest_charge);
let response = if is_payment_failure(status) {
*get_stripe_payments_response_data(
&item.response.payment_intent_fields.last_payment_error,
item.http_code,
item.response.id.clone(),
)
} else {
let network_transaction_id = match item.response.latest_charge.clone() {
Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
.payment_method_details
.and_then(|payment_method_details| match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => {
card.network_transaction_id
}
_ => None,
}),
_ => None,
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: redirection_data.map(Box::new),
mandate_reference: mandate_reference.map(Box::new),
connector_metadata,
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id.clone()),
incremental_authorization_allowed: None,
status_code: item.http_code,
})
};
let currency_enum =
common_enums::Currency::from_str(item.response.currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let amount_in_minor_unit =
StripeAmountConvertor::convert_back(item.response.amount, currency_enum)?;
let response_integrity_object = PaymentSynIntegrityObject {
amount: amount_in_minor_unit,
currency: currency_enum,
};
Ok(Self {
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::from(item.response.status.to_owned()),
amount_captured: item
.response
.amount_received
.map(|amount| amount.get_amount_as_i64()),
minor_amount_captured: item.response.amount_received,
connector_response: connector_response_data,
..item.router_data.resource_common_data
},
request: PaymentsSyncData {
integrity_object: Some(response_integrity_object),
..item.router_data.request
},
response,
..item.router_data
})
}
}
fn extract_payment_method_connector_response_from_latest_attempt(
stripe_latest_attempt: &LatestAttempt,
) -> Option<ConnectorResponseData> {
if let LatestAttempt::PaymentIntentAttempt(intent_attempt) = stripe_latest_attempt {
intent_attempt
.payment_method_details
.as_ref()
.and_then(StripePaymentMethodDetailsResponse::get_additional_payment_method_data)
} else {
None
}
.as_ref()
.map(AdditionalPaymentMethodConnectorResponse::from)
.map(ConnectorResponseData::with_additional_payment_method_data)
}
impl<F, T> TryFrom<ResponseRouterData<SetupMandateResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<SetupMandateResponse, Self>) -> Result<Self, Self::Error> {
| {
"chunk": 27,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_28 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
let redirect_data = item.response.next_action.clone();
let redirection_data = redirect_data
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| RedirectForm::from((redirection_url, Method::Get)));
let mandate_reference = item.response.payment_method.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
// For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
let connector_mandate_id = Some(payment_method_id.clone());
let payment_method_id = Some(payment_method_id);
MandateReference {
connector_mandate_id,
payment_method_id,
}
});
let status = common_enums::AttemptStatus::from(item.response.status);
let connector_response_data = item
.response
.latest_attempt
.as_ref()
.and_then(extract_payment_method_connector_response_from_latest_attempt);
let response = if is_payment_failure(status) {
*get_stripe_payments_response_data(
&item.response.last_setup_error,
item.http_code,
item.response.id.clone(),
)
} else {
let network_transaction_id = match item.response.latest_attempt {
Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt
.payment_method_details
.and_then(|payment_method_details| match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => {
card.network_transaction_id
}
_ => None,
}),
_ => None,
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: redirection_data.map(Box::new),
mandate_reference: mandate_reference.map(Box::new),
connector_metadata: None,
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
status_code: item.http_code,
})
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
connector_response: connector_response_data,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
pub fn stripe_opt_latest_attempt_to_opt_string(
latest_attempt: Option<LatestAttempt>,
) -> Option<String> {
match latest_attempt {
Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt
.payment_method_options
.and_then(|payment_method_options| match payment_method_options {
StripePaymentMethodOptions::Card {
network_transaction_id,
..
} => network_transaction_id.map(|network_id| network_id.expose()),
_ => None,
}),
_ => None,
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", remote = "Self")]
pub enum StripeNextActionResponse {
CashappHandleRedirectOrDisplayQrCode(StripeCashappQrResponse),
RedirectToUrl(StripeRedirectToUrlResponse),
AlipayHandleRedirect(StripeRedirectToUrlResponse),
VerifyWithMicrodeposits(StripeVerifyWithMicroDepositsResponse),
WechatPayDisplayQrCode(WechatPayRedirectToQr),
DisplayBankTransferInstructions(StripeBankTransferDetails),
MultibancoDisplayDetails(MultibancoCreditTransferResponse),
NoNextActionBody,
}
impl StripeNextActionResponse {
fn get_url(&self) -> Option<url::Url> {
match self {
Self::RedirectToUrl(redirect_to_url) | Self::AlipayHandleRedirect(redirect_to_url) => {
Some(redirect_to_url.url.to_owned())
}
| {
"chunk": 28,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_29 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
Self::WechatPayDisplayQrCode(_) => None,
Self::VerifyWithMicrodeposits(verify_with_microdeposits) => {
Some(verify_with_microdeposits.hosted_verification_url.to_owned())
}
Self::CashappHandleRedirectOrDisplayQrCode(_) => None,
Self::DisplayBankTransferInstructions(_) => None,
Self::MultibancoDisplayDetails(_) => None,
Self::NoNextActionBody => None,
}
}
}
// This impl is required because Stripe's response is of the below format, which is externally
// tagged, but also with an extra 'type' field specifying the enum variant name:
// "next_action": {
// "redirect_to_url": { "return_url": "...", "url": "..." },
// "type": "redirect_to_url"
// },
// Reference: https://github.com/serde-rs/serde/issues/1343#issuecomment-409698470
impl<'de> Deserialize<'de> for StripeNextActionResponse {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Wrapper {
#[serde(rename = "type")]
_ignore: String,
#[serde(flatten, with = "StripeNextActionResponse")]
inner: StripeNextActionResponse,
}
// There is some exception in the stripe next action, it usually sends :
// "next_action": {
// "redirect_to_url": { "return_url": "...", "url": "..." },
// "type": "redirect_to_url"
// },
// But there is a case where it only sends the type and not other field named as it's type
let stripe_next_action_response =
Wrapper::deserialize(deserializer).map_or(Self::NoNextActionBody, |w| w.inner);
Ok(stripe_next_action_response)
}
}
impl Serialize for StripeNextActionResponse {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match *self {
Self::CashappHandleRedirectOrDisplayQrCode(ref i) => {
Serialize::serialize(i, serializer)
}
Self::RedirectToUrl(ref i) => Serialize::serialize(i, serializer),
Self::AlipayHandleRedirect(ref i) => Serialize::serialize(i, serializer),
Self::VerifyWithMicrodeposits(ref i) => Serialize::serialize(i, serializer),
Self::WechatPayDisplayQrCode(ref i) => Serialize::serialize(i, serializer),
Self::DisplayBankTransferInstructions(ref i) => Serialize::serialize(i, serializer),
Self::MultibancoDisplayDetails(ref i) => Serialize::serialize(i, serializer),
Self::NoNextActionBody => Serialize::serialize("NoNextActionBody", serializer),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeRedirectToUrlResponse {
return_url: String,
url: Url,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct WechatPayRedirectToQr {
// This data contains url, it should be converted to QR code.
// Note: The url in this data is not redirection url
data: Url,
// This is the image source, this image_data_url can directly be used by sdk to show the QR code
image_data_url: Url,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeVerifyWithMicroDepositsResponse {
hosted_verification_url: Url,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum FinancialInformation {
AchFinancialInformation(Vec<AchFinancialInformation>),
StripeFinancialInformation(Vec<StripeFinancialInformation>),
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeBankTransferDetails {
pub amount_remaining: MinorUnit,
pub currency: String,
pub financial_addresses: FinancialInformation,
pub hosted_instructions_url: Option<String>,
pub reference: Option<String>,
#[serde(rename = "type")]
pub bank_transfer_type: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeCashappQrResponse {
pub mobile_auth_url: Url,
pub qr_code: QrCodeResponse,
pub hosted_instructions_url: Url,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct QrCodeResponse {
pub expires_at: Option<i64>,
| {
"chunk": 29,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_30 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
pub image_url_png: Url,
pub image_url_svg: Url,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct AbaDetails {
pub account_number: Secret<String>,
pub bank_name: Secret<String>,
pub routing_number: Secret<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SwiftDetails {
pub account_number: Secret<String>,
pub bank_name: Secret<String>,
pub swift_code: Secret<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AchFinancialDetails {
Aba(AbaDetails),
Swift(SwiftDetails),
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeFinancialInformation {
pub iban: Option<SepaFinancialDetails>,
pub sort_code: Option<BacsFinancialDetails>,
pub supported_networks: Vec<String>,
#[serde(rename = "type")]
pub financial_info_type: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct AchFinancialInformation {
#[serde(flatten)]
pub financial_details: AchFinancialDetails,
pub supported_networks: Vec<String>,
#[serde(rename = "type")]
pub financial_info_type: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SepaFinancialDetails {
pub account_holder_name: Secret<String>,
pub bic: Secret<String>,
pub country: Secret<String>,
pub iban: Secret<String>,
pub reference: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct BacsFinancialDetails {
pub account_holder_name: Secret<String>,
pub account_number: Secret<String>,
pub sort_code: Secret<String>,
}
// REFUND :
// Type definition for Stripe RefundRequest
#[derive(Debug, Serialize)]
pub struct RefundRequest {
pub amount: Option<MinorUnit>, //amount in cents, hence passed as integer
pub payment_intent: String,
#[serde(flatten)]
pub meta_data: StripeMetadata,
}
#[derive(Debug, Serialize)]
pub struct ChargeRefundRequest {
pub charge: String,
pub refund_application_fee: Option<bool>,
pub reverse_transfer: Option<bool>,
pub amount: Option<MinorUnit>, //amount in cents, hence passed as integer
#[serde(flatten)]
pub meta_data: StripeMetadata,
}
// Type definition for Stripe Refund Response
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Pending,
RequiresAction,
}
impl From<RefundStatus> for common_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Pending => Self::Pending,
RefundStatus::RequiresAction => Self::ManualReview,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub object: String,
pub amount: MinorUnit,
pub currency: String,
pub metadata: StripeMetadata,
pub payment_intent: String,
pub status: RefundStatus,
pub failure_reason: Option<String>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct ErrorDetails {
pub code: Option<String>,
#[serde(rename = "type")]
pub error_type: Option<String>,
pub message: Option<String>,
pub param: Option<String>,
pub decline_code: Option<String>,
pub payment_intent: Option<PaymentIntentErrorResponse>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub advice_code: Option<String>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentIntentErrorResponse {
pub id: String,
}
#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct ErrorResponse {
pub error: ErrorDetails,
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct StripeShippingAddress {
#[serde(rename = "shipping[address][city]")]
pub city: Option<String>,
#[serde(rename = "shipping[address][country]")]
pub country: Option<common_enums::CountryAlpha2>,
#[serde(rename = "shipping[address][line1]")]
pub line1: Option<Secret<String>>,
#[serde(rename = "shipping[address][line2]")]
pub line2: Option<Secret<String>>,
| {
"chunk": 30,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_31 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
#[serde(rename = "shipping[address][postal_code]")]
pub zip: Option<Secret<String>>,
#[serde(rename = "shipping[address][state]")]
pub state: Option<Secret<String>>,
#[serde(rename = "shipping[name]")]
pub name: Option<Secret<String>>,
#[serde(rename = "shipping[phone]")]
pub phone: Option<Secret<String>>,
}
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize)]
pub struct StripeBillingAddress {
#[serde(rename = "payment_method_data[billing_details][email]")]
pub email: Option<Email>,
#[serde(rename = "payment_method_data[billing_details][address][country]")]
pub country: Option<common_enums::CountryAlpha2>,
#[serde(rename = "payment_method_data[billing_details][name]")]
pub name: Option<Secret<String>>,
#[serde(rename = "payment_method_data[billing_details][address][city]")]
pub city: Option<String>,
#[serde(rename = "payment_method_data[billing_details][address][line1]")]
pub address_line1: Option<Secret<String>>,
#[serde(rename = "payment_method_data[billing_details][address][line2]")]
pub address_line2: Option<Secret<String>>,
#[serde(rename = "payment_method_data[billing_details][address][postal_code]")]
pub zip_code: Option<Secret<String>>,
#[serde(rename = "payment_method_data[billing_details][address][state]")]
pub state: Option<Secret<String>>,
#[serde(rename = "payment_method_data[billing_details][phone]")]
pub phone: Option<Secret<String>>,
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
pub struct StripeRedirectResponse {
pub payment_intent: Option<String>,
pub payment_intent_client_secret: Option<Secret<String>>,
pub source_redirect_slug: Option<String>,
pub redirect_status: Option<StripePaymentStatus>,
pub source_type: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CancelRequest {
cancellation_reason: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct UpdateMetadataRequest {
#[serde(flatten)]
pub metadata: HashMap<String, String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
pub enum StripePaymentMethodOptions {
Card {
mandate_options: Option<StripeMandateOptions>,
#[serde(rename = "payment_method_options[card][network_transaction_id]")]
network_transaction_id: Option<Secret<String>>,
#[serde(flatten)]
mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns
},
Klarna {},
Affirm {},
AfterpayClearpay {},
AmazonPay {},
Eps {},
Giropay {},
Ideal {},
Sofort {},
#[serde(rename = "us_bank_account")]
Ach {},
#[serde(rename = "sepa_debit")]
Sepa {},
#[serde(rename = "au_becs_debit")]
Becs {},
#[serde(rename = "bacs_debit")]
Bacs {},
Bancontact {},
WechatPay {},
Alipay {},
#[serde(rename = "p24")]
Przelewy24 {},
CustomerBalance {},
Multibanco {},
Blik {},
Cashapp {},
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct MitExemption {
#[serde(rename = "payment_method_options[card][mit_exemption][network_transaction_id]")]
pub network_transaction_id: Secret<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum LatestAttempt {
PaymentIntentAttempt(Box<LatestPaymentAttempt>),
SetupAttempt(String),
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct LatestPaymentAttempt {
pub payment_method_options: Option<StripePaymentMethodOptions>,
pub payment_method_details: Option<StripePaymentMethodDetailsResponse>,
}
// #[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
// pub struct Card
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)]
pub struct StripeMandateOptions {
reference: Secret<String>, // Extendable, But only important field to be captured
}
/// Represents the capture request body for stripe connector.
#[derive(Debug, Serialize, Clone, Copy)]
pub struct CaptureRequest {
/// If amount_to_capture is None stripe captures the amount in the payment intent.
amount_to_capture: Option<MinorUnit>,
}
impl TryFrom<MinorUnit> for CaptureRequest {
type Error = error_stack::Report<ConnectorError>;
| {
"chunk": 31,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_32 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
fn try_from(capture_amount: MinorUnit) -> Result<Self, Self::Error> {
Ok(Self {
amount_to_capture: Some(capture_amount),
})
}
}
#[derive(Debug, Deserialize)]
pub struct WebhookEventDataResource {
pub object: Value,
}
#[derive(Debug, Deserialize)]
pub struct WebhookEventObjectResource {
pub data: WebhookEventDataResource,
}
#[derive(Debug, Deserialize)]
pub struct WebhookEvent {
#[serde(rename = "type")]
pub event_type: WebhookEventType,
#[serde(rename = "data")]
pub event_data: WebhookEventData,
}
#[derive(Debug, Deserialize)]
pub struct WebhookEventTypeBody {
#[serde(rename = "type")]
pub event_type: WebhookEventType,
#[serde(rename = "data")]
pub event_data: WebhookStatusData,
}
#[derive(Debug, Deserialize)]
pub struct WebhookEventData {
#[serde(rename = "object")]
pub event_object: WebhookEventObjectData,
}
#[derive(Debug, Deserialize)]
pub struct WebhookStatusData {
#[serde(rename = "object")]
pub event_object: WebhookStatusObjectData,
}
#[derive(Debug, Deserialize)]
pub struct WebhookStatusObjectData {
pub status: Option<WebhookEventStatus>,
pub payment_method_details: Option<WebhookPaymentMethodDetails>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookPaymentMethodType {
AchCreditTransfer,
MultibancoBankTransfers,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct WebhookPaymentMethodDetails {
#[serde(rename = "type")]
pub payment_method: WebhookPaymentMethodType,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookEventObjectData {
pub id: String,
pub object: WebhookEventObjectType,
pub amount: Option<MinorUnit>,
#[serde(default, deserialize_with = "convert_uppercase")]
pub currency: common_enums::Currency,
pub payment_intent: Option<String>,
pub client_secret: Option<Secret<String>>,
pub reason: Option<String>,
#[serde(with = "common_utils::custom_serde::timestamp")]
pub created: PrimitiveDateTime,
pub evidence_details: Option<EvidenceDetails>,
pub status: Option<WebhookEventStatus>,
pub metadata: Option<StripeMetadata>,
pub last_payment_error: Option<ErrorDetails>,
}
#[derive(Debug, Clone, Serialize, Deserialize, strum::Display)]
#[serde(rename_all = "snake_case")]
pub enum WebhookEventObjectType {
PaymentIntent,
Dispute,
Charge,
Source,
Refund,
}
#[derive(Debug, Deserialize)]
pub enum WebhookEventType {
#[serde(rename = "payment_intent.payment_failed")]
PaymentIntentFailed,
#[serde(rename = "payment_intent.succeeded")]
PaymentIntentSucceed,
#[serde(rename = "charge.dispute.created")]
DisputeCreated,
#[serde(rename = "charge.dispute.closed")]
DisputeClosed,
#[serde(rename = "charge.dispute.updated")]
DisputeUpdated,
#[serde(rename = "charge.dispute.funds_reinstated")]
ChargeDisputeFundsReinstated,
#[serde(rename = "charge.dispute.funds_withdrawn")]
ChargeDisputeFundsWithdrawn,
#[serde(rename = "charge.expired")]
ChargeExpired,
#[serde(rename = "charge.failed")]
ChargeFailed,
#[serde(rename = "charge.pending")]
ChargePending,
#[serde(rename = "charge.captured")]
ChargeCaptured,
#[serde(rename = "charge.refund.updated")]
ChargeRefundUpdated,
#[serde(rename = "charge.succeeded")]
ChargeSucceeded,
#[serde(rename = "charge.updated")]
ChargeUpdated,
#[serde(rename = "charge.refunded")]
ChargeRefunded,
#[serde(rename = "payment_intent.canceled")]
PaymentIntentCanceled,
#[serde(rename = "payment_intent.created")]
PaymentIntentCreated,
#[serde(rename = "payment_intent.processing")]
PaymentIntentProcessing,
#[serde(rename = "payment_intent.requires_action")]
PaymentIntentRequiresAction,
#[serde(rename = "payment_intent.amount_capturable_updated")]
PaymentIntentAmountCapturableUpdated,
#[serde(rename = "source.chargeable")]
SourceChargeable,
#[serde(rename = "source.transaction.created")]
SourceTransactionCreated,
#[serde(rename = "payment_intent.partially_funded")]
PaymentIntentPartiallyFunded,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Serialize, strum::Display, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum WebhookEventStatus {
WarningNeedsResponse,
WarningClosed,
| {
"chunk": 32,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_33 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
WarningUnderReview,
Won,
Lost,
NeedsResponse,
UnderReview,
ChargeRefunded,
Succeeded,
RequiresPaymentMethod,
RequiresConfirmation,
RequiresAction,
Processing,
RequiresCapture,
Canceled,
Chargeable,
Failed,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EvidenceDetails {
#[serde(with = "common_utils::custom_serde::timestamp")]
pub due_by: PrimitiveDateTime,
}
#[derive(Debug, Deserialize)]
pub struct StripeGpayToken {
pub id: String,
}
#[derive(Debug, Serialize)]
pub struct StripeFileRequest {
pub purpose: &'static str,
#[serde(skip)]
pub file: Vec<u8>,
#[serde(skip)]
pub file_key: String,
#[serde(skip)]
pub file_type: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FileUploadResponse {
#[serde(rename = "id")]
pub file_id: String,
}
#[derive(Debug, Serialize)]
pub struct Evidence {
#[serde(rename = "evidence[access_activity_log]")]
pub access_activity_log: Option<String>,
#[serde(rename = "evidence[billing_address]")]
pub billing_address: Option<Secret<String>>,
#[serde(rename = "evidence[cancellation_policy]")]
pub cancellation_policy: Option<String>,
#[serde(rename = "evidence[cancellation_policy_disclosure]")]
pub cancellation_policy_disclosure: Option<String>,
#[serde(rename = "evidence[cancellation_rebuttal]")]
pub cancellation_rebuttal: Option<String>,
#[serde(rename = "evidence[customer_communication]")]
pub customer_communication: Option<String>,
#[serde(rename = "evidence[customer_email_address]")]
pub customer_email_address: Option<Secret<String, pii::EmailStrategy>>,
#[serde(rename = "evidence[customer_name]")]
pub customer_name: Option<Secret<String>>,
#[serde(rename = "evidence[customer_purchase_ip]")]
pub customer_purchase_ip: Option<Secret<String, pii::IpAddress>>,
#[serde(rename = "evidence[customer_signature]")]
pub customer_signature: Option<Secret<String>>,
#[serde(rename = "evidence[product_description]")]
pub product_description: Option<String>,
#[serde(rename = "evidence[receipt]")]
pub receipt: Option<Secret<String>>,
#[serde(rename = "evidence[refund_policy]")]
pub refund_policy: Option<String>,
#[serde(rename = "evidence[refund_policy_disclosure]")]
pub refund_policy_disclosure: Option<String>,
#[serde(rename = "evidence[refund_refusal_explanation]")]
pub refund_refusal_explanation: Option<String>,
#[serde(rename = "evidence[service_date]")]
pub service_date: Option<String>,
#[serde(rename = "evidence[service_documentation]")]
pub service_documentation: Option<String>,
#[serde(rename = "evidence[shipping_address]")]
pub shipping_address: Option<Secret<String>>,
#[serde(rename = "evidence[shipping_carrier]")]
pub shipping_carrier: Option<String>,
#[serde(rename = "evidence[shipping_date]")]
pub shipping_date: Option<String>,
#[serde(rename = "evidence[shipping_documentation]")]
pub shipping_documentation: Option<Secret<String>>,
#[serde(rename = "evidence[shipping_tracking_number]")]
pub shipping_tracking_number: Option<Secret<String>>,
#[serde(rename = "evidence[uncategorized_file]")]
pub uncategorized_file: Option<String>,
#[serde(rename = "evidence[uncategorized_text]")]
pub uncategorized_text: Option<String>,
pub submit: bool,
}
// Mandates for bank redirects - ideal happens through sepa direct debit in stripe
fn mandatory_parameters_for_sepa_bank_debit_mandates(
billing_details: &Option<StripeBillingAddress>,
is_customer_initiated_mandate_payment: Option<bool>,
) -> Result<StripeBillingAddress, ConnectorError> {
let billing_name = billing_details
.clone()
.and_then(|billing_data| billing_data.name.clone());
let billing_email = billing_details
.clone()
.and_then(|billing_data| billing_data.email.clone());
match is_customer_initiated_mandate_payment {
Some(true) => Ok(StripeBillingAddress {
name: Some(billing_name.ok_or(ConnectorError::MissingRequiredField {
field_name: "billing_name",
})?),
email: Some(billing_email.ok_or(ConnectorError::MissingRequiredField {
| {
"chunk": 33,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_34 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
field_name: "billing_email",
})?),
..StripeBillingAddress::default()
}),
Some(false) | None => Ok(StripeBillingAddress {
name: billing_name,
email: billing_email,
..StripeBillingAddress::default()
}),
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct DisputeObj {
#[serde(rename = "id")]
pub dispute_id: String,
pub status: String,
}
fn get_transaction_metadata(
merchant_metadata: Option<Secret<Value>>,
order_id: String,
) -> HashMap<String, String> {
let mut meta_data = HashMap::from([("metadata[order_id]".to_string(), order_id)]);
let mut request_hash_map = HashMap::new();
if let Some(metadata) = merchant_metadata {
let hashmap: HashMap<String, Value> =
serde_json::from_str(&metadata.peek().to_string()).unwrap_or(HashMap::new());
for (key, value) in hashmap {
request_hash_map.insert(format!("metadata[{key}]"), value.to_string());
}
meta_data.extend(request_hash_map)
};
meta_data
}
fn get_stripe_payments_response_data(
response: &Option<ErrorDetails>,
http_code: u16,
response_id: String,
) -> Box<Result<PaymentsResponseData, domain_types::router_data::ErrorResponse>> {
let (code, error_message) = match response {
Some(error_details) => (
error_details
.code
.to_owned()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
error_details
.message
.to_owned()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
),
None => (
consts::NO_ERROR_CODE.to_string(),
consts::NO_ERROR_MESSAGE.to_string(),
),
};
Box::new(Err(domain_types::router_data::ErrorResponse {
code,
message: error_message.clone(),
reason: response.clone().and_then(|res| {
res.decline_code
.clone()
.map(|decline_code| {
format!("message - {error_message}, decline_code - {decline_code}")
})
.or(Some(error_message.clone()))
}),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(response_id),
network_advice_code: response
.as_ref()
.and_then(|res| res.network_advice_code.clone()),
network_decline_code: response
.as_ref()
.and_then(|res| res.network_decline_code.clone()),
network_error_message: response
.as_ref()
.and_then(|res| res.decline_code.clone().or(res.advice_code.clone())),
}))
}
pub fn construct_charge_response<T>(
charge_id: String,
request: &T,
) -> Option<domain_types::connector_types::ConnectorChargeResponseData>
where
T: SplitPaymentData,
{
let charge_request = request.get_split_payment_data();
if let Some(domain_types::connector_types::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) = charge_request
{
let stripe_charge_response = domain_types::connector_types::StripeChargeResponseData {
charge_id: Some(charge_id),
charge_type: stripe_split_payment.charge_type,
application_fees: stripe_split_payment.application_fees,
transfer_account_id: stripe_split_payment.transfer_account_id,
};
Some(
domain_types::connector_types::ConnectorChargeResponseData::StripeSplitPayment(
stripe_charge_response,
),
)
} else {
None
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
&RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
> for StripeSplitPaymentRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
_item: &RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
charge_type: None,
transfer_account_id: None,
| {
"chunk": 34,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_35 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
application_fees: None,
})
}
}
pub(super) fn transform_headers_for_connect_platform(
charge_type: common_enums::PaymentChargeType,
transfer_account_id: Secret<String>,
header: &mut Vec<(String, Maskable<String>)>,
) {
if let common_enums::PaymentChargeType::Stripe(common_enums::StripeChargeType::Direct) =
charge_type
{
let mut customer_account_header = vec![(
STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
transfer_account_id.into_masked(),
)];
header.append(&mut customer_account_header);
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaymentSyncResponse {
PaymentIntentSyncResponse(PaymentIntentSyncResponse),
SetupMandateResponse(SetupMandateResponse),
}
impl<F> TryFrom<ResponseRouterData<PaymentSyncResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<PaymentSyncResponse, Self>) -> Result<Self, Self::Error> {
let id = item.router_data.request.connector_transaction_id.clone();
match id.get_connector_transaction_id() {
Ok(x) if x.starts_with("set") => match item.response {
PaymentSyncResponse::SetupMandateResponse(setup_intent_response) => {
RouterDataV2::try_from(ResponseRouterData {
response: setup_intent_response,
router_data: item.router_data,
http_code: item.http_code,
})
}
_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
},
Ok(_) => match item.response {
PaymentSyncResponse::PaymentIntentSyncResponse(payment_intent_sync_response) => {
RouterDataV2::try_from(ResponseRouterData {
response: payment_intent_sync_response,
router_data: item.router_data,
http_code: item.http_code,
})
}
_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
},
Err(err) => Err(err).change_context(ConnectorError::MissingConnectorTransactionID),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentsAuthorizeResponse(PaymentIntentResponse);
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<PaymentsAuthorizeResponse, Self>>
for RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<PaymentsAuthorizeResponse, Self>,
) -> Result<Self, Self::Error> {
let currency_enum =
common_enums::Currency::from_str(item.response.0.currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let amount_in_minor_unit =
StripeAmountConvertor::convert_back(item.response.0.amount, currency_enum)?;
let response_integrity_object = AuthoriseIntegrityObject {
amount: amount_in_minor_unit,
currency: currency_enum,
};
let new_router_data = RouterDataV2::try_from(ResponseRouterData {
response: item.response.0,
router_data: item.router_data,
http_code: item.http_code,
})
.change_context(ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentsCaptureResponse(PaymentIntentResponse);
impl TryFrom<ResponseRouterData<PaymentsCaptureResponse, Self>>
for RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<PaymentsCaptureResponse, Self>,
| {
"chunk": 35,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_36 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
) -> Result<Self, Self::Error> {
let currency_enum =
common_enums::Currency::from_str(item.response.0.currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let capture_amount_in_minor_unit = item
.response
.0
.amount_received
.map(|amount| StripeAmountConvertor::convert_back(amount, currency_enum))
.transpose()?;
let response_integrity_object =
capture_amount_in_minor_unit.map(|amount_to_capture| CaptureIntegrityObject {
amount_to_capture,
currency: currency_enum,
});
let new_router_data = RouterDataV2::try_from(ResponseRouterData {
response: item.response.0,
router_data: item.router_data,
http_code: item.http_code,
})
.change_context(ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = response_integrity_object;
router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentsVoidResponse(PaymentIntentResponse);
impl TryFrom<ResponseRouterData<PaymentsVoidResponse, Self>>
for RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<PaymentsVoidResponse, Self>) -> Result<Self, Self::Error> {
RouterDataV2::try_from(ResponseRouterData {
response: item.response.0,
router_data: item.router_data,
http_code: item.http_code,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
StripeRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
> for CancelRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: StripeRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
cancellation_reason: item.router_data.request.cancellation_reason.clone(),
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
StripeRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for CaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: StripeRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let amount_to_capture = StripeAmountConvertor::convert(
item.router_data.request.minor_amount_to_capture,
item.router_data.request.currency,
)?;
Ok(Self {
amount_to_capture: Some(amount_to_capture),
})
}
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum StripeRefundRequest {
RefundRequest(RefundRequest),
ChargeRefundRequest(ChargeRefundRequest),
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<StripeRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>>
for StripeRefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: StripeRouterData<
RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let refund_amount = StripeAmountConvertor::convert(
item.router_data.request.minor_refund_amount,
item.router_data.request.currency,
)?;
match item.router_data.request.split_refunds.as_ref() {
| {
"chunk": 36,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_37 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
Some(domain_types::connector_types::SplitRefundsRequest::StripeSplitRefund(_)) => {
Ok(StripeRefundRequest::ChargeRefundRequest(
ChargeRefundRequest::try_from(&item.router_data)?,
))
}
_ => Ok(StripeRefundRequest::RefundRequest(RefundRequest::try_from(
(&item.router_data, refund_amount),
)?)),
}
}
}
impl<F>
TryFrom<(
&RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
MinorUnit,
)> for RefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(item, refund_amount): (
&RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
MinorUnit,
),
) -> Result<Self, Self::Error> {
let payment_intent = item.request.connector_transaction_id.clone();
Ok(Self {
amount: Some(refund_amount),
payment_intent,
meta_data: StripeMetadata {
order_id: Some(item.request.refund_id.clone()),
is_refund_id_as_reference: Some("true".to_string()),
},
})
}
}
impl<F> TryFrom<&RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>>
for ChargeRefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let amount = item.request.minor_refund_amount;
match item.request.split_refunds.as_ref() {
None => Err(ConnectorError::MissingRequiredField {
field_name: "split_refunds",
}
.into()),
Some(split_refunds) => match split_refunds {
domain_types::connector_types::SplitRefundsRequest::StripeSplitRefund(
stripe_refund,
) => {
let (refund_application_fee, reverse_transfer) = match &stripe_refund.options {
domain_types::connector_types::ChargeRefundsOptions::Direct(
domain_types::connector_types::DirectChargeRefund {
revert_platform_fee,
},
) => (Some(*revert_platform_fee), None),
domain_types::connector_types::ChargeRefundsOptions::Destination(
domain_types::connector_types::DestinationChargeRefund {
revert_platform_fee,
revert_transfer,
},
) => (Some(*revert_platform_fee), Some(*revert_transfer)),
};
Ok(Self {
charge: stripe_refund.charge_id.clone(),
refund_application_fee,
reverse_transfer,
amount: Some(amount),
meta_data: StripeMetadata {
order_id: Some(item.request.refund_id.clone()),
is_refund_id_as_reference: Some("true".to_string()),
},
})
}
},
}
}
}
impl<F> TryFrom<ResponseRouterData<RefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundResponse, Self>) -> Result<Self, Self::Error> {
let refund_status = common_enums::RefundStatus::from(item.response.status);
let response = if is_refund_failure(refund_status) {
Err(domain_types::router_data::ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: item
.response
.failure_reason
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.failure_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.id),
network_advice_code: None,
| {
"chunk": 37,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_38 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
status_code: item.http_code,
})
};
let currency_enum =
common_enums::Currency::from_str(item.response.currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let refund_amount_in_minor_unit =
StripeAmountConvertor::convert_back(item.response.amount, currency_enum)?;
let response_integrity_object = RefundIntegrityObject {
currency: currency_enum,
refund_amount: refund_amount_in_minor_unit,
};
Ok(Self {
response,
request: RefundsData {
integrity_object: Some(response_integrity_object),
..item.router_data.request
},
..item.router_data
})
}
}
impl<F> TryFrom<ResponseRouterData<RefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundResponse, Self>) -> Result<Self, Self::Error> {
let refund_status = common_enums::RefundStatus::from(item.response.status);
let response = if is_refund_failure(refund_status) {
Err(domain_types::router_data::ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: item
.response
.failure_reason
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.failure_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
status_code: item.http_code,
})
};
Ok(Self {
response,
..item.router_data
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
StripeRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
> for SetupMandateRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: StripeRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
//Only cards supported for mandates
let pm_type = StripePaymentMethodType::Card;
let payment_data = StripePaymentMethodData::try_from((
&item,
item.router_data.resource_common_data.auth_type,
pm_type,
))?;
let meta_data = Some(get_transaction_metadata(
item.router_data.request.metadata.clone().map(Into::into),
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
));
let browser_info = item
.router_data
.request
.browser_info
.clone()
.map(StripeBrowserInformation::from);
Ok(Self {
confirm: true,
payment_data,
return_url: item.router_data.request.router_return_url.clone(),
off_session: item.router_data.request.off_session,
usage: item.router_data.request.setup_future_usage,
payment_method_options: None,
customer: item
.router_data
| {
"chunk": 38,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_39 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
.resource_common_data
.connector_customer
.to_owned()
.map(Secret::new),
meta_data,
payment_method_types: Some(pm_type),
expand: Some(ExpandableObjects::LatestAttempt),
browser_info,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&StripeRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
common_enums::AuthenticationType,
StripePaymentMethodType,
)> for StripePaymentMethodData<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(item, auth_type, pm_type): (
&StripeRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
common_enums::AuthenticationType,
StripePaymentMethodType,
),
) -> Result<Self, Self::Error> {
let pm_data = &item.router_data.request.payment_method_data;
match pm_data {
PaymentMethodData::Card(ref ccard) => {
let payment_method_auth_type = match auth_type {
common_enums::AuthenticationType::ThreeDs => Auth3ds::Any,
common_enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic,
};
Ok(Self::try_from((
ccard,
payment_method_auth_type,
item.router_data.request.request_incremental_authorization,
None,
None,
))?)
}
PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData {
payment_method_data_type: pm_type,
})),
PaymentMethodData::BankRedirect(ref bank_redirect_data) => {
Ok(Self::try_from(bank_redirect_data)?)
}
PaymentMethodData::Wallet(ref wallet_data) => Ok(Self::try_from((wallet_data, None))?),
PaymentMethodData::BankDebit(bank_debit_data) => {
let (_pm_type, bank_data) = get_bank_debit_data(bank_debit_data);
Ok(Self::BankDebit(StripeBankDebitData {
bank_specific_data: bank_data,
}))
}
PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data.deref()
{
payment_method_data::BankTransferData::AchBankTransfer {} => {
Ok(Self::BankTransfer(StripeBankTransferData::AchBankTransfer(
Box::new(AchTransferData {
payment_method_data_type: StripePaymentMethodType::CustomerBalance,
bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer,
payment_method_type: StripePaymentMethodType::CustomerBalance,
balance_funding_type: BankTransferType::BankTransfers,
}),
)))
}
payment_method_data::BankTransferData::MultibancoBankTransfer {} => Ok(
Self::BankTransfer(StripeBankTransferData::MultibancoBankTransfers(Box::new(
MultibancoTransferData {
payment_method_data_type: StripeCreditTransferTypes::Multibanco,
payment_method_type: StripeCreditTransferTypes::Multibanco,
email: item.router_data.resource_common_data.get_billing_email()?,
},
))),
),
payment_method_data::BankTransferData::SepaBankTransfer {} => {
Ok(Self::BankTransfer(
StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData {
| {
"chunk": 39,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_40 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
payment_method_data_type: StripePaymentMethodType::CustomerBalance,
bank_transfer_type: BankTransferType::EuBankTransfer,
balance_funding_type: BankTransferType::BankTransfers,
payment_method_type: StripePaymentMethodType::CustomerBalance,
country: item
.router_data
.resource_common_data
.get_billing_country()?,
})),
))
}
payment_method_data::BankTransferData::BacsBankTransfer { .. } => {
Ok(Self::BankTransfer(
StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData {
payment_method_data_type: StripePaymentMethodType::CustomerBalance,
bank_transfer_type: BankTransferType::GbBankTransfer,
balance_funding_type: BankTransferType::BankTransfers,
payment_method_type: StripePaymentMethodType::CustomerBalance,
})),
))
}
payment_method_data::BankTransferData::Pix { .. }
| payment_method_data::BankTransferData::Pse {}
| payment_method_data::BankTransferData::PermataBankTransfer { .. }
| payment_method_data::BankTransferData::BcaBankTransfer { .. }
| payment_method_data::BankTransferData::BniVaBankTransfer { .. }
| payment_method_data::BankTransferData::BriVaBankTransfer { .. }
| payment_method_data::BankTransferData::CimbVaBankTransfer { .. }
| payment_method_data::BankTransferData::DanamonVaBankTransfer { .. }
| payment_method_data::BankTransferData::LocalBankTransfer { .. }
| payment_method_data::BankTransferData::InstantBankTransfer {}
| payment_method_data::BankTransferData::InstantBankTransferFinland {}
| payment_method_data::BankTransferData::InstantBankTransferPoland {}
| payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into())
}
},
PaymentMethodData::MandatePayment
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
))?
}
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
StripeRouterData<
RouterDataV2<
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
ConnectorCustomerResponse,
>,
T,
>,
> for CreateConnectorCustomerRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: StripeRouterData<
RouterDataV2<
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
ConnectorCustomerResponse,
>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
description: item.router_data.request.description.to_owned(),
email: item
| {
"chunk": 40,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_41 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
.router_data
.request
.email
.map(|email| email.peek().to_owned()),
phone: item.router_data.request.phone.to_owned(),
name: item.router_data.request.name.to_owned(),
source: item
.router_data
.request
.preprocessing_id
.to_owned()
.map(Secret::new),
})
}
}
impl<F, T> TryFrom<ResponseRouterData<CreateConnectorCustomerResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, ConnectorCustomerResponse>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CreateConnectorCustomerResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(ConnectorCustomerResponse {
connector_customer_id: item.response.id,
}),
..item.router_data
})
}
}
impl TryFrom<&RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>>
for StripeSplitPaymentRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &RouterDataV2<
RepeatPayment,
PaymentFlowData,
RepeatPaymentData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
//extracting mandate metadata from CIT call if CIT call was a Split Payment
let from_metadata = match &item
.request
.mandate_reference {
MandateReferenceId::ConnectorMandateId(mandate_data) => {
mandate_data.get_mandate_metadata()
}
_ => None,
}
.and_then(|secret_value| {
let json_value = secret_value.clone().expose();
match serde_json::from_value::<Self>(json_value.clone()) {
Ok(val) => Some(val),
Err(err) => {
tracing::info!(
"STRIPE: Picking merchant_account_id and merchant_config_currency from payments request: {:?}", err
);
None
}
}
});
// If the Split Payment Request in MIT mismatches with the metadata from CIT, throw an error
if from_metadata.is_some() && item.request.split_payments.is_some() {
let mut mit_charge_type = None;
let mut mit_application_fees = None;
let mut mit_transfer_account_id = None;
if let Some(domain_types::connector_types::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) = item.request.split_payments.as_ref()
{
mit_charge_type = Some(stripe_split_payment.charge_type.clone());
mit_application_fees = stripe_split_payment.application_fees;
mit_transfer_account_id = Some(stripe_split_payment.transfer_account_id.clone());
}
if mit_charge_type != from_metadata.as_ref().and_then(|m| m.charge_type.clone())
|| mit_application_fees != from_metadata.as_ref().and_then(|m| m.application_fees)
|| mit_transfer_account_id
!= from_metadata
.as_ref()
.and_then(|m| m.transfer_account_id.clone().map(|s| s.expose()))
{
let mismatched_fields = ["transfer_account_id", "application_fees", "charge_type"];
let field_str = mismatched_fields.join(", ");
Err(ConnectorError::MandatePaymentDataMismatch { fields: field_str })?
}
}
// If Mandate Metadata from CIT call has something, populate it
let (charge_type, mut transfer_account_id, application_fees) =
if let Some(ref metadata) = from_metadata {
(
metadata.charge_type.clone(),
metadata.transfer_account_id.clone(),
metadata.application_fees,
)
} else {
(None, None, None)
};
// If Charge Type is Destination, transfer_account_id need not be appended in headers
| {
"chunk": 41,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_42 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
if charge_type
== Some(common_enums::PaymentChargeType::Stripe(
common_enums::StripeChargeType::Destination,
))
{
transfer_account_id = None;
}
Ok(Self {
charge_type,
transfer_account_id,
application_fees,
})
}
}
impl TryFrom<ResponseRouterData<PaymentsAuthorizeResponse, Self>>
for RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<PaymentsAuthorizeResponse, Self>,
) -> Result<Self, Self::Error> {
RouterDataV2::try_from(ResponseRouterData {
response: item.response.0,
router_data: item.router_data,
http_code: item.http_code,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
StripeRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
> for PaymentIntentRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
value: StripeRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let item = value.router_data;
let mandate_metadata = match &item.request.mandate_reference {
MandateReferenceId::ConnectorMandateId(mandate_data) => {
Some(mandate_data.get_mandate_metadata())
}
_ => None,
};
let (transfer_account_id, charge_type, application_fees) =
match mandate_metadata.as_ref().and_then(|s| s.as_ref()) {
Some(secret_value) => {
let json_value = secret_value.clone().expose();
let parsed: Result<StripeSplitPaymentRequest, _> =
serde_json::from_value(json_value);
match parsed {
Ok(data) => (
data.transfer_account_id,
data.charge_type,
data.application_fees,
),
Err(_) => (None, None, None),
}
}
None => (None, None, None),
};
let payment_method_token = match &item.request.split_payments {
Some(domain_types::connector_types::SplitPaymentsRequest::StripeSplitPayment(_)) => {
match item.resource_common_data.payment_method_token.clone() {
Some(domain_types::router_data::PaymentMethodToken::Token(secret)) => {
Some(secret)
}
_ => None,
}
}
_ => None,
};
let amount =
StripeAmountConvertor::convert(item.request.minor_amount, item.request.currency)?;
let order_id = item
.resource_common_data
.connector_request_reference_id
.clone();
let shipping_address = match payment_method_token {
Some(_) => None,
None => Some(StripeShippingAddress {
city: item.resource_common_data.get_optional_shipping_city(),
country: item.resource_common_data.get_optional_shipping_country(),
line1: item.resource_common_data.get_optional_shipping_line1(),
line2: item.resource_common_data.get_optional_shipping_line2(),
zip: item.resource_common_data.get_optional_shipping_zip(),
state: item.resource_common_data.get_optional_shipping_state(),
name: item.resource_common_data.get_optional_shipping_full_name(),
phone: item
.resource_common_data
.get_optional_shipping_phone_number(),
}),
};
let (
mut payment_data,
payment_method,
billing_address,
payment_method_types,
setup_future_usage,
| {
"chunk": 42,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_43 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
) = if payment_method_token.is_some() {
(None, None, StripeBillingAddress::default(), None, None)
} else {
match &item.request.mandate_reference {
MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => (
None,
connector_mandate_ids.get_connector_mandate_id(),
StripeBillingAddress::default(),
get_payment_method_type_for_saved_payment_method_payment(&item)?,
None,
),
MandateReferenceId::NetworkMandateId(_)
| MandateReferenceId::NetworkTokenWithNTI(_) => {
Err(ConnectorError::NotSupported {
message: "This Mandate type is not yet supported".to_string(),
connector: "Stripe",
})?
}
}
};
if payment_method_token.is_some() {
payment_data = None
};
let meta_data = get_transaction_metadata(item.request.metadata.clone(), order_id);
// We pass browser_info only when payment_data exists.
// Hence, we're pass Null during recurring payments as payment_method_data[type] is not passed
let browser_info = if payment_data.is_some() && payment_method_token.is_none() {
item.request
.browser_info
.clone()
.map(StripeBrowserInformation::from)
} else {
None
};
let charges = match &item.request.split_payments {
Some(domain_types::connector_types::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) => match &stripe_split_payment.charge_type {
common_enums::PaymentChargeType::Stripe(charge_type) => match charge_type {
common_enums::StripeChargeType::Direct => Some(IntentCharges {
application_fee_amount: stripe_split_payment.application_fees,
destination_account_id: None,
}),
common_enums::StripeChargeType::Destination => Some(IntentCharges {
application_fee_amount: stripe_split_payment.application_fees,
destination_account_id: Some(Secret::new(
stripe_split_payment.transfer_account_id.clone(),
)),
}),
},
},
None => None,
};
let charges_in = if charges.is_none() {
match charge_type {
Some(common_enums::PaymentChargeType::Stripe(
common_enums::StripeChargeType::Direct,
)) => Some(IntentCharges {
application_fee_amount: application_fees, // default to 0 if None
destination_account_id: None,
}),
Some(common_enums::PaymentChargeType::Stripe(
common_enums::StripeChargeType::Destination,
)) => Some(IntentCharges {
application_fee_amount: application_fees,
destination_account_id: transfer_account_id,
}),
_ => None,
}
} else {
charges
};
let pm = match (payment_method, payment_method_token.clone()) {
(Some(method), _) => Some(Secret::new(method)),
(None, Some(token)) => Some(token),
(None, None) => None,
};
Ok(Self {
amount, //hopefully we don't loose some cents here
currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership
statement_descriptor_suffix: None,
statement_descriptor: None,
meta_data,
return_url: item
.request
.router_return_url
.clone()
.unwrap_or_else(|| "https://juspay.in/".to_string()),
confirm: true, // Stripe requires confirm to be true if return URL is present
description: item.resource_common_data.description.clone(),
shipping: shipping_address,
| {
"chunk": 43,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-239682093767531356_44 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/stripe/transformers.rs
billing: billing_address,
capture_method: StripeCaptureMethod::from(item.request.capture_method),
payment_data,
payment_method_options: None,
payment_method: pm,
customer: item
.resource_common_data
.connector_customer
.clone()
.map(Secret::new),
setup_mandate_details: None,
off_session: item.request.off_session,
setup_future_usage,
payment_method_types,
expand: Some(ExpandableObjects::LatestCharge),
browser_info,
charges: charges_in,
})
}
}
fn get_payment_method_type_for_saved_payment_method_payment(
item: &RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
) -> Result<Option<StripePaymentMethodType>, error_stack::Report<ConnectorError>> {
if item.resource_common_data.payment_method == common_enums::PaymentMethod::Card {
Ok(Some(StripePaymentMethodType::Card)) //stripe takes ["Card"] as default
} else {
let stripe_payment_method_type = match item
.resource_common_data
.recurring_mandate_payment_data
.clone()
{
Some(recurring_payment_method_data) => {
match recurring_payment_method_data.payment_method_type {
Some(payment_method_type) => {
StripePaymentMethodType::try_from(payment_method_type)
}
None => Err(ConnectorError::MissingRequiredField {
field_name: "payment_method_type",
}
.into()),
}
}
None => Err(ConnectorError::MissingRequiredField {
field_name: "recurring_mandate_payment_data",
}
.into()),
}?;
match stripe_payment_method_type {
//Stripe converts Ideal, Bancontact & Sofort Bank redirect methods to Sepa direct debit and attaches to the customer for future usage
StripePaymentMethodType::Ideal
| StripePaymentMethodType::Bancontact
| StripePaymentMethodType::Sofort => Ok(Some(StripePaymentMethodType::Sepa)),
_ => Ok(Some(stripe_payment_method_type)),
}
}
}
| {
"chunk": 44,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_connector-integration_-8421620542795988629_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/utils/xml_utils.rs
use bytes::Bytes;
use domain_types::errors;
use serde_json::{Map, Value};
/// Processes XML response bytes by converting to properly structured JSON.
///
/// This function:
/// 1. Takes XML data as `Bytes` input
/// 2. Converts it to a UTF-8 string and trims whitespace
/// 3. Checks for XML declarations and removes them if present
/// 4. Parses the XML into a JSON structure
/// 5. Flattens nested "$text" fields to create a clean key-value structure
/// 6. Returns the processed JSON data as `Bytes`
pub fn preprocess_xml_response_bytes(xml_data: Bytes) -> Result<Bytes, errors::ConnectorError> {
// Log raw bytes for debugging
tracing::info!(bytes=?xml_data, "Raw XML bytes received for preprocessing");
// Convert to UTF-8 string
let response_str = std::str::from_utf8(&xml_data)
.map_err(|_| errors::ConnectorError::ResponseDeserializationFailed)?
.trim();
// Handle XML declarations by removing them if present
let cleaned_response = if response_str.starts_with("<?xml") {
// Find the end of the XML declaration and skip it
match response_str.find("?>") {
Some(pos) => {
let substring = &response_str[pos + 2..];
let cleaned = substring.trim();
tracing::info!("Removed XML declaration: {}", cleaned);
cleaned
}
None => {
tracing::warn!("XML declaration start found but no closing '?>' tag");
response_str
}
}
} else {
tracing::info!("No XML declaration found, using as-is");
response_str
};
// Ensure the XML has a txn wrapper if needed
let final_xml = if !cleaned_response.starts_with("<txn>")
&& (cleaned_response.contains("<ssl_") || cleaned_response.contains("<error"))
{
format!("<txn>{cleaned_response}</txn>")
} else {
cleaned_response.to_string()
};
// Parse XML to a generic JSON Value
let json_value: Value = match quick_xml::de::from_str(&final_xml) {
Ok(val) => {
tracing::info!("Successfully converted XML to JSON structure");
val
}
Err(err) => {
tracing::error!(error=?err, "Failed to parse XML to JSON structure");
// Create a basic JSON structure with error information
return Err(errors::ConnectorError::ResponseDeserializationFailed);
}
};
// Extract and flatten the JSON structure
let flattened_json = flatten_json_structure(json_value);
// Convert JSON Value to string and then to bytes
let json_string = serde_json::to_string(&flattened_json).map_err(|e| {
tracing::error!(error=?e, "Failed to convert to JSON string");
errors::ConnectorError::ResponseDeserializationFailed
})?;
tracing::info!(json=?json_string, "Flattened JSON structure");
// Return JSON as bytes
Ok(Bytes::from(json_string.into_bytes()))
}
/// Flattens a nested JSON structure, extracting values from "$text" fields
pub fn flatten_json_structure(json_value: Value) -> Value {
let mut flattened = Map::new();
// Extract txn object if present
let txn_obj = if let Some(obj) = json_value.as_object() {
if let Some(txn) = obj.get("txn") {
txn.as_object()
} else {
Some(obj)
}
} else {
None
};
// Process the fields
if let Some(obj) = txn_obj {
for (key, value) in obj {
// Handle nested "$text" fields
if let Some(value_obj) = value.as_object() {
if let Some(text_value) = value_obj.get("$text") {
// Extract the value from "$text" field
flattened.insert(key.clone(), text_value.clone());
} else if value_obj.is_empty() {
// Empty object, insert empty string
flattened.insert(key.clone(), Value::String("".to_string()));
} else {
// Use the value as is
flattened.insert(key.clone(), value.clone());
}
} else {
// Use the value as is
flattened.insert(key.clone(), value.clone());
}
}
}
Value::Object(flattened)
}
| {
"chunk": 0,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_5501410502799828961_0 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/lib.rs
//! A Kafka tracing layer that integrates with the tracing ecosystem.
//!
//! This crate provides a simple way to send tracing logs to Kafka while maintaining
//! consistent JSON formatting through the log_utils infrastructure.
//!
//! # Examples
//! ```no_run
//! use tracing_kafka::KafkaLayer;
//! use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
//!
//! let kafka_layer = KafkaLayer::builder()
//! .brokers(&["localhost:9092"])
//! .topic("application-logs")
//! .build()
//! .expect("Failed to create Kafka layer");
//!
//! tracing_subscriber::registry()
//! .with(kafka_layer)
//! .init();
//! ```
//!
//! # Publishing Custom Events
//!
//! In addition to logging, the `KafkaWriter` can be used to publish custom events to Kafka.
//! The `publish_event` method allows you to send a payload to a specific topic with an optional key and headers.
//!
//! ```no_run
//! use tracing_kafka::KafkaWriter;
//! use rdkafka::message::OwnedHeaders;
//!
//! let writer = KafkaWriter::new(
//! vec!["localhost:9092".to_string()],
//! "default-topic".to_string(),
//! None, None, None, None, None, None
//! ).expect("Failed to create KafkaWriter");
//!
//! let headers = OwnedHeaders::new().add("my-header", "my-value");
//!
//! let result = writer.publish_event(
//! "custom-events",
//! Some("event-key"),
//! b"event-payload",
//! Some(headers),
//! );
//!
//! if let Err(e) = result {
//! eprintln!("Failed to publish event: {}", e);
//! }
//! ```
pub mod builder;
mod layer;
mod writer;
pub use layer::{KafkaLayer, KafkaLayerError};
pub use writer::{KafkaWriter, KafkaWriterError};
#[cfg(feature = "kafka-metrics")]
mod metrics;
/// Initializes the metrics for the tracing kafka.
/// This function should be called once at application startup.
#[cfg(feature = "kafka-metrics")]
pub fn init() {
metrics::initialize_all_metrics();
}
#[cfg(not(feature = "kafka-metrics"))]
pub fn init() {
tracing::warn!("Kafka metrics feature is not enabled. Metrics will not be collected.");
}
| {
"chunk": 0,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_863436229918585844_0 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/metrics.rs
//! Prometheus metrics for Kafka writer
use std::sync::LazyLock;
use prometheus::{register_int_counter, register_int_gauge, IntCounter, IntGauge};
/// Total number of logs successfully sent to Kafka
#[allow(clippy::expect_used)]
pub static KAFKA_LOGS_SENT: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_logs_sent_total",
"Total number of logs successfully sent to Kafka"
)
.expect("Failed to register kafka_logs_sent_total metric")
});
/// Total number of logs dropped due to Kafka queue full or errors
#[allow(clippy::expect_used)]
pub static KAFKA_LOGS_DROPPED: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_logs_dropped_total",
"Total number of logs dropped due to Kafka queue full or errors"
)
.expect("Failed to register kafka_logs_dropped_total metric")
});
/// Current size of Kafka producer queue
#[allow(clippy::expect_used)]
pub static KAFKA_QUEUE_SIZE: LazyLock<IntGauge> = LazyLock::new(|| {
register_int_gauge!(
"kafka_producer_queue_size",
"Current size of Kafka producer queue"
)
.expect("Failed to register kafka_producer_queue_size metric")
});
/// Logs dropped due to queue full
#[allow(clippy::expect_used)]
pub static KAFKA_DROPS_QUEUE_FULL: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_drops_queue_full_total",
"Total number of logs dropped due to Kafka queue being full"
)
.expect("Failed to register kafka_drops_queue_full_total metric")
});
/// Logs dropped due to message too large
#[allow(clippy::expect_used)]
pub static KAFKA_DROPS_MSG_TOO_LARGE: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_drops_msg_too_large_total",
"Total number of logs dropped due to message size exceeding limit"
)
.expect("Failed to register kafka_drops_msg_too_large_total metric")
});
/// Logs dropped due to timeout
#[allow(clippy::expect_used)]
pub static KAFKA_DROPS_TIMEOUT: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_drops_timeout_total",
"Total number of logs dropped due to timeout"
)
.expect("Failed to register kafka_drops_timeout_total metric")
});
/// Logs dropped due to other errors
#[allow(clippy::expect_used)]
pub static KAFKA_DROPS_OTHER: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_drops_other_total",
"Total number of logs dropped due to other errors"
)
.expect("Failed to register kafka_drops_other_total metric")
});
/// Total number of audit events successfully sent to Kafka
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_EVENTS_SENT: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_events_sent_total",
"Total number of audit events successfully sent to Kafka"
)
.expect("Failed to register kafka_audit_events_sent_total metric")
});
/// Total number of audit events dropped due to Kafka queue full or errors
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_EVENTS_DROPPED: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_events_dropped_total",
"Total number of audit events dropped due to Kafka queue full or errors"
)
.expect("Failed to register kafka_audit_events_dropped_total metric")
});
/// Current size of Kafka audit event producer queue
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_EVENT_QUEUE_SIZE: LazyLock<IntGauge> = LazyLock::new(|| {
register_int_gauge!(
"kafka_audit_event_queue_size",
"Current size of Kafka audit event producer queue"
)
.expect("Failed to register kafka_audit_event_queue_size metric")
});
/// Audit events dropped due to queue full
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_DROPS_QUEUE_FULL: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_drops_queue_full_total",
"Total number of audit events dropped due to Kafka queue being full"
)
.expect("Failed to register kafka_audit_drops_queue_full_total metric")
});
/// Audit events dropped due to message too large
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_DROPS_MSG_TOO_LARGE: LazyLock<IntCounter> = LazyLock::new(|| {
| {
"chunk": 0,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_863436229918585844_1 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/metrics.rs
register_int_counter!(
"kafka_audit_drops_msg_too_large_total",
"Total number of audit events dropped due to message size exceeding limit"
)
.expect("Failed to register kafka_audit_drops_msg_too_large_total metric")
});
/// Audit events dropped due to timeout
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_DROPS_TIMEOUT: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_drops_timeout_total",
"Total number of audit events dropped due to timeout"
)
.expect("Failed to register kafka_audit_drops_timeout_total metric")
});
/// Audit events dropped due to other errors
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_DROPS_OTHER: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_drops_other_total",
"Total number of audit events dropped due to other errors"
)
.expect("Failed to register kafka_audit_drops_other_total metric")
});
/// Forces the initialization of all metrics in this module.
///
/// This function should be called once at application startup to ensure that all metrics
/// are registered upfront. If any metric registration fails (e.g., due to a duplicate
/// metric name), the application will panic immediately.
#[cfg(feature = "kafka-metrics")]
pub fn initialize_all_metrics() {
// Force evaluation of all lazy metrics to fail fast if registration fails.
let _ = &*KAFKA_LOGS_SENT;
let _ = &*KAFKA_LOGS_DROPPED;
let _ = &*KAFKA_QUEUE_SIZE;
let _ = &*KAFKA_DROPS_QUEUE_FULL;
let _ = &*KAFKA_DROPS_MSG_TOO_LARGE;
let _ = &*KAFKA_DROPS_TIMEOUT;
let _ = &*KAFKA_DROPS_OTHER;
let _ = &*KAFKA_AUDIT_EVENTS_SENT;
let _ = &*KAFKA_AUDIT_EVENTS_DROPPED;
let _ = &*KAFKA_AUDIT_EVENT_QUEUE_SIZE;
let _ = &*KAFKA_AUDIT_DROPS_QUEUE_FULL;
let _ = &*KAFKA_AUDIT_DROPS_MSG_TOO_LARGE;
let _ = &*KAFKA_AUDIT_DROPS_TIMEOUT;
let _ = &*KAFKA_AUDIT_DROPS_OTHER;
}
| {
"chunk": 1,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_-8840925468162898005_0 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/writer.rs
//! Kafka writer implementation for sending formatted log messages to Kafka.
use std::{
io::{self, Write},
sync::Arc,
time::Duration,
};
use rdkafka::{
config::ClientConfig,
error::{KafkaError, RDKafkaErrorCode},
message::OwnedHeaders,
producer::{BaseRecord, DeliveryResult, Producer, ProducerContext, ThreadedProducer},
ClientContext,
};
#[cfg(feature = "kafka-metrics")]
use super::metrics::{
KAFKA_AUDIT_DROPS_MSG_TOO_LARGE, KAFKA_AUDIT_DROPS_OTHER, KAFKA_AUDIT_DROPS_QUEUE_FULL,
KAFKA_AUDIT_DROPS_TIMEOUT, KAFKA_AUDIT_EVENTS_DROPPED, KAFKA_AUDIT_EVENTS_SENT,
KAFKA_AUDIT_EVENT_QUEUE_SIZE, KAFKA_DROPS_MSG_TOO_LARGE, KAFKA_DROPS_OTHER,
KAFKA_DROPS_QUEUE_FULL, KAFKA_DROPS_TIMEOUT, KAFKA_LOGS_DROPPED, KAFKA_LOGS_SENT,
KAFKA_QUEUE_SIZE,
};
/// A `ProducerContext` that handles delivery callbacks to increment metrics.
#[derive(Clone)]
struct MetricsProducerContext;
impl ClientContext for MetricsProducerContext {}
impl ProducerContext for MetricsProducerContext {
type DeliveryOpaque = Box<KafkaMessageType>;
fn delivery(&self, delivery_result: &DeliveryResult<'_>, opaque: Self::DeliveryOpaque) {
let message_type = *opaque;
let is_success = delivery_result.is_ok();
#[cfg(feature = "kafka-metrics")]
{
match (message_type, is_success) {
(KafkaMessageType::Event, true) => KAFKA_AUDIT_EVENTS_SENT.inc(),
(KafkaMessageType::Event, false) => KAFKA_AUDIT_EVENTS_DROPPED.inc(),
(KafkaMessageType::Log, true) => KAFKA_LOGS_SENT.inc(),
(KafkaMessageType::Log, false) => KAFKA_LOGS_DROPPED.inc(),
}
}
if let Err((kafka_error, _)) = delivery_result {
#[cfg(feature = "kafka-metrics")]
match (message_type, &kafka_error) {
(
KafkaMessageType::Event,
KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull),
) => {
KAFKA_AUDIT_DROPS_QUEUE_FULL.inc();
}
(
KafkaMessageType::Event,
KafkaError::MessageProduction(RDKafkaErrorCode::MessageSizeTooLarge),
) => {
KAFKA_AUDIT_DROPS_MSG_TOO_LARGE.inc();
}
(
KafkaMessageType::Event,
KafkaError::MessageProduction(RDKafkaErrorCode::MessageTimedOut),
) => {
KAFKA_AUDIT_DROPS_TIMEOUT.inc();
}
(KafkaMessageType::Event, _) => {
KAFKA_AUDIT_DROPS_OTHER.inc();
}
(
KafkaMessageType::Log,
KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull),
) => {
KAFKA_DROPS_QUEUE_FULL.inc();
}
(
KafkaMessageType::Log,
KafkaError::MessageProduction(RDKafkaErrorCode::MessageSizeTooLarge),
) => {
KAFKA_DROPS_MSG_TOO_LARGE.inc();
}
(
KafkaMessageType::Log,
KafkaError::MessageProduction(RDKafkaErrorCode::MessageTimedOut),
) => {
KAFKA_DROPS_TIMEOUT.inc();
}
(KafkaMessageType::Log, _) => {
KAFKA_DROPS_OTHER.inc();
}
}
}
}
}
/// This enum helps the callback distinguish between logs and events.
#[derive(Clone, Copy, Debug)]
enum KafkaMessageType {
Event,
Log,
}
/// Kafka writer that implements std::io::Write for seamless integration with tracing
#[derive(Clone)]
pub struct KafkaWriter {
producer: Arc<ThreadedProducer<MetricsProducerContext>>,
topic: String,
}
impl std::fmt::Debug for KafkaWriter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("KafkaWriter")
.field("topic", &self.topic)
.finish()
}
}
impl KafkaWriter {
/// Creates a new KafkaWriter with the specified brokers and topic.
#[allow(clippy::too_many_arguments)]
pub fn new(
brokers: Vec<String>,
topic: String,
batch_size: Option<usize>,
| {
"chunk": 0,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_-8840925468162898005_1 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/writer.rs
linger_ms: Option<u64>,
queue_buffering_max_messages: Option<usize>,
queue_buffering_max_kbytes: Option<usize>,
reconnect_backoff_min_ms: Option<u64>,
reconnect_backoff_max_ms: Option<u64>,
) -> Result<Self, KafkaWriterError> {
let mut config = ClientConfig::new();
config.set("bootstrap.servers", brokers.join(","));
if let Some(min_backoff) = reconnect_backoff_min_ms {
config.set("reconnect.backoff.ms", min_backoff.to_string());
}
if let Some(max_backoff) = reconnect_backoff_max_ms {
config.set("reconnect.backoff.max.ms", max_backoff.to_string());
}
if let Some(max_messages) = queue_buffering_max_messages {
config.set("queue.buffering.max.messages", max_messages.to_string());
}
if let Some(max_kbytes) = queue_buffering_max_kbytes {
config.set("queue.buffering.max.kbytes", max_kbytes.to_string());
}
if let Some(size) = batch_size {
config.set("batch.size", size.to_string());
}
if let Some(ms) = linger_ms {
config.set("linger.ms", ms.to_string());
}
let producer: ThreadedProducer<MetricsProducerContext> = config
.create_with_context(MetricsProducerContext)
.map_err(KafkaWriterError::ProducerCreation)?;
producer
.client()
.fetch_metadata(Some(&topic), Duration::from_secs(5))
.map_err(KafkaWriterError::MetadataFetch)?;
Ok(Self {
producer: Arc::new(producer),
topic,
})
}
/// Publishes a single event to Kafka. This method is non-blocking.
/// Returns an error if the message cannot be enqueued to the producer's buffer.
pub fn publish_event(
&self,
topic: &str,
key: Option<&str>,
payload: &[u8],
headers: Option<OwnedHeaders>,
) -> Result<(), KafkaError> {
#[cfg(feature = "kafka-metrics")]
{
let queue_size = self.producer.in_flight_count();
KAFKA_AUDIT_EVENT_QUEUE_SIZE.set(queue_size.into());
}
let mut record = BaseRecord::with_opaque_to(topic, Box::new(KafkaMessageType::Event))
.payload(payload)
.timestamp(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis().try_into().unwrap_or(0))
.unwrap_or(0),
);
if let Some(k) = key {
record = record.key(k);
}
if let Some(h) = headers {
record = record.headers(h);
}
match self.producer.send(record) {
Ok(_) => Ok(()),
Err((kafka_error, _)) => {
#[cfg(feature = "kafka-metrics")]
{
KAFKA_AUDIT_EVENTS_DROPPED.inc();
// Only QUEUE_FULL can happen during send() - others happen during delivery
match &kafka_error {
KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull) => {
KAFKA_AUDIT_DROPS_QUEUE_FULL.inc();
}
_ => {
KAFKA_AUDIT_DROPS_OTHER.inc();
}
}
}
Err(kafka_error)
}
}
}
/// Creates a new builder for constructing a KafkaWriter
pub fn builder() -> crate::builder::KafkaWriterBuilder {
crate::builder::KafkaWriterBuilder::new()
}
}
impl Write for KafkaWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
#[cfg(feature = "kafka-metrics")]
{
let queue_size = self.producer.in_flight_count();
KAFKA_QUEUE_SIZE.set(queue_size.into());
}
let record = BaseRecord::with_opaque_to(&self.topic, Box::new(KafkaMessageType::Log))
.payload(buf)
.timestamp(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis().try_into().unwrap_or(0))
.unwrap_or(0),
);
| {
"chunk": 1,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_-8840925468162898005_2 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/writer.rs
if let Err((kafka_error, _)) = self.producer.send::<(), [u8]>(record) {
#[cfg(feature = "kafka-metrics")]
{
KAFKA_LOGS_DROPPED.inc();
match &kafka_error {
KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull) => {
KAFKA_DROPS_QUEUE_FULL.inc();
}
_ => {
KAFKA_DROPS_OTHER.inc();
}
}
}
}
// Return Ok to not block the application. The actual delivery result
// is handled by the callback in the background.
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.producer
.flush(rdkafka::util::Timeout::After(Duration::from_secs(5)))
.map_err(|e: KafkaError| io::Error::other(format!("Kafka flush failed: {e}")))
}
}
/// Errors that can occur when creating or using a KafkaWriter.
#[derive(Debug, thiserror::Error)]
pub enum KafkaWriterError {
#[error("Failed to create Kafka producer: {0}")]
ProducerCreation(KafkaError),
#[error("Failed to fetch Kafka metadata: {0}")]
MetadataFetch(KafkaError),
}
/// Make KafkaWriter compatible with tracing_appender's MakeWriter trait.
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for KafkaWriter {
type Writer = Self;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
/// Graceful shutdown - flush pending messages when dropping
impl Drop for KafkaWriter {
fn drop(&mut self) {
// Only flush if this is the last reference to the producer
if Arc::strong_count(&self.producer) == 1 {
// Try to flush pending messages with a 5 second timeout
let _ = self
.producer
.flush(rdkafka::util::Timeout::After(Duration::from_secs(5)));
}
}
}
| {
"chunk": 2,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_-6998519293309712771_0 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/layer.rs
//! Kafka layer implementation that reuses log_utils formatting.
use std::{
collections::{HashMap, HashSet},
time::Duration,
};
use log_utils::{
AdditionalFieldsPlacement, JsonFormattingLayer, JsonFormattingLayerConfig, LoggerError,
};
use tracing::Subscriber;
use tracing_subscriber::Layer;
use crate::{
builder::KafkaWriterBuilder,
writer::{KafkaWriter, KafkaWriterError},
};
/// Tracing layer that sends JSON-formatted logs to Kafka
///
/// Wraps log_utils' JsonFormattingLayer
pub struct KafkaLayer {
inner: JsonFormattingLayer<KafkaWriter, serde_json::ser::CompactFormatter>,
}
impl KafkaLayer {
/// Creates a new builder for configuring a KafkaLayer.
pub fn builder() -> KafkaLayerBuilder {
KafkaLayerBuilder::new()
}
/// Creates a new KafkaLayer from a pre-configured KafkaWriter.
/// This is primarily used internally by the builder.
pub(crate) fn from_writer(
kafka_writer: KafkaWriter,
static_fields: HashMap<String, serde_json::Value>,
) -> Result<Self, KafkaLayerError> {
let config = JsonFormattingLayerConfig {
static_top_level_fields: static_fields,
top_level_keys: HashSet::new(),
log_span_lifecycles: true,
additional_fields_placement: AdditionalFieldsPlacement::TopLevel,
};
let inner: JsonFormattingLayer<KafkaWriter, serde_json::ser::CompactFormatter> =
JsonFormattingLayer::new(config, kafka_writer, serde_json::ser::CompactFormatter)?;
Ok(Self { inner })
}
}
impl<S> Layer<S> for KafkaLayer
where
S: Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
{
fn on_event(&self, event: &tracing::Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_event(event, ctx);
}
fn on_new_span(
&self,
attrs: &tracing::span::Attributes<'_>,
id: &tracing::span::Id,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
self.inner.on_new_span(attrs, id, ctx);
}
fn on_enter(&self, id: &tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_enter(id, ctx);
}
fn on_exit(&self, id: &tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_exit(id, ctx);
}
fn on_close(&self, id: tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_close(id, ctx);
}
}
impl KafkaLayer {
/// Boxes the layer, making it easier to compose with other layers.
pub fn boxed<S>(self) -> Box<dyn Layer<S> + Send + Sync + 'static>
where
Self: Layer<S> + Sized + Send + Sync + 'static,
S: Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>,
{
Box::new(self)
}
}
/// Errors that can occur when creating a KafkaLayer.
#[derive(Debug, thiserror::Error)]
pub enum KafkaLayerError {
#[error("Kafka writer error: {0}")]
Writer(#[from] KafkaWriterError),
#[error("Logger configuration error: {0}")]
Logger(#[from] LoggerError),
#[error("Missing brokers configuration")]
MissingBrokers,
#[error("Missing topic configuration")]
MissingTopic,
}
/// Builder for creating a KafkaLayer with custom configuration.
#[derive(Debug, Clone, Default)]
pub struct KafkaLayerBuilder {
writer_builder: KafkaWriterBuilder,
static_fields: HashMap<String, serde_json::Value>,
}
impl KafkaLayerBuilder {
/// Creates a new builder with default settings.
pub fn new() -> Self {
Self::default()
}
/// Sets the Kafka brokers to connect to.
pub fn brokers(mut self, brokers: &[&str]) -> Self {
self.writer_builder = self
.writer_builder
.brokers(brokers.iter().map(|s| s.to_string()).collect());
self
}
/// Sets the Kafka topic to send logs to.
pub fn topic(mut self, topic: impl Into<String>) -> Self {
self.writer_builder = self.writer_builder.topic(topic);
self
}
/// Sets the batch size for buffering messages before sending.
pub fn batch_size(mut self, size: usize) -> Self {
self.writer_builder = self.writer_builder.batch_size(size);
self
}
/// Sets the linger time in milliseconds.
pub fn linger_ms(mut self, ms: u64) -> Self {
| {
"chunk": 0,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_-6998519293309712771_1 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/layer.rs
self.writer_builder = self.writer_builder.linger_ms(ms);
self
}
/// Sets the linger time as a Duration.
pub fn linger(mut self, duration: Duration) -> Self {
self.writer_builder = self.writer_builder.linger(duration);
self
}
/// Sets the maximum number of messages to buffer in the producer's queue.
pub fn queue_buffering_max_messages(mut self, size: usize) -> Self {
self.writer_builder = self.writer_builder.queue_buffering_max_messages(size);
self
}
/// Sets the maximum size of the producer's queue in kilobytes.
pub fn queue_buffering_max_kbytes(mut self, size: usize) -> Self {
self.writer_builder = self.writer_builder.queue_buffering_max_kbytes(size);
self
}
/// Sets the reconnect backoff times.
pub fn reconnect_backoff(mut self, min: Duration, max: Duration) -> Self {
self.writer_builder = self.writer_builder.reconnect_backoff(min, max);
self
}
/// Adds static fields that will be included in every log entry.
/// These fields are added at the top level of the JSON output.
pub fn static_fields(mut self, fields: HashMap<String, serde_json::Value>) -> Self {
self.static_fields = fields;
self
}
/// Adds a single static field that will be included in every log entry.
pub fn add_static_field(mut self, key: String, value: serde_json::Value) -> Self {
self.static_fields.insert(key, value);
self
}
/// Builds the KafkaLayer with the configured settings.
pub fn build(self) -> Result<KafkaLayer, KafkaLayerError> {
let kafka_writer = self.writer_builder.build()?;
KafkaLayer::from_writer(kafka_writer, self.static_fields)
}
}
| {
"chunk": 1,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_tracing-kafka_-7694171944301536872_0 | clm | mini_chunk | // connector-service/backend/tracing-kafka/src/builder.rs
//! Builder pattern implementation for KafkaWriter
use std::time::Duration;
use super::writer::{KafkaWriter, KafkaWriterError};
/// Builder for creating a KafkaWriter with custom configuration
#[derive(Debug, Clone, Default)]
pub struct KafkaWriterBuilder {
brokers: Option<Vec<String>>,
topic: Option<String>,
batch_size: Option<usize>,
linger_ms: Option<u64>,
queue_buffering_max_messages: Option<usize>,
queue_buffering_max_kbytes: Option<usize>,
reconnect_backoff_min_ms: Option<u64>,
reconnect_backoff_max_ms: Option<u64>,
}
impl KafkaWriterBuilder {
/// Creates a new builder with default settings
pub fn new() -> Self {
Self::default()
}
/// Sets the Kafka brokers to connect to
pub fn brokers(mut self, brokers: Vec<String>) -> Self {
self.brokers = Some(brokers);
self
}
/// Sets the Kafka topic to send logs to
pub fn topic(mut self, topic: impl Into<String>) -> Self {
self.topic = Some(topic.into());
self
}
/// Sets the batch size for buffering messages before sending
pub fn batch_size(mut self, size: usize) -> Self {
self.batch_size = Some(size);
self
}
/// Sets the linger time in milliseconds
pub fn linger_ms(mut self, ms: u64) -> Self {
self.linger_ms = Some(ms);
self
}
/// Sets the linger time as a Duration
pub fn linger(mut self, duration: Duration) -> Self {
self.linger_ms = duration.as_millis().try_into().ok();
self
}
/// Sets the maximum number of messages to buffer in the producer's queue
pub fn queue_buffering_max_messages(mut self, size: usize) -> Self {
self.queue_buffering_max_messages = Some(size);
self
}
/// Sets the maximum size of the producer's queue in kilobytes
pub fn queue_buffering_max_kbytes(mut self, size: usize) -> Self {
self.queue_buffering_max_kbytes = Some(size);
self
}
/// Sets the reconnect backoff times
pub fn reconnect_backoff(mut self, min: Duration, max: Duration) -> Self {
self.reconnect_backoff_min_ms = min.as_millis().try_into().ok();
self.reconnect_backoff_max_ms = max.as_millis().try_into().ok();
self
}
/// Builds the KafkaWriter with the configured settings
pub fn build(self) -> Result<KafkaWriter, KafkaWriterError> {
let brokers = self.brokers.ok_or_else(|| {
KafkaWriterError::ProducerCreation(rdkafka::error::KafkaError::ClientCreation(
"No brokers specified. Use .brokers()".to_string(),
))
})?;
let topic = self.topic.ok_or_else(|| {
KafkaWriterError::ProducerCreation(rdkafka::error::KafkaError::ClientCreation(
"No topic specified. Use .topic()".to_string(),
))
})?;
KafkaWriter::new(
brokers,
topic,
self.batch_size,
self.linger_ms,
self.queue_buffering_max_messages,
self.queue_buffering_max_kbytes,
self.reconnect_backoff_min_ms,
self.reconnect_backoff_max_ms,
)
}
}
| {
"chunk": 0,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_0 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
/// Currency related errors.
#[derive(Debug, thiserror::Error)]
pub enum CurrencyError {
/// The provided currency is not supported for amount conversion
#[error("Unsupported currency: {currency}. Please add this currency to the supported currency list with appropriate decimal configuration.")]
UnsupportedCurrency { currency: String },
}
/// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment.
#[allow(clippy::upper_case_acronyms)]
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
strum::VariantNames,
ToSchema,
)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum Currency {
AED,
AFN,
ALL,
AMD,
ANG,
AOA,
ARS,
AUD,
AWG,
AZN,
BAM,
BBD,
BDT,
BGN,
BHD,
BIF,
BMD,
BND,
BOB,
BRL,
BSD,
BTN,
BWP,
BYN,
BZD,
CAD,
CDF,
CHF,
CLF,
CLP,
CNY,
COP,
CRC,
CUC,
CUP,
CVE,
CZK,
DJF,
DKK,
DOP,
DZD,
EGP,
ERN,
ETB,
EUR,
FJD,
FKP,
GBP,
GEL,
GHS,
GIP,
GMD,
GNF,
GTQ,
GYD,
HKD,
HNL,
HRK,
HTG,
HUF,
IDR,
ILS,
INR,
IQD,
IRR,
ISK,
JMD,
JOD,
JPY,
KES,
KGS,
KHR,
KMF,
KPW,
KRW,
KWD,
KYD,
KZT,
LAK,
LBP,
LKR,
LRD,
LSL,
LYD,
MAD,
MDL,
MGA,
MKD,
MMK,
MNT,
MOP,
MRU,
MUR,
MVR,
MWK,
MXN,
MYR,
MZN,
NAD,
NGN,
NIO,
NOK,
NPR,
NZD,
OMR,
PAB,
PEN,
PGK,
PHP,
PKR,
PLN,
PYG,
QAR,
RON,
RSD,
RUB,
RWF,
SAR,
SBD,
SCR,
SDG,
SEK,
SGD,
SHP,
SLE,
SLL,
SOS,
SRD,
SSP,
STD,
STN,
SVC,
SYP,
SZL,
THB,
TJS,
TMT,
TND,
TOP,
TRY,
TTD,
TWD,
TZS,
UAH,
UGX,
#[default]
USD,
UYU,
UZS,
VES,
VND,
VUV,
WST,
XAF,
XCD,
XOF,
XPF,
YER,
ZAR,
ZMW,
ZWL,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)]
#[serde(rename_all = "lowercase")]
pub enum SamsungPayCardBrand {
Visa,
MasterCard,
Amex,
Discover,
Unknown,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum BankType {
Checking,
Savings,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum BankHolderType {
Personal,
Business,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum BankNames {
AmericanExpress,
AffinBank,
AgroBank,
AllianceBank,
AmBank,
BankOfAmerica,
BankOfChina,
BankIslam,
BankMuamalat,
BankRakyat,
BankSimpananNasional,
Barclays,
BlikPSP,
CapitalOne,
Chase,
Citi,
CimbBank,
Discover,
NavyFederalCreditUnion,
PentagonFederalCreditUnion,
SynchronyBank,
WellsFargo,
AbnAmro,
AsnBank,
Bunq,
Handelsbanken,
HongLeongBank,
HsbcBank,
Ing,
Knab,
KuwaitFinanceHouse,
Moneyou,
Rabobank,
Regiobank,
Revolut,
SnsBank,
TriodosBank,
VanLanschot,
ArzteUndApothekerBank,
AustrianAnadiBankAg,
BankAustria,
Bank99Ag,
BankhausCarlSpangler,
BankhausSchelhammerUndSchatteraAg,
BankMillennium,
BankPEKAOSA,
BawagPskAg,
BksBankAg,
BrullKallmusBankAg,
BtvVierLanderBank,
CapitalBankGraweGruppeAg,
CeskaSporitelna,
Dolomitenbank,
EasybankAg,
EPlatbyVUB,
ErsteBankUndSparkassen,
FrieslandBank,
HypoAlpeadriabankInternationalAg,
HypoNoeLbFurNiederosterreichUWien,
HypoOberosterreichSalzburgSteiermark,
| {
"chunk": 0,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_1 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
HypoTirolBankAg,
HypoVorarlbergBankAg,
HypoBankBurgenlandAktiengesellschaft,
KomercniBanka,
MBank,
MarchfelderBank,
Maybank,
OberbankAg,
OsterreichischeArzteUndApothekerbank,
OcbcBank,
PayWithING,
PlaceZIPKO,
PlatnoscOnlineKartaPlatnicza,
PosojilnicaBankEGen,
PostovaBanka,
PublicBank,
RaiffeisenBankengruppeOsterreich,
RhbBank,
SchelhammerCapitalBankAg,
StandardCharteredBank,
SchoellerbankAg,
SpardaBankWien,
SporoPay,
SantanderPrzelew24,
TatraPay,
Viamo,
VolksbankGruppe,
VolkskreditbankAg,
VrBankBraunau,
UobBank,
PayWithAliorBank,
BankiSpoldzielcze,
PayWithInteligo,
BNPParibasPoland,
BankNowySA,
CreditAgricole,
PayWithBOS,
PayWithCitiHandlowy,
PayWithPlusBank,
ToyotaBank,
VeloBank,
ETransferPocztowy24,
PlusBank,
EtransferPocztowy24,
BankiSpbdzielcze,
BankNowyBfgSa,
GetinBank,
Blik,
NoblePay,
IdeaBank,
EnveloBank,
NestPrzelew,
MbankMtransfer,
Inteligo,
PbacZIpko,
BnpParibas,
BankPekaoSa,
VolkswagenBank,
AliorBank,
Boz,
BangkokBank,
KrungsriBank,
KrungThaiBank,
TheSiamCommercialBank,
KasikornBank,
OpenBankSuccess,
OpenBankFailure,
OpenBankCancelled,
Aib,
BankOfScotland,
DanskeBank,
FirstDirect,
FirstTrust,
Halifax,
Lloyds,
Monzo,
NatWest,
NationwideBank,
RoyalBankOfScotland,
Starling,
TsbBank,
TescoBank,
UlsterBank,
Yoursafe,
N26,
NationaleNederlanden,
}
/// Specifies the regulated name for a card network, primarily used for US debit card routing regulations.
/// This helps identify specific regulatory categories that cards may fall under.
#[derive(
Clone,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum RegulatedName {
#[serde(rename = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")]
#[strum(serialize = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")]
NonExemptWithFraud,
#[serde(untagged)]
#[strum(default)]
Unknown(String),
}
impl Currency {
pub fn to_currency_base_unit(self, amount: i64) -> Result<String, CurrencyError> {
let amount_f64 = self.to_currency_base_unit_asf64(amount)?;
Ok(format!("{amount_f64:.2}"))
}
pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, CurrencyError> {
let exponent = self.number_of_digits_after_decimal_point()?;
let divisor = 10_u32.pow(exponent.into());
let amount_f64 = amount as f64 / f64::from(divisor);
Ok(amount_f64)
}
pub fn to_currency_lower_unit(self, amount: String) -> Result<String, CurrencyError> {
let amount_decimal =
amount
.parse::<f64>()
.map_err(|_| CurrencyError::UnsupportedCurrency {
currency: format!("Invalid amount format: {amount}"),
})?;
let exponent = self.number_of_digits_after_decimal_point()?;
let multiplier = 10_u32.pow(exponent.into());
let final_amount = amount_decimal * f64::from(multiplier);
Ok(final_amount.to_string())
}
pub fn to_currency_base_unit_with_zero_decimal_check(
self,
amount: i64,
) -> Result<String, CurrencyError> {
if self.is_zero_decimal_currency() {
Ok(amount.to_string())
} else {
self.to_currency_base_unit(amount)
}
}
pub fn iso_4217(self) -> &'static str {
match self {
Self::AED => "784",
Self::AFN => "971",
Self::ALL => "008",
Self::AMD => "051",
Self::ANG => "532",
Self::AOA => "973",
Self::ARS => "032",
Self::AUD => "036",
Self::AWG => "533",
Self::AZN => "944",
Self::BAM => "977",
Self::BBD => "052",
Self::BDT => "050",
Self::BGN => "975",
Self::BHD => "048",
Self::BIF => "108",
Self::BMD => "060",
Self::BND => "096",
Self::BOB => "068",
Self::BRL => "986",
Self::BSD => "044",
Self::BTN => "064",
Self::BWP => "072",
Self::BYN => "933",
| {
"chunk": 1,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_2 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
Self::BZD => "084",
Self::CAD => "124",
Self::CDF => "976",
Self::CHF => "756",
Self::CLF => "990",
Self::CLP => "152",
Self::CNY => "156",
Self::COP => "170",
Self::CRC => "188",
Self::CUC => "931",
Self::CUP => "192",
Self::CVE => "132",
Self::CZK => "203",
Self::DJF => "262",
Self::DKK => "208",
Self::DOP => "214",
Self::DZD => "012",
Self::EGP => "818",
Self::ERN => "232",
Self::ETB => "230",
Self::EUR => "978",
Self::FJD => "242",
Self::FKP => "238",
Self::GBP => "826",
Self::GEL => "981",
Self::GHS => "936",
Self::GIP => "292",
Self::GMD => "270",
Self::GNF => "324",
Self::GTQ => "320",
Self::GYD => "328",
Self::HKD => "344",
Self::HNL => "340",
Self::HRK => "191",
Self::HTG => "332",
Self::HUF => "348",
Self::IDR => "360",
Self::ILS => "376",
Self::INR => "356",
Self::IQD => "368",
Self::IRR => "364",
Self::ISK => "352",
Self::JMD => "388",
Self::JOD => "400",
Self::JPY => "392",
Self::KES => "404",
Self::KGS => "417",
Self::KHR => "116",
Self::KMF => "174",
Self::KPW => "408",
Self::KRW => "410",
Self::KWD => "414",
Self::KYD => "136",
Self::KZT => "398",
Self::LAK => "418",
Self::LBP => "422",
Self::LKR => "144",
Self::LRD => "430",
Self::LSL => "426",
Self::LYD => "434",
Self::MAD => "504",
Self::MDL => "498",
Self::MGA => "969",
Self::MKD => "807",
Self::MMK => "104",
Self::MNT => "496",
Self::MOP => "446",
Self::MRU => "929",
Self::MUR => "480",
Self::MVR => "462",
Self::MWK => "454",
Self::MXN => "484",
Self::MYR => "458",
Self::MZN => "943",
Self::NAD => "516",
Self::NGN => "566",
Self::NIO => "558",
Self::NOK => "578",
Self::NPR => "524",
Self::NZD => "554",
Self::OMR => "512",
Self::PAB => "590",
Self::PEN => "604",
Self::PGK => "598",
Self::PHP => "608",
Self::PKR => "586",
Self::PLN => "985",
Self::PYG => "600",
Self::QAR => "634",
Self::RON => "946",
Self::RSD => "941",
Self::RUB => "643",
Self::RWF => "646",
Self::SAR => "682",
Self::SBD => "090",
Self::SCR => "690",
Self::SDG => "938",
Self::SEK => "752",
Self::SGD => "702",
Self::SHP => "654",
Self::SLE => "925",
Self::SLL => "694",
Self::SOS => "706",
Self::SRD => "968",
Self::SSP => "728",
Self::STD => "678",
Self::STN => "930",
Self::SVC => "222",
Self::SYP => "760",
Self::SZL => "748",
Self::THB => "764",
Self::TJS => "972",
Self::TMT => "934",
Self::TND => "788",
Self::TOP => "776",
Self::TRY => "949",
Self::TTD => "780",
Self::TWD => "901",
Self::TZS => "834",
Self::UAH => "980",
Self::UGX => "800",
Self::USD => "840",
Self::UYU => "858",
Self::UZS => "860",
Self::VES => "928",
Self::VND => "704",
Self::VUV => "548",
Self::WST => "882",
Self::XAF => "950",
Self::XCD => "951",
Self::XOF => "952",
Self::XPF => "953",
Self::YER => "886",
Self::ZAR => "710",
Self::ZMW => "967",
Self::ZWL => "932",
}
}
pub fn is_zero_decimal_currency(self) -> bool {
matches!(
self,
Self::BIF
| Self::CLP
| Self::DJF
| Self::GNF
| Self::JPY
| Self::KMF
| Self::KRW
| Self::MGA
| {
"chunk": 2,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_3 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
| Self::PYG
| Self::RWF
| Self::UGX
| Self::VND
| Self::VUV
| Self::XAF
| Self::XOF
| Self::XPF
)
}
pub fn is_three_decimal_currency(self) -> bool {
matches!(
self,
Self::BHD | Self::JOD | Self::KWD | Self::OMR | Self::TND
)
}
pub fn is_four_decimal_currency(self) -> bool {
matches!(self, Self::CLF)
}
/// Returns the number of decimal places for the currency based on ISO 4217 standard.
///
/// **Reference**: <https://www.iso.org/iso-4217-currency-codes.html>
///
/// **To add new currency**: Add to appropriate method (`is_zero_decimal_currency`, `is_two_decimal_currency`, etc.)
pub fn number_of_digits_after_decimal_point(self) -> Result<u8, CurrencyError> {
if self.is_zero_decimal_currency() {
Ok(0)
} else if self.is_three_decimal_currency() {
Ok(3)
} else if self.is_four_decimal_currency() {
Ok(4)
} else if self.is_two_decimal_currency() {
Ok(2)
} else {
Err(CurrencyError::UnsupportedCurrency {
currency: format!("{self:?}"),
})
}
}
/// Checks if the currency uses 2 decimal places (most common case).
/// This replaces the implicit default fallback with explicit validation.
pub fn is_two_decimal_currency(self) -> bool {
matches!(
self,
Self::AED
| Self::AFN
| Self::ALL
| Self::AMD
| Self::ANG
| Self::AOA
| Self::ARS
| Self::AUD
| Self::AWG
| Self::AZN
| Self::BAM
| Self::BBD
| Self::BDT
| Self::BGN
| Self::BMD
| Self::BND
| Self::BOB
| Self::BRL
| Self::BSD
| Self::BTN
| Self::BWP
| Self::BYN
| Self::BZD
| Self::CAD
| Self::CDF
| Self::CHF
| Self::CNY
| Self::COP
| Self::CRC
| Self::CUC
| Self::CUP
| Self::CVE
| Self::CZK
| Self::DKK
| Self::DOP
| Self::DZD
| Self::EGP
| Self::ERN
| Self::ETB
| Self::EUR
| Self::FJD
| Self::FKP
| Self::GBP
| Self::GEL
| Self::GHS
| Self::GIP
| Self::GMD
| Self::GTQ
| Self::GYD
| Self::HKD
| Self::HNL
| Self::HRK
| Self::HTG
| Self::HUF
| Self::IDR
| Self::ILS
| Self::INR
| Self::IQD
| Self::IRR
| Self::ISK
| Self::JMD
| Self::KES
| Self::KGS
| Self::KHR
| Self::KPW
| Self::KYD
| Self::KZT
| Self::LAK
| Self::LBP
| Self::LKR
| Self::LRD
| Self::LSL
| Self::LYD
| Self::MAD
| Self::MDL
| Self::MKD
| Self::MMK
| Self::MNT
| Self::MOP
| Self::MRU
| Self::MUR
| Self::MVR
| Self::MWK
| Self::MXN
| Self::MYR
| Self::MZN
| Self::NAD
| Self::NGN
| Self::NIO
| Self::NOK
| Self::NPR
| Self::NZD
| Self::PAB
| Self::PEN
| Self::PGK
| Self::PHP
| Self::PKR
| Self::PLN
| Self::QAR
| Self::RON
| Self::RSD
| Self::RUB
| Self::SAR
| Self::SBD
| Self::SCR
| Self::SDG
| Self::SEK
| Self::SGD
| Self::SHP
| Self::SLE
| {
"chunk": 3,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_4 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
| Self::SLL
| Self::SOS
| Self::SRD
| Self::SSP
| Self::STD
| Self::STN
| Self::SVC
| Self::SYP
| Self::SZL
| Self::THB
| Self::TJS
| Self::TMT
| Self::TOP
| Self::TRY
| Self::TTD
| Self::TWD
| Self::TZS
| Self::UAH
| Self::USD
| Self::UYU
| Self::UZS
| Self::VES
| Self::WST
| Self::XCD
| Self::YER
| Self::ZAR
| Self::ZMW
| Self::ZWL
)
}
}
/// Specifies how the payment is captured.
/// - `automatic`: Funds are captured immediately after successful authorization. This is the default behavior if the field is omitted.
/// - `manual`: Funds are authorized but not captured. A separate request to the `/payments/{payment_id}/capture` endpoint is required to capture the funds.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CaptureMethod {
#[default]
Automatic,
Manual,
ManualMultiple,
Scheduled,
SequentialAutomatic,
}
/// Specifies how the payment method can be used for future payments.
/// - `off_session`: The payment method can be used for future payments when the customer is not present.
/// - `on_session`: The payment method is intended for use only when the customer is present during checkout.
/// If omitted, defaults to `on_session`.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FutureUsage {
OffSession,
#[default]
OnSession,
}
/// To indicate the type of payment experience that the customer would go through
#[derive(
Eq,
strum::EnumString,
PartialEq,
Hash,
Copy,
Clone,
Debug,
serde::Serialize,
serde::Deserialize,
strum::Display,
ToSchema,
Default,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentExperience {
#[default]
RedirectToUrl,
InvokeSdkClient,
DisplayQrCode,
OneClick,
LinkWallet,
InvokePaymentApp,
DisplayWaitScreen,
CollectOtp,
}
/// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets.
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethodType {
Ach,
Affirm,
AfterpayClearpay,
Alfamart,
AliPay,
AliPayHk,
Alma,
AmazonPay,
ApplePay,
Atome,
Bluecode,
Bacs,
BancontactCard,
Becs,
Benefit,
Bizum,
Blik,
Boleto,
BcaBankTransfer,
BniVa,
BriVa,
CardRedirect,
CimbVa,
#[serde(rename = "classic")]
ClassicReward,
Credit,
CryptoCurrency,
Cashapp,
Dana,
DanamonVa,
Debit,
DuitNow,
Efecty,
Eft,
Eps,
Fps,
Evoucher,
Giropay,
Givex,
GooglePay,
GoPay,
Gcash,
Ideal,
Interac,
Indomaret,
Klarna,
KakaoPay,
LocalBankRedirect,
MandiriVa,
Knet,
MbWay,
MobilePay,
Momo,
MomoAtm,
Multibanco,
OnlineBankingThailand,
OnlineBankingCzechRepublic,
OnlineBankingFinland,
OnlineBankingFpx,
OnlineBankingPoland,
OnlineBankingSlovakia,
Oxxo,
PagoEfectivo,
PermataBankTransfer,
OpenBankingUk,
PayBright,
Paypal,
Paze,
Pix,
PaySafeCard,
Przelewy24,
PromptPay,
Pse,
RedCompra,
RedPagos,
SamsungPay,
Sepa,
SepaBankTransfer,
Sofort,
Swish,
TouchNGo,
Trustly,
Twint,
UpiCollect,
UpiIntent,
Vipps,
VietQr,
Venmo,
Walley,
WeChatPay,
SevenEleven,
Lawson,
MiniStop,
FamilyMart,
Seicomart,
PayEasy,
LocalBankTransfer,
Mifinity,
| {
"chunk": 4,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_5 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
#[serde(rename = "open_banking_pis")]
OpenBankingPIS,
DirectCarrierBilling,
InstantBankTransfer,
InstantBankTransferFinland,
InstantBankTransferPoland,
RevolutPay,
}
impl PaymentMethodType {
pub fn should_check_for_customer_saved_payment_method_type(self) -> bool {
matches!(self, Self::Credit | Self::Debit)
}
pub fn to_display_name(&self) -> String {
match self {
Self::ApplePay => "Apple Pay".to_string(),
Self::GooglePay => "Google Pay".to_string(),
Self::SamsungPay => "Samsung Pay".to_string(),
Self::AliPay => "AliPay".to_string(),
Self::WeChatPay => "WeChat Pay".to_string(),
Self::KakaoPay => "Kakao Pay".to_string(),
Self::GoPay => "GoPay".to_string(),
Self::Gcash => "GCash".to_string(),
_ => format!("{self:?}"),
}
}
}
/// Connector accepted currency unit as either "Base" or "Minor"
#[derive(Debug)]
pub enum CurrencyUnit {
/// Base currency unit
Base,
/// Minor currency unit
Minor,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
strum::Display,
strum::EnumString,
strum::EnumIter,
serde::Serialize,
serde::Deserialize,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RefundStatus {
#[serde(alias = "Failure")]
Failure,
#[serde(alias = "ManualReview")]
ManualReview,
#[default]
#[serde(alias = "Pending")]
Pending,
#[serde(alias = "Success")]
Success,
#[serde(alias = "TransactionFailure")]
TransactionFailure,
}
/// The status of the attempt
#[derive(
Clone,
Copy,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AttemptStatus {
Started,
AuthenticationFailed,
RouterDeclined,
AuthenticationPending,
AuthenticationSuccessful,
Authorized,
AuthorizationFailed,
Charged,
Authorizing,
CodInitiated,
Voided,
VoidedPostCapture,
VoidInitiated,
VoidPostCaptureInitiated,
CaptureInitiated,
CaptureFailed,
VoidFailed,
AutoRefunded,
PartialCharged,
PartialChargedAndChargeable,
Unresolved,
#[default]
Pending,
Failure,
PaymentMethodAwaited,
ConfirmationAwaited,
DeviceDataCollectionPending,
IntegrityFailure,
Unknown,
}
impl TryFrom<u32> for AttemptStatus {
type Error = String;
fn try_from(value: u32) -> Result<Self, Self::Error> {
Ok(match value {
1 => AttemptStatus::Started,
2 => AttemptStatus::AuthenticationFailed,
3 => AttemptStatus::RouterDeclined,
4 => AttemptStatus::AuthenticationPending,
5 => AttemptStatus::AuthenticationSuccessful,
6 => AttemptStatus::Authorized,
7 => AttemptStatus::AuthorizationFailed,
8 => AttemptStatus::Charged,
9 => AttemptStatus::Authorizing,
10 => AttemptStatus::CodInitiated,
11 => AttemptStatus::Voided,
12 => AttemptStatus::VoidedPostCapture,
13 => AttemptStatus::VoidInitiated,
14 => AttemptStatus::VoidPostCaptureInitiated,
15 => AttemptStatus::CaptureInitiated,
16 => AttemptStatus::CaptureFailed,
17 => AttemptStatus::VoidFailed,
18 => AttemptStatus::AutoRefunded,
19 => AttemptStatus::PartialCharged,
20 => AttemptStatus::PartialChargedAndChargeable,
21 => AttemptStatus::Unresolved,
22 => AttemptStatus::Pending,
23 => AttemptStatus::Failure,
24 => AttemptStatus::PaymentMethodAwaited,
25 => AttemptStatus::ConfirmationAwaited,
26 => AttemptStatus::DeviceDataCollectionPending,
_ => AttemptStatus::Unknown,
})
}
}
impl AttemptStatus {
pub fn is_terminal_status(self) -> bool {
matches!(
self,
Self::Charged
| Self::AutoRefunded
| Self::Voided
| Self::VoidedPostCapture
| Self::PartialCharged
| Self::AuthenticationFailed
| Self::AuthorizationFailed
| {
"chunk": 5,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_6 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
| Self::VoidFailed
| Self::CaptureFailed
| Self::Failure
| Self::IntegrityFailure
)
}
}
/// Status of the dispute
#[derive(
Clone,
Debug,
Copy,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DisputeStatus {
#[default]
DisputeOpened,
DisputeExpired,
DisputeAccepted,
DisputeCancelled,
DisputeChallenged,
DisputeWon,
DisputeLost,
}
/// Stage of the dispute
#[derive(
Clone,
Copy,
Default,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DisputeStage {
PreDispute,
#[default]
Dispute,
PreArbitration,
}
/// Indicates the card network.
#[derive(
Clone,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
pub enum CardNetwork {
#[serde(alias = "VISA")]
Visa,
#[serde(alias = "MASTERCARD")]
Mastercard,
#[serde(alias = "AMERICANEXPRESS")]
#[serde(alias = "AMEX")]
AmericanExpress,
JCB,
#[serde(alias = "DINERSCLUB")]
DinersClub,
#[serde(alias = "DISCOVER")]
Discover,
#[serde(alias = "CARTESBANCAIRES")]
CartesBancaires,
#[serde(alias = "UNIONPAY")]
UnionPay,
#[serde(alias = "INTERAC")]
Interac,
#[serde(alias = "RUPAY")]
RuPay,
#[serde(alias = "MAESTRO")]
Maestro,
#[serde(alias = "STAR")]
Star,
#[serde(alias = "PULSE")]
Pulse,
#[serde(alias = "ACCEL")]
Accel,
#[serde(alias = "NYCE")]
Nyce,
}
impl CardNetwork {
pub fn is_global_network(&self) -> bool {
matches!(
self,
Self::Visa
| Self::Mastercard
| Self::AmericanExpress
| Self::JCB
| Self::DinersClub
| Self::Discover
| Self::CartesBancaires
| Self::UnionPay
)
}
pub fn is_us_local_network(&self) -> bool {
matches!(self, Self::Star | Self::Pulse | Self::Accel | Self::Nyce)
}
}
/// Indicates the type of payment method. Eg: 'card', 'wallet', etc.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethod {
#[default]
Card,
CardRedirect,
PayLater,
Wallet,
BankRedirect,
BankTransfer,
Crypto,
BankDebit,
Reward,
RealTimePayment,
Upi,
Voucher,
GiftCard,
OpenBanking,
MobilePayment,
}
/// Specifies the type of cardholder authentication to be applied for a payment.
///
/// - `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer.
/// - `NoThreeDs`: Indicates that 3D Secure authentication should not be performed. The liability for chargebacks typically remains with the merchant. This is often the default if not specified.
///
/// Note: The actual authentication behavior can also be influenced by merchant configuration and specific connector defaults. Some connectors might still enforce 3DS or bypass it regardless of this parameter.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthenticationType {
ThreeDs,
#[default]
NoThreeDs,
}
#[derive(
Clone,
Copy,
Debug,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EventClass {
Payments,
Refunds,
Disputes,
}
#[derive(
Clone,
Debug,
Eq,
Default,
Hash,
| {
"chunk": 6,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_7 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
utoipa::ToSchema,
Copy,
)]
#[rustfmt::skip]
pub enum CountryAlpha2 {
AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT,
AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW,
BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL,
CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ,
DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI,
FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU,
GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR,
IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW,
KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY,
MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS,
MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP,
NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA,
RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA,
SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK,
SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO,
TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU,
VE, VN, VG, VI, WF, EH, YE, ZM, ZW,
#[default]
US
}
#[derive(Debug, thiserror::Error, PartialEq, Clone)]
pub enum ApiClientError {
#[error("Header map construction failed")]
HeaderMapConstructionFailed,
#[error("Invalid proxy configuration")]
InvalidProxyConfiguration,
#[error("Client construction failed")]
ClientConstructionFailed,
#[error("Certificate decode failed")]
CertificateDecodeFailed,
#[error("Request body serialization failed")]
BodySerializationFailed,
#[error("Unexpected state reached/Invariants conflicted")]
UnexpectedState,
#[error("Failed to parse URL")]
UrlParsingFailed,
#[error("URL encoding of request payload failed")]
UrlEncodingFailed,
#[error("Failed to send request to connector {0}")]
RequestNotSent(String),
#[error("Failed to decode response")]
ResponseDecodingFailed,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("connection closed before a message could complete")]
ConnectionClosedIncompleteMessage,
#[error("Server responded with Internal Server Error")]
InternalServerErrorReceived,
#[error("Server responded with Bad Gateway")]
BadGatewayReceived,
#[error("Server responded with Service Unavailable")]
ServiceUnavailableReceived,
#[error("Server responded with Gateway Timeout")]
GatewayTimeoutReceived,
#[error("Server responded with unexpected response")]
UnexpectedServerResponse,
}
impl ApiClientError {
pub fn is_upstream_timeout(&self) -> bool {
self == &Self::RequestTimeoutReceived
}
pub fn is_connection_closed_before_message_could_complete(&self) -> bool {
self == &Self::ConnectionClosedIncompleteMessage
}
}
#[derive(
serde::Serialize,
serde::Deserialize,
Clone,
Copy,
Debug,
PartialEq,
Eq,
strum::EnumString,
strum::Display,
)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum ProcessTrackerRunner {
PaymentsSyncWorkflow,
RefundWorkflowRouter,
DeleteTokenizeDataWorkflow,
ApiKeyExpiryWorkflow,
OutgoingWebhookRetryWorkflow,
AttachPayoutAccountWorkflow,
PaymentMethodStatusUpdateWorkflow,
PassiveRecoveryWorkflow,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
strum::VariantNames,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
/// RoutableConnectors are the subset of Connectors that are eligible for payments routing
pub enum RoutableConnectors {
Adyenplatform,
Aci,
Adyen,
Airwallex,
// Amazonpay,
Archipel,
Authorizedotnet,
Bluecode,
Bankofamerica,
Barclaycard,
Billwerk,
Bitpay,
Bambora,
Bamboraapac,
Bluesnap,
Boku,
Braintree,
Cashtocode,
Chargebee,
Checkout,
Coinbase,
Coingate,
Cryptopay,
Cybersource,
Datatrans,
Deutschebank,
Digitalvirgo,
Dlocal,
Ebanx,
Elavon,
Facilitapay,
Fiserv,
Fiservemea,
Fiuu,
Forte,
Getnet,
Globalpay,
Globepay,
Gocardless,
| {
"chunk": 7,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_common_enums_5419210580886904799_8 | clm | mini_chunk | // connector-service/backend/common_enums/src/enums.rs
Hipay,
Helcim,
Iatapay,
Inespay,
Itaubank,
Jpmorgan,
Klarna,
Mifinity,
Mollie,
Moneris,
Multisafepay,
Nexinets,
Nexixpay,
Nmi,
Nomupay,
Noon,
// Nordea,
Novalnet,
Nuvei,
// Opayo, added as template code for future usage
Opennode,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
Paybox,
Payme,
Payone,
Paypal,
Paystack,
Payu,
Placetopay,
Powertranz,
Prophetpay,
Rapyd,
Razorpay,
Recurly,
Redsys,
Riskified,
Shift4,
Signifyd,
Square,
Stax,
Stripe,
Stripebilling,
// Taxjar,
Trustpay,
// Thunes
Tokenio,
// Tsys,
Tsys,
// UnifiedAuthenticationService,
// Vgs
Volt,
Wellsfargo,
// Wellsfargopayout,
Wise,
Worldline,
Worldpay,
Worldpayvantiv,
Worldpayxml,
Xendit,
Zen,
Plaid,
Zsl,
}
/// Indicates the transaction status
#[derive(
Clone,
Default,
Debug,
serde::Serialize,
serde::Deserialize,
Eq,
Hash,
PartialEq,
ToSchema,
strum::Display,
strum::EnumString,
)]
pub enum TransactionStatus {
/// Authentication/ Account Verification Successful
#[serde(rename = "Y")]
Success,
/// Not Authenticated /Account Not Verified; Transaction denied
#[default]
#[serde(rename = "N")]
Failure,
/// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq)
#[serde(rename = "U")]
VerificationNotPerformed,
/// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided
#[serde(rename = "A")]
NotVerified,
/// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted.
#[serde(rename = "R")]
Rejected,
/// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes)
#[serde(rename = "C")]
ChallengeRequired,
/// Challenge Required; Decoupled Authentication confirmed.
#[serde(rename = "D")]
ChallengeRequiredDecoupledAuthentication,
/// Informational Only; 3DS Requestor challenge preference acknowledged.
#[serde(rename = "I")]
InformationOnly,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GooglePayAuthMethod {
/// Contain pan data only
PanOnly,
/// Contain cryptogram data along with pan data
#[serde(rename = "CRYPTOGRAM_3DS")]
Cryptogram,
}
#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProductType {
#[default]
Physical,
Digital,
Travel,
Ride,
Event,
Accommodation,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum WebhookTransformationStatus {
/// Transformation completed successfully, no further action needed
Complete,
/// Transformation incomplete, requires second call for final status
Incomplete,
}
#[derive(Clone, Debug, PartialEq)]
pub enum CallConnectorAction {
Trigger,
HandleResponse(Vec<u8>),
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
Hash,
)]
pub enum PaymentChargeType {
#[serde(untagged)]
Stripe(StripeChargeType),
}
#[derive(
Clone,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum StripeChargeType {
#[default]
Direct,
Destination,
}
#[derive(
Default,
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthorizationStatus {
Success,
Failure,
// Processing state is before calling connector
#[default]
Processing,
// Requires merchant action
Unresolved,
}
#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum DecoupledAuthenticationType {
#[default]
| {
"chunk": 8,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_cards_-8249660221355203845_0 | clm | mini_chunk | // connector-service/backend/cards/src/validate.rs
use std::{collections::HashMap, fmt, ops::Deref, str::FromStr, sync::LazyLock};
use common_utils::{
consts::{MAX_CARD_NUMBER_LENGTH, MIN_CARD_NUMBER_LENGTH},
date_time, ValidationError,
};
use error_stack::report;
use hyperswitch_masking::{PeekInterface, Strategy, StrongSecret, WithType};
use regex::Regex;
use serde::{
de::{self},
Deserialize, Deserializer, Serialize,
};
use thiserror::Error;
#[derive(Debug, Deserialize, Serialize, Error)]
#[error("{0}")]
pub struct CardNumberValidationErr(&'static str);
/// Card number
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct CardNumber(StrongSecret<String, CardNumberStrategy>);
//Network Token
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct NetworkToken(StrongSecret<String, CardNumberStrategy>);
impl CardNumber {
pub fn get_card_isin(&self) -> String {
self.0.peek().chars().take(6).collect::<String>()
}
pub fn get_extended_card_bin(&self) -> String {
self.0.peek().chars().take(8).collect::<String>()
}
pub fn get_card_no(&self) -> String {
self.0.peek().chars().collect::<String>()
}
pub fn get_last4(&self) -> String {
self.0
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>()
}
pub fn is_cobadged_card(&self) -> Result<bool, error_stack::Report<ValidationError>> {
/// Regex to identify card networks
static CARD_NETWORK_REGEX: LazyLock<HashMap<&str, Result<Regex, regex::Error>>> =
LazyLock::new(|| {
let mut map = HashMap::new();
map.insert(
"Mastercard",
Regex::new(r"^(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[0-1][0-9]|2720|5[1-5])"),
);
map.insert("American Express", Regex::new(r"^3[47]"));
map.insert("Visa", Regex::new(r"^4"));
map.insert(
"Discover",
Regex::new(
r"^(6011|64[4-9]|65|622126|622[1-9][0-9][0-9]|6229[0-1][0-9]|622925)",
),
);
map.insert(
"Maestro",
Regex::new(r"^(5018|5081|5044|504681|504993|5020|502260|5038|5893|603845|603123|6304|6759|676[1-3]|6220|504834|504817|504645|504775|600206|627741)"),
);
map.insert(
"RuPay",
Regex::new(r"^(508227|508[5-9]|603741|60698[5-9]|60699|607[0-8]|6079[0-7]|60798[0-4]|60800[1-9]|6080[1-9]|608[1-4]|608500|6521[5-9]|652[2-9]|6530|6531[0-4]|817290|817368|817378|353800|82)"),
);
map.insert("Diners Club", Regex::new(r"^(36|38|39|30[0-5])"));
map.insert("JCB", Regex::new(r"^35(2[89]|[3-8][0-9])"));
map.insert("CarteBlanche", Regex::new(r"^389[0-9]{11}$"));
map.insert("Sodex", Regex::new(r"^(637513)"));
map.insert("BAJAJ", Regex::new(r"^(203040)"));
map.insert("CartesBancaires", Regex::new(r"^(401(005|006|581)|4021(01|02)|403550|405936|406572|41(3849|4819|50(56|59|62|71|74)|6286|65(37|79)|71[7])|420110|423460|43(47(21|22)|50(48|49|50|51|52)|7875|95(09|11|15|39|98)|96(03|18|19|20|22|72))|4424(48|49|50|51|52|57)|448412|4505(19|60)|45(33|56[6-8]|61|62[^3]|6955|7452|7717|93[02379])|46(099|54(76|77)|6258|6575|98[023])|47(4107|71(73|74|86)|72(65|93)|9619)|48(1091|3622|6519)|49(7|83[5-9]|90(0[1-6]|1[0-6]|2[0-3]|3[0-3]|4[0-3]|5[0-2]|68|9[256789]))|5075(89|90|93|94|97)|51(0726|3([0-7]|8[56]|9(00|38))|5214|62(07|36)|72(22|43)|73(65|66)|7502|7647|8101|9920)|52(0993|1662|3718|7429|9227|93(13|14|31)|94(14|21|30|40|47|55|56|[6-9])|9542)|53(0901|10(28|30)|1195|23(4[4-7])|2459|25(09|34|54|56)|3801|41(02|05|11)|50(29|66)|5324|61(07|15)|71(06|12)|8011)|54(2848|5157|9538|98(5[89]))|55(39(79|93)|42(05|60)|4965|7008|88(67|82)|89(29|4[23])|9618|98(09|10))|56(0408|12(0[2-6]|4[134]|5[04678]))|58(17(0[0-7]|15|2[14]|3[16789]|4[0-9]|5[016]|6[269]|7[3789]|8[0-7]|9[017])|55(0[2-5]|7[7-9]|8[0-2])))"));
map
});
let mut no_of_supported_card_networks = 0;
let card_number_str = self.get_card_no();
for (_, regex) in CARD_NETWORK_REGEX.iter() {
| {
"chunk": 0,
"crate": "ucs_cards",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_cards_-8249660221355203845_1 | clm | mini_chunk | // connector-service/backend/cards/src/validate.rs
let card_regex = match regex.as_ref() {
Ok(regex) => Ok(regex),
Err(_) => Err(report!(ValidationError::InvalidValue {
message: "Invalid regex expression".into(),
})),
}?;
if card_regex.is_match(&card_number_str) {
no_of_supported_card_networks += 1;
if no_of_supported_card_networks > 1 {
break;
}
}
}
Ok(no_of_supported_card_networks > 1)
}
}
impl NetworkToken {
pub fn get_card_isin(&self) -> String {
self.0.peek().chars().take(6).collect::<String>()
}
pub fn get_extended_card_bin(&self) -> String {
self.0.peek().chars().take(8).collect::<String>()
}
pub fn get_card_no(&self) -> String {
self.0.peek().chars().collect::<String>()
}
pub fn get_last4(&self) -> String {
self.0
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>()
}
}
impl FromStr for CardNumber {
type Err = CardNumberValidationErr;
fn from_str(card_number: &str) -> Result<Self, Self::Err> {
// Valid test cards for threedsecureio
let valid_test_cards = [
"4000100511112003",
"6000100611111203",
"3000100811111072",
"9000100111111111",
];
let card_number = card_number.split_whitespace().collect::<String>();
let is_card_valid = sanitize_card_number(&card_number)?;
if valid_test_cards.contains(&card_number.as_str()) || is_card_valid {
Ok(Self(StrongSecret::new(card_number)))
} else {
Err(CardNumberValidationErr("card number invalid"))
}
}
}
impl FromStr for NetworkToken {
type Err = CardNumberValidationErr;
fn from_str(network_token: &str) -> Result<Self, Self::Err> {
// Valid test cards for threedsecureio
let valid_test_network_tokens = [
"4000100511112003",
"6000100611111203",
"3000100811111072",
"9000100111111111",
];
let network_token = network_token.split_whitespace().collect::<String>();
let is_network_token_valid = sanitize_card_number(&network_token)?;
if valid_test_network_tokens.contains(&network_token.as_str()) || is_network_token_valid {
Ok(Self(StrongSecret::new(network_token)))
} else {
Err(CardNumberValidationErr("network token invalid"))
}
}
}
pub fn sanitize_card_number(card_number: &str) -> Result<bool, CardNumberValidationErr> {
let is_card_number_valid = Ok(card_number)
.and_then(validate_card_number_chars)
.and_then(validate_card_number_length)
.map(|number| luhn(&number))?;
Ok(is_card_number_valid)
}
/// # Panics
///
/// Never, as a single character will never be greater than 10, or `u8`
pub fn validate_card_number_chars(number: &str) -> Result<Vec<u8>, CardNumberValidationErr> {
let data = number.chars().try_fold(
Vec::with_capacity(MAX_CARD_NUMBER_LENGTH),
|mut data, character| {
data.push(
#[allow(clippy::expect_used)]
character
.to_digit(10)
.ok_or(CardNumberValidationErr(
"invalid character found in card number",
))?
.try_into()
.expect("error while converting a single character to u8"), // safety, a single character will never be greater `u8`
);
Ok::<Vec<u8>, CardNumberValidationErr>(data)
},
)?;
Ok(data)
}
pub fn validate_card_number_length(number: Vec<u8>) -> Result<Vec<u8>, CardNumberValidationErr> {
if number.len() >= MIN_CARD_NUMBER_LENGTH && number.len() <= MAX_CARD_NUMBER_LENGTH {
Ok(number)
} else {
Err(CardNumberValidationErr("invalid card number length"))
}
}
#[allow(clippy::as_conversions)]
pub fn luhn(number: &[u8]) -> bool {
number
.iter()
.rev()
.enumerate()
.map(|(idx, element)| {
((*element * 2) / 10 + (*element * 2) % 10) * ((idx as u8) % 2)
+ (*element) * (((idx + 1) as u8) % 2)
})
| {
"chunk": 1,
"crate": "ucs_cards",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_cards_-8249660221355203845_2 | clm | mini_chunk | // connector-service/backend/cards/src/validate.rs
.sum::<u8>()
% 10
== 0
}
impl TryFrom<String> for CardNumber {
type Error = CardNumberValidationErr;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value)
}
}
impl TryFrom<String> for NetworkToken {
type Error = CardNumberValidationErr;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value)
}
}
impl Deref for CardNumber {
type Target = StrongSecret<String, CardNumberStrategy>;
fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> {
&self.0
}
}
impl Deref for NetworkToken {
type Target = StrongSecret<String, CardNumberStrategy>;
fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> {
&self.0
}
}
impl<'de> Deserialize<'de> for CardNumber {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl<'de> Deserialize<'de> for NetworkToken {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
pub enum CardNumberStrategy {}
impl<T> Strategy<T> for CardNumberStrategy
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
if val_str.len() < 15 || val_str.len() > 19 {
return WithType::fmt(val, f);
}
if let Some(value) = val_str.get(..6) {
write!(f, "{}{}", value, "*".repeat(val_str.len() - 6))
} else {
WithType::fmt(val, f)
}
}
}
impl prost::Message for CardNumber {
fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
if !self.0.peek().is_empty() {
prost::encoding::string::encode(1, self.0.peek(), buf);
}
}
fn merge_field(
&mut self,
tag: u32,
wire_type: prost::encoding::WireType,
buf: &mut impl bytes::Buf,
ctx: prost::encoding::DecodeContext,
) -> Result<(), prost::DecodeError> {
if tag == 1 {
let mut temp_string = String::new();
prost::encoding::string::merge(wire_type, &mut temp_string, buf, ctx)?;
*self = CardNumber(StrongSecret::new(temp_string));
Ok(())
} else {
prost::encoding::skip_field(wire_type, tag, buf, ctx)
}
}
fn encoded_len(&self) -> usize {
if !self.0.peek().is_empty() {
prost::encoding::string::encoded_len(1, self.0.peek())
} else {
0
}
}
fn clear(&mut self) {
*self = CardNumber::default();
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use hyperswitch_masking::Secret;
use super::*;
#[test]
fn valid_card_number() {
let s = "371449635398431";
assert_eq!(
CardNumber::from_str(s).unwrap(),
CardNumber(StrongSecret::from_str(s).unwrap())
);
}
#[test]
fn invalid_card_number_length() {
let s = "371446";
assert_eq!(
CardNumber::from_str(s).unwrap_err().to_string(),
"invalid card number length".to_string()
);
}
#[test]
fn card_number_with_non_digit_character() {
let s = "371446431 A";
assert_eq!(
CardNumber::from_str(s).unwrap_err().to_string(),
"invalid character found in card number".to_string()
);
}
#[test]
fn invalid_card_number() {
let s = "371446431";
assert_eq!(
CardNumber::from_str(s).unwrap_err().to_string(),
"card number invalid".to_string()
);
}
#[test]
fn card_number_no_whitespace() {
let s = "3714 4963 5398 431";
assert_eq!(
CardNumber::from_str(s).unwrap().to_string(),
"371449*********"
);
}
#[test]
fn test_valid_card_number_masking() {
let secret: Secret<String, CardNumberStrategy> =
Secret::new("1234567890987654".to_string());
assert_eq!("123456**********", format!("{secret:?}"));
}
#[test]
fn test_invalid_card_number_masking() {
let secret: Secret<String, CardNumberStrategy> = Secret::new("9123456789".to_string());
| {
"chunk": 2,
"crate": "ucs_cards",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_ucs_cards_-8249660221355203845_3 | clm | mini_chunk | // connector-service/backend/cards/src/validate.rs
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_card_number_strong_secret_masking() {
let card_number = CardNumber::from_str("3714 4963 5398 431").unwrap();
let secret = &(*card_number);
assert_eq!("371449*********", format!("{secret:?}"));
}
#[test]
fn test_valid_card_number_deserialization() {
let card_number = serde_json::from_str::<CardNumber>(r#""3714 4963 5398 431""#).unwrap();
let secret = card_number.to_string();
assert_eq!(r#""371449*********""#, format!("{secret:?}"));
}
#[test]
fn test_invalid_card_number_deserialization() {
let card_number = serde_json::from_str::<CardNumber>(r#""1234 5678""#);
let error_msg = card_number.unwrap_err().to_string();
assert_eq!(error_msg, "card number invalid".to_string());
}
}
#[derive(Clone, Debug, Serialize)]
pub struct CardExpirationMonth(StrongSecret<u8>);
impl CardExpirationMonth {
pub fn two_digits(&self) -> String {
format!("{:02}", self.0.peek())
}
}
impl TryFrom<u8> for CardExpirationMonth {
type Error = error_stack::Report<ValidationError>;
fn try_from(month: u8) -> Result<Self, Self::Error> {
if (1..=12).contains(&month) {
Ok(Self(StrongSecret::new(month)))
} else {
Err(report!(ValidationError::InvalidValue {
message: "invalid card expiration month".to_string()
}))
}
}
}
impl<'de> Deserialize<'de> for CardExpirationMonth {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let month = u8::deserialize(deserializer)?;
month.try_into().map_err(de::Error::custom)
}
}
#[derive(Clone, Debug, Serialize)]
pub struct CardExpirationYear(StrongSecret<u16>);
impl CardExpirationYear {
pub fn get_year(&self) -> u16 {
*self.0.peek()
}
}
impl TryFrom<u16> for CardExpirationYear {
type Error = error_stack::Report<ValidationError>;
fn try_from(year: u16) -> Result<Self, Self::Error> {
let curr_year = u16::try_from(date_time::now().year()).map_err(|_| {
report!(ValidationError::InvalidValue {
message: "invalid year".to_string()
})
})?;
if year >= curr_year {
Ok(Self(StrongSecret::<u16>::new(year)))
} else {
Err(report!(ValidationError::InvalidValue {
message: "invalid card expiration year".to_string()
}))
}
}
}
impl<'de> Deserialize<'de> for CardExpirationYear {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let year = u16::deserialize(deserializer)?;
year.try_into().map_err(de::Error::custom)
}
}
| {
"chunk": 3,
"crate": "ucs_cards",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_6066888807983657858_0 | clm | mini_chunk | // connector-service/backend/external-services/src/shared_metrics.rs
#![allow(clippy::unwrap_used)]
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
time::Instant,
};
use error_stack::ResultExt;
use http_body::Body as HttpBody;
use lazy_static::lazy_static;
use prometheus::{
self, register_histogram_vec, register_int_counter_vec, Encoder, HistogramVec, IntCounterVec,
TextEncoder,
};
use tower::{Layer, Service};
// Define latency buckets for histograms
const LATENCY_BUCKETS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];
lazy_static! {
pub static ref GRPC_SERVER_REQUESTS_TOTAL: IntCounterVec = register_int_counter_vec!(
"GRPC_SERVER_REQUESTS_TOTAL",
"Total number of gRPC requests received",
&["method", "service", "connector"]
)
.unwrap();
pub static ref GRPC_SERVER_REQUESTS_SUCCESSFUL: IntCounterVec = register_int_counter_vec!(
"GRPC_SERVER_REQUESTS_SUCCESSFUL",
"Total number of gRPC requests successful",
&["method", "service", "connector"]
)
.unwrap();
pub static ref GRPC_SERVER_REQUEST_LATENCY: HistogramVec = register_histogram_vec!(
"GRPC_SERVER_REQUEST_LATENCY",
"Request latency in seconds",
&["method", "service", "connector"],
LATENCY_BUCKETS.to_vec()
)
.unwrap();
pub static ref EXTERNAL_SERVICE_API_CALLS_LATENCY: HistogramVec = register_histogram_vec!(
"EXTERNAL_SERVICE_API_CALLS_LATENCY_SECONDS",
"Latency of external service API calls",
&["method", "service", "connector"],
LATENCY_BUCKETS.to_vec()
)
.unwrap();
pub static ref EXTERNAL_SERVICE_TOTAL_API_CALLS: IntCounterVec = register_int_counter_vec!(
"EXTERNAL_SERVICE_TOTAL_API_CALLS",
"Total number of external service API calls",
&["method", "service", "connector"]
)
.unwrap();
pub static ref EXTERNAL_SERVICE_API_CALLS_ERRORS: IntCounterVec = register_int_counter_vec!(
"EXTERNAL_SERVICE_API_CALLS_ERRORS",
"Total number of errors in external service API calls",
&["method", "service", "connector", "error"]
)
.unwrap();
}
// Middleware Layer that automatically handles all gRPC methods
#[derive(Clone)]
pub struct GrpcMetricsLayer;
#[allow(clippy::new_without_default)]
impl GrpcMetricsLayer {
pub fn new() -> Self {
Self
}
}
impl<S> Layer<S> for GrpcMetricsLayer {
type Service = GrpcMetricsService<S>;
fn layer(&self, service: S) -> Self::Service {
GrpcMetricsService::new(service)
}
}
// Middleware Service that intercepts all gRPC calls
#[derive(Clone)]
pub struct GrpcMetricsService<S> {
inner: S,
}
impl<S> GrpcMetricsService<S> {
pub fn new(inner: S) -> Self {
Self { inner }
}
}
impl<S, B> Service<hyper::Request<B>> for GrpcMetricsService<S>
where
S: Service<hyper::Request<B>, Response = hyper::Response<B>> + Clone + Send + 'static,
S::Future: Send + 'static,
S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
B: HttpBody + Send + 'static,
{
type Response = hyper::Response<B>;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut req: hyper::Request<B>) -> Self::Future {
let clone = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, clone);
let start_time = Instant::now();
// Extract method name from gRPC path
let method_name = extract_grpc_method_name(&req);
let service_name = extract_grpc_service_name(&req);
// Extract connector from request headers/metadata
let connector = extract_connector_from_request(&req);
// Increment total requests counter
GRPC_SERVER_REQUESTS_TOTAL
.with_label_values(&[&method_name, &service_name, &connector])
.inc();
req.extensions_mut().insert(service_name.clone());
Box::pin(async move {
let result = inner.call(req).await;
// Record metrics based on response
match &result {
Ok(response) => {
// Check gRPC status from response
if is_grpc_success(response) {
| {
"chunk": 0,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_6066888807983657858_1 | clm | mini_chunk | // connector-service/backend/external-services/src/shared_metrics.rs
GRPC_SERVER_REQUESTS_SUCCESSFUL
.with_label_values(&[&method_name, &service_name, &connector])
.inc();
}
}
Err(_) => {
// Network/transport level error
}
}
// Record latency
let duration = start_time.elapsed().as_secs_f64();
GRPC_SERVER_REQUEST_LATENCY
.with_label_values(&[&method_name, &service_name, &connector])
.observe(duration);
result
})
}
}
// Extract gRPC method name from HTTP request
fn extract_grpc_method_name<B>(req: &hyper::Request<B>) -> String {
let path = req.uri().path();
if let Some(method) = path.rfind('/') {
let method_name = &path[method + 1..];
if !method_name.is_empty() {
return method_name.to_string();
}
}
"unknown_method".to_string()
}
fn extract_grpc_service_name<B>(req: &hyper::Request<B>) -> String {
let path = req.uri().path();
if let Some(pos) = path.rfind('/') {
let full_service = &path[1..pos];
if let Some(service_name) = full_service.rsplit('.').next() {
return service_name.to_string();
}
}
"unknown_service".to_string()
}
// Extract connector information from request
fn extract_connector_from_request<B>(req: &hyper::Request<B>) -> String {
if let Some(connector) = req.headers().get("x-connector") {
if let Ok(connector_str) = connector.to_str() {
return connector_str.to_string();
}
}
"unknown".to_string()
}
// Check if gRPC response indicates success
fn is_grpc_success<B>(response: &hyper::Response<B>) -> bool {
// gRPC success is based on grpc-status header, not HTTP status
if let Some(grpc_status) = response.headers().get("grpc-status") {
if let Ok(status_str) = grpc_status.to_str() {
if let Ok(status_code) = status_str.parse::<i32>() {
if status_code == 0 {
return true; // gRPC OK
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
true
}
// Metrics handler
pub async fn metrics_handler() -> error_stack::Result<String, MetricsError> {
let mut buffer = Vec::new();
let encoder = TextEncoder::new();
let metric_families = prometheus::gather();
encoder
.encode(&metric_families, &mut buffer)
.change_context(MetricsError::EncodingError)?;
String::from_utf8(buffer).change_context(MetricsError::Utf8Error)
}
#[derive(Debug, thiserror::Error)]
pub enum MetricsError {
#[error("Error encoding metrics")]
EncodingError,
#[error("Error converting metrics to utf8")]
Utf8Error,
}
| {
"chunk": 1,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_0 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
use std::{collections::HashMap, str::FromStr, time::Duration};
use common_enums::ApiClientError;
use common_utils::{
ext_traits::AsyncExt,
lineage,
request::{Method, Request, RequestContent},
};
use domain_types::{
connector_types::{ConnectorResponseHeaders, RawConnectorRequestResponse},
errors::{ApiErrorResponse, ConnectorError},
router_data_v2::RouterDataV2,
router_response_types::Response,
types::Proxy,
};
use hyperswitch_masking::Secret;
use injector;
pub trait ConnectorRequestReference {
fn get_connector_request_reference_id(&self) -> &str;
}
pub trait AdditionalHeaders {
fn get_vault_headers(&self) -> Option<&HashMap<String, Secret<String>>>;
}
impl ConnectorRequestReference for domain_types::connector_types::PaymentFlowData {
fn get_connector_request_reference_id(&self) -> &str {
&self.connector_request_reference_id
}
}
impl AdditionalHeaders for domain_types::connector_types::PaymentFlowData {
fn get_vault_headers(&self) -> Option<&HashMap<String, Secret<String>>> {
self.vault_headers.as_ref()
}
}
impl ConnectorRequestReference for domain_types::connector_types::RefundFlowData {
fn get_connector_request_reference_id(&self) -> &str {
&self.connector_request_reference_id
}
}
impl AdditionalHeaders for domain_types::connector_types::RefundFlowData {
fn get_vault_headers(&self) -> Option<&HashMap<String, Secret<String>>> {
// RefundFlowData might not have vault_headers, so return None
None
}
}
impl ConnectorRequestReference for domain_types::connector_types::DisputeFlowData {
fn get_connector_request_reference_id(&self) -> &str {
&self.connector_request_reference_id
}
}
impl AdditionalHeaders for domain_types::connector_types::DisputeFlowData {
fn get_vault_headers(&self) -> Option<&HashMap<String, Secret<String>>> {
// DisputeFlowData might not have vault_headers, so return None
None
}
}
use common_utils::{
emit_event_with_config,
events::{Event, EventConfig, EventStage, FlowName, MaskedSerdeValue},
};
use error_stack::{report, ResultExt};
use hyperswitch_masking::{ErasedMaskSerialize, ExposeInterface, Maskable};
// TokenData is now imported from hyperswitch_injector
use common_utils::consts;
use injector::{injector_core, HttpMethod, TokenData};
use interfaces::{
connector_integration_v2::BoxedConnectorIntegrationV2,
integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject},
};
use once_cell::sync::OnceCell;
use reqwest::Client;
use serde_json::json;
use tracing::field::Empty;
use crate::shared_metrics as metrics;
pub type Headers = std::collections::HashSet<(String, Maskable<String>)>;
trait ToHttpMethod {
fn to_http_method(&self) -> HttpMethod;
}
impl ToHttpMethod for Method {
fn to_http_method(&self) -> HttpMethod {
match self {
Self::Get => HttpMethod::GET,
Self::Post => HttpMethod::POST,
Self::Put => HttpMethod::PUT,
Self::Patch => HttpMethod::PATCH,
Self::Delete => HttpMethod::DELETE,
}
}
}
#[derive(Debug)]
pub struct EventProcessingParams<'a> {
pub connector_name: &'a str,
pub service_name: &'a str,
pub flow_name: FlowName,
pub event_config: &'a EventConfig,
pub request_id: &'a str,
pub lineage_ids: &'a lineage::LineageIds<'a>,
pub reference_id: &'a Option<String>,
pub shadow_mode: bool,
}
#[tracing::instrument(
name = "execute_connector_processing_step",
skip_all,
fields(
request.headers = Empty,
request.body = Empty,
request.url = Empty,
request.method = Empty,
response.body = Empty,
response.headers = Empty,
response.error_message = Empty,
response.status_code = Empty,
message_ = "Golden Log Line (outgoing)",
latency = Empty,
)
)]
pub async fn execute_connector_processing_step<T, F, ResourceCommonData, Req, Resp>(
proxy: &Proxy,
connector: BoxedConnectorIntegrationV2<'static, F, ResourceCommonData, Req, Resp>,
router_data: RouterDataV2<F, ResourceCommonData, Req, Resp>,
all_keys_required: Option<bool>,
event_params: EventProcessingParams<'_>,
token_data: Option<TokenData>,
call_connector_action: common_enums::CallConnectorAction,
| {
"chunk": 0,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_1 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
) -> CustomResult<RouterDataV2<F, ResourceCommonData, Req, Resp>, ConnectorError>
where
F: Clone + 'static,
T: FlowIntegrity,
Req: Clone + 'static + std::fmt::Debug + GetIntegrityObject<T> + CheckIntegrity<Req, T>,
Resp: Clone + 'static + std::fmt::Debug,
ResourceCommonData: Clone
+ 'static
+ RawConnectorRequestResponse
+ ConnectorResponseHeaders
+ ConnectorRequestReference
+ AdditionalHeaders,
{
let start = tokio::time::Instant::now();
let result = match call_connector_action {
common_enums::CallConnectorAction::HandleResponse(res) => {
let body = Response {
headers: None,
response: res.into(),
status_code: 200,
};
let status_code = body.status_code;
tracing::Span::current().record("status_code", tracing::field::display(status_code));
if let Ok(response) = parse_json_with_bom_handling(&body.response) {
tracing::Span::current().record(
"response.body",
tracing::field::display(response.masked_serialize().unwrap_or(
json!({ "error": "failed to mask serialize connector response"}),
)),
);
}
// Set raw_connector_response BEFORE calling the transformer
let mut updated_router_data = router_data.clone();
if all_keys_required.unwrap_or(true) {
let raw_response_string = strip_bom_and_convert_to_string(&body.response);
updated_router_data
.resource_common_data
.set_raw_connector_response(raw_response_string.map(Into::into));
}
let handle_response_result =
connector.handle_response_v2(&updated_router_data, None, body.clone());
let response = match handle_response_result {
Ok(data) => {
tracing::info!("Transformer completed successfully");
Ok(data)
}
Err(err) => Err(err),
}?;
Ok(response)
}
common_enums::CallConnectorAction::Trigger => {
let mut connector_request = connector.build_request_v2(&router_data.clone())?;
let mut updated_router_data = router_data.clone();
updated_router_data = match &connector_request {
Some(request) => {
updated_router_data
.resource_common_data
.set_raw_connector_request(Some(
extract_raw_connector_request(request).into(),
));
updated_router_data
}
None => updated_router_data,
};
connector_request = connector_request.map(|mut req| {
if event_params.shadow_mode {
req.add_header(
consts::X_REQUEST_ID,
Maskable::Masked(Secret::new(event_params.request_id.to_string())),
);
req.add_header(
consts::X_SOURCE_NAME,
Maskable::Masked(Secret::new(consts::X_CONNECTOR_SERVICE.to_string())),
);
req.add_header(
consts::X_FLOW_NAME,
Maskable::Masked(Secret::new(event_params.flow_name.to_string())),
);
req.add_header(
consts::X_CONNECTOR_NAME,
Maskable::Masked(Secret::new(event_params.connector_name.to_string())),
);
}
req
});
let headers = connector_request
.as_ref()
.map(|connector_request| connector_request.headers.clone())
.unwrap_or_default();
tracing::info!(?headers, "headers of connector request");
let event_headers: HashMap<String, String> = headers
.iter()
.map(|(k, v)| (k.clone(), format!("{v:?}")))
.collect();
let masked_headers = headers
.iter()
| {
"chunk": 1,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_2 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
.fold(serde_json::Map::new(), |mut acc, (k, v)| {
let value = match v {
Maskable::Masked(_) => {
serde_json::Value::String("*** alloc::string::String ***".to_string())
}
Maskable::Normal(iv) => serde_json::Value::String(iv.to_owned()),
};
acc.insert(k.clone(), value);
acc
});
let headers = serde_json::Value::Object(masked_headers);
tracing::Span::current().record("request.headers", tracing::field::display(&headers));
let req = connector_request.as_ref().map(|connector_request| {
let masked_request = match connector_request.body.as_ref() {
Some(request) => match request {
RequestContent::Json(i)
| RequestContent::FormUrlEncoded(i)
| RequestContent::Xml(i) => (**i).masked_serialize().unwrap_or(
json!({ "error": "failed to mask serialize connector request"}),
),
RequestContent::FormData(_) => json!({"request_type": "FORM_DATA"}),
RequestContent::RawBytes(_) => json!({"request_type": "RAW_BYTES"}),
},
None => serde_json::Value::Null,
};
tracing::info!(request=?masked_request, "request of connector");
tracing::Span::current()
.record("request.body", tracing::field::display(&masked_request));
masked_request
});
match connector_request {
Some(request) => {
let url = request.url.clone();
let method = request.method;
metrics::EXTERNAL_SERVICE_TOTAL_API_CALLS
.with_label_values(&[
&method.to_string(),
event_params.service_name,
event_params.connector_name,
])
.inc();
let external_service_start_latency = tokio::time::Instant::now();
tracing::Span::current().record("request.url", tracing::field::display(&url));
tracing::Span::current()
.record("request.method", tracing::field::display(method));
let request_id = event_params.request_id.to_string();
let response = if let Some(token_data) = token_data {
tracing::debug!(
"Creating injector request with token data using unified API"
);
// Extract template and combine headers
let template = request
.body
.as_ref()
.ok_or(ConnectorError::RequestEncodingFailed)?
.get_inner_value()
.expose()
.to_string();
let headers = request
.headers
.iter()
.map(|(key, value)| {
(
key.clone(),
Secret::new(match value {
Maskable::Normal(val) => val.clone(),
Maskable::Masked(val) => val.clone().expose().to_string(),
}),
)
})
.chain(
updated_router_data
.resource_common_data
.get_vault_headers()
.map(|headers| {
headers.iter().map(|(k, v)| (k.clone(), v.clone()))
})
.into_iter()
| {
"chunk": 2,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_3 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
.flatten(),
)
.collect();
// Create injector request
let injector_request = injector::InjectorRequest::new(
request.url.clone(),
request.method.to_http_method(),
template,
token_data,
Some(headers),
proxy
.https_url
.as_ref()
.or(proxy.http_url.as_ref())
.map(|url| Secret::new(url.clone())),
None,
None,
None,
);
// New injector handles HTTP request internally and returns enhanced response
let injector_response = injector_core(injector_request)
.await
.change_context(ConnectorError::RequestEncodingFailed)?;
// Convert injector response to connector service Response format
let response_bytes = serde_json::to_vec(&injector_response.response)
.map_err(|_| ConnectorError::ResponseHandlingFailed)?;
// Convert headers from HashMap<String, String> to reqwest::HeaderMap if present
let headers = injector_response.headers.map(|h| {
let mut header_map = reqwest::header::HeaderMap::new();
for (key, value) in h {
if let (Ok(header_name), Ok(header_value)) = (
reqwest::header::HeaderName::from_bytes(key.as_bytes()),
reqwest::header::HeaderValue::from_str(&value),
) {
header_map.insert(header_name, header_value);
}
}
header_map
});
Ok(Ok(Response {
headers,
response: response_bytes.into(),
status_code: injector_response.status_code, // Use actual status code from connector
}))
} else {
call_connector_api(proxy, request, "execute_connector_processing_step")
.await
.change_context(ConnectorError::RequestEncodingFailed)
.inspect_err(|err| {
info_log(
"NETWORK_ERROR",
&json!(format!(
"Failed getting response from connector. Error: {:?}",
err
)),
);
})
};
let external_service_elapsed = external_service_start_latency.elapsed();
metrics::EXTERNAL_SERVICE_API_CALLS_LATENCY
.with_label_values(&[
&method.to_string(),
event_params.service_name,
event_params.connector_name,
])
.observe(external_service_elapsed.as_secs_f64());
tracing::info!(?response, "response from connector");
// Extract status code BEFORE creating event - one liner
let status_code = response.as_ref().ok().map(|result| match result {
Ok(body) | Err(body) => i32::from(body.status_code),
});
// Construct masked request for event
let masked_request_data = req.as_ref().and_then(|r| {
MaskedSerdeValue::from_masked_optional(r, "connector_request")
| {
"chunk": 3,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_4 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
});
let latency =
u64::try_from(external_service_elapsed.as_millis()).unwrap_or(u64::MAX);
// Create single event (response_data will be set by connector)
let mut event = Event {
request_id: request_id.to_string(),
timestamp: chrono::Utc::now().timestamp().into(),
flow_type: event_params.flow_name,
connector: event_params.connector_name.to_string(),
url: Some(url.clone()),
stage: EventStage::ConnectorCall,
latency_ms: Some(latency),
status_code,
request_data: masked_request_data,
response_data: None, // Will be set by connector via set_response_body
headers: event_headers,
additional_fields: HashMap::new(),
lineage_ids: event_params.lineage_ids.to_owned(),
};
event.add_reference_id(event_params.reference_id.as_deref());
let result = match response {
Ok(body) => {
let response = match body {
Ok(body) => {
let status_code = body.status_code;
tracing::Span::current().record(
"status_code",
tracing::field::display(status_code),
);
let is_source_verified = connector.verify(&updated_router_data, interfaces::verification::ConnectorSourceVerificationSecrets::AuthHeaders(updated_router_data.connector_auth_type.clone()), &body.response)?;
if !is_source_verified {
return Err(error_stack::report!(
ConnectorError::SourceVerificationFailed
));
}
if all_keys_required.unwrap_or(true) {
let raw_response_string =
strip_bom_and_convert_to_string(&body.response);
updated_router_data
.resource_common_data
.set_raw_connector_response(
raw_response_string.map(Into::into),
);
// Set response headers if available
updated_router_data
.resource_common_data
.set_connector_response_headers(body.headers.clone());
}
let handle_response_result = connector.handle_response_v2(
&updated_router_data,
Some(&mut event),
body.clone(),
);
// Log response body and headers using properly masked data from connector
if let Some(response_data) = &event.response_data {
tracing::Span::current().record(
"response.body",
tracing::field::display(response_data.inner()),
);
}
// Log response headers from event (already masked)
tracing::Span::current().record(
"response.headers",
tracing::field::debug(&event.headers),
| {
"chunk": 4,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_5 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
);
match handle_response_result {
Ok(data) => {
tracing::info!("Transformer completed successfully");
Ok(data)
}
Err(err) => Err(err),
}?
}
Err(body) => {
metrics::EXTERNAL_SERVICE_API_CALLS_ERRORS
.with_label_values(&[
&method.to_string(),
event_params.service_name,
event_params.connector_name,
body.status_code.to_string().as_str(),
])
.inc();
if all_keys_required.unwrap_or(true) {
let raw_response_string =
strip_bom_and_convert_to_string(&body.response);
updated_router_data
.resource_common_data
.set_raw_connector_response(
raw_response_string.map(Into::into),
);
updated_router_data
.resource_common_data
.set_connector_response_headers(body.headers.clone());
}
let error = match body.status_code {
500..=511 => connector.get_5xx_error_response(
body.clone(),
Some(&mut event),
)?,
_ => connector.get_error_response_v2(
body.clone(),
Some(&mut event),
)?,
};
tracing::Span::current().record(
"response.error_message",
tracing::field::display(&error.message),
);
tracing::Span::current().record(
"response.status_code",
tracing::field::display(error.status_code),
);
updated_router_data.response = Err(error);
updated_router_data
}
};
Ok(response)
}
Err(err) => {
tracing::Span::current().record("url", tracing::field::display(url));
Err(err.change_context(ConnectorError::ProcessingStepFailed(None)))
}
};
emit_event_with_config(event, event_params.event_config);
result
}
None => Ok(router_data),
}
}
};
let result_with_integrity_check = match result {
Ok(data) => {
data.request
.check_integrity(&data.request.clone(), None)
.map_err(|err| ConnectorError::IntegrityCheckFailed {
field_names: err.field_names,
connector_transaction_id: err.connector_transaction_id,
})?;
Ok(data)
}
Err(err) => Err(err),
};
let elapsed = start.elapsed().as_millis();
| {
"chunk": 5,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_6 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
tracing::Span::current().record("latency", elapsed);
tracing::info!(tag = ?Tag::OutgoingApi, log_type = "api", "Outgoing Request completed");
result_with_integrity_check
}
pub enum ApplicationResponse<R> {
Json(R),
}
pub type CustomResult<T, E> = error_stack::Result<T, E>;
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
pub type RouterResponse<T> = CustomResult<ApplicationResponse<T>, ApiErrorResponse>;
pub async fn call_connector_api(
proxy: &Proxy,
request: Request,
_flow_name: &str,
) -> CustomResult<Result<Response, Response>, ApiClientError> {
let url =
reqwest::Url::parse(&request.url).change_context(ApiClientError::UrlEncodingFailed)?;
let should_bypass_proxy = proxy.bypass_proxy_urls.contains(&url.to_string());
let client = create_client(
proxy,
should_bypass_proxy,
request.certificate,
request.certificate_key,
)?;
let headers = request.headers.construct_header_map()?;
// Process and log the request body based on content type
let request = {
match request.method {
Method::Get => client.get(url),
Method::Post => {
let client = client.post(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
// For XML content, we need to extract the XML string properly
// The payload implements a custom Serialize that generates XML content
let body = serde_json::to_string(&payload)
.change_context(ApiClientError::UrlEncodingFailed)?;
// Properly deserialize the JSON string to extract clean XML
let xml_body = if body.starts_with('"') && body.ends_with('"') {
// This is a JSON-encoded string, deserialize it properly
serde_json::from_str::<String>(&body)
.change_context(ApiClientError::UrlEncodingFailed)?
} else {
// This is already the raw body content
body
};
client.body(xml_body).header("Content-Type", "text/xml")
}
Some(RequestContent::FormData(form)) => client.multipart(form),
_ => client,
}
}
Method::Put => {
let client = client.put(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = serde_json::to_string(&payload)
.change_context(ApiClientError::UrlEncodingFailed)?;
let xml_body = if body.starts_with('"') && body.ends_with('"') {
serde_json::from_str::<String>(&body)
.change_context(ApiClientError::UrlEncodingFailed)?
} else {
body
};
client.body(xml_body).header("Content-Type", "text/xml")
}
Some(RequestContent::FormData(form)) => client.multipart(form),
_ => client,
}
}
Method::Patch => {
let client = client.patch(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = serde_json::to_string(&payload)
.change_context(ApiClientError::UrlEncodingFailed)?;
| {
"chunk": 6,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_7 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
let xml_body = if body.starts_with('"') && body.ends_with('"') {
serde_json::from_str::<String>(&body)
.change_context(ApiClientError::UrlEncodingFailed)?
} else {
body
};
client.body(xml_body).header("Content-Type", "text/xml")
}
Some(RequestContent::FormData(form)) => client.multipart(form),
_ => client,
}
}
Method::Delete => {
let client = client.delete(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = serde_json::to_string(&payload)
.change_context(ApiClientError::UrlEncodingFailed)?;
let xml_body = if body.starts_with('"') && body.ends_with('"') {
serde_json::from_str::<String>(&body)
.change_context(ApiClientError::UrlEncodingFailed)?
} else {
body
};
client.body(xml_body).header("Content-Type", "text/xml")
}
Some(RequestContent::FormData(form)) => client.multipart(form),
_ => client,
}
}
}
.add_headers(headers)
};
let send_request = async {
request.send().await.map_err(|error| {
let api_error = match error {
error if error.is_timeout() => ApiClientError::RequestTimeoutReceived,
_ => ApiClientError::RequestNotSent(error.to_string()),
};
info_log(
"REQUEST_FAILURE",
&json!(format!("Unable to send request to connector.",)),
);
report!(api_error)
})
};
let response = send_request.await;
handle_response(response).await
}
pub fn create_client(
proxy_config: &Proxy,
should_bypass_proxy: bool,
_client_certificate: Option<Secret<String>>,
_client_certificate_key: Option<Secret<String>>,
) -> CustomResult<Client, ApiClientError> {
get_base_client(proxy_config, should_bypass_proxy)
// match (client_certificate, client_certificate_key) {
// (Some(encoded_certificate), Some(encoded_certificate_key)) => {
// let client_builder = get_client_builder(proxy_config, should_bypass_proxy)?;
// let identity = create_identity_from_certificate_and_key(
// encoded_certificate.clone(),
// encoded_certificate_key,
// )?;
// let certificate_list = create_certificate(encoded_certificate)?;
// let client_builder = certificate_list
// .into_iter()
// .fold(client_builder, |client_builder, certificate| {
// client_builder.add_root_certificate(certificate)
// });
// client_builder
// .identity(identity)
// .use_rustls_tls()
// .build()
// .change_context(ApiClientError::ClientConstructionFailed)
// .inspect_err(|err| {
// info_log(
// "ERROR",
// &json!(format!(
// "Failed to construct client with certificate and certificate key. Error: {:?}",
// err
// )),
// );
// })
// }
// _ => ,
// }
}
static NON_PROXIED_CLIENT: OnceCell<Client> = OnceCell::new();
static PROXIED_CLIENT: OnceCell<Client> = OnceCell::new();
fn get_base_client(
proxy_config: &Proxy,
should_bypass_proxy: bool,
) -> CustomResult<Client, ApiClientError> {
Ok(if should_bypass_proxy
|| (proxy_config.http_url.is_none() && proxy_config.https_url.is_none())
{
&NON_PROXIED_CLIENT
} else {
| {
"chunk": 7,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_8 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
&PROXIED_CLIENT
}
.get_or_try_init(|| {
get_client_builder(proxy_config, should_bypass_proxy)?
.build()
.change_context(ApiClientError::ClientConstructionFailed)
.inspect_err(|err| {
info_log(
"ERROR",
&json!(format!("Failed to construct base client. Error: {:?}", err)),
);
})
})?
.clone())
}
fn load_custom_ca_certificate_from_content(
mut client_builder: reqwest::ClientBuilder,
cert_content: &str,
) -> CustomResult<reqwest::ClientBuilder, ApiClientError> {
let certificate = reqwest::Certificate::from_pem(cert_content.as_bytes())
.change_context(ApiClientError::InvalidProxyConfiguration)
.attach_printable("Failed to parse certificate PEM from provided content")?;
client_builder = client_builder.add_root_certificate(certificate);
Ok(client_builder)
}
fn get_client_builder(
proxy_config: &Proxy,
should_bypass_proxy: bool,
) -> CustomResult<reqwest::ClientBuilder, ApiClientError> {
let mut client_builder = Client::builder()
.redirect(reqwest::redirect::Policy::none())
.pool_idle_timeout(Duration::from_secs(
proxy_config
.idle_pool_connection_timeout
.unwrap_or_default(),
));
if should_bypass_proxy {
return Ok(client_builder);
}
// Attach MITM certificate if enabled
if proxy_config.mitm_proxy_enabled {
if let Some(cert_content) = &proxy_config.mitm_ca_cert {
if !cert_content.trim().is_empty() {
client_builder =
load_custom_ca_certificate_from_content(client_builder, cert_content.trim())?;
}
}
}
// Proxy all HTTPS traffic through the configured HTTPS proxy
if let Some(url) = proxy_config.https_url.as_ref() {
client_builder = client_builder.proxy(
reqwest::Proxy::https(url)
.change_context(ApiClientError::InvalidProxyConfiguration)
.inspect_err(|err| {
info_log(
"PROXY_ERROR",
&json!(format!("HTTPS proxy configuration error. Error: {:?}", err)),
);
})?,
);
}
// Proxy all HTTP traffic through the configured HTTP proxy
if let Some(url) = proxy_config.http_url.as_ref() {
client_builder = client_builder.proxy(
reqwest::Proxy::http(url)
.change_context(ApiClientError::InvalidProxyConfiguration)
.inspect_err(|err| {
info_log(
"PROXY_ERROR",
&json!(format!("HTTP proxy configuration error. Error: {:?}", err)),
);
})?,
);
}
Ok(client_builder)
}
// pub fn create_identity_from_certificate_and_key(
// encoded_certificate: hyperswitch_masking::Secret<String>,
// encoded_certificate_key: hyperswitch_masking::Secret<String>,
// ) -> Result<reqwest::Identity, error_stack::Report<ApiClientError>> {
// let decoded_certificate = BASE64_ENGINE
// .decode(encoded_certificate.expose())
// .change_context(ApiClientError::CertificateDecodeFailed)?;
// let decoded_certificate_key = BASE64_ENGINE
// .decode(encoded_certificate_key.expose())
// .change_context(ApiClientError::CertificateDecodeFailed)?;
// let certificate = String::from_utf8(decoded_certificate)
// .change_context(ApiClientError::CertificateDecodeFailed)?;
// let certificate_key = String::from_utf8(decoded_certificate_key)
// .change_context(ApiClientError::CertificateDecodeFailed)?;
// let key_chain = format!("{}{}", certificate_key, certificate);
// reqwest::Identity::from_pem(key_chain.as_bytes())
// .change_context(ApiClientError::CertificateDecodeFailed)
// }
// pub fn create_certificate(
// encoded_certificate: hyperswitch_masking::Secret<String>,
// ) -> Result<Vec<reqwest::Certificate>, error_stack::Report<ApiClientError>> {
// let decoded_certificate = BASE64_ENGINE
// .decode(encoded_certificate.expose())
// .change_context(ApiClientError::CertificateDecodeFailed)?;
| {
"chunk": 8,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_9 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
// let certificate = String::from_utf8(decoded_certificate)
// .change_context(ApiClientError::CertificateDecodeFailed)?;
// reqwest::Certificate::from_pem_bundle(certificate.as_bytes())
// .change_context(ApiClientError::CertificateDecodeFailed)
// }
async fn handle_response(
response: CustomResult<reqwest::Response, ApiClientError>,
) -> CustomResult<Result<Response, Response>, ApiClientError> {
response
.async_map(|resp| async {
let status_code = resp.status().as_u16();
let headers = Some(resp.headers().to_owned());
match status_code {
200..=202 | 302 | 204 => {
let response = resp
.bytes()
.await
.change_context(ApiClientError::ResponseDecodingFailed)?;
Ok(Ok(Response {
headers,
response,
status_code,
}))
}
500..=599 => {
let bytes = resp.bytes().await.map_err(|error| {
report!(error).change_context(ApiClientError::ResponseDecodingFailed)
})?;
Ok(Err(Response {
headers,
response: bytes,
status_code,
}))
}
400..=499 => {
let bytes = resp.bytes().await.map_err(|error| {
report!(error).change_context(ApiClientError::ResponseDecodingFailed)
})?;
Ok(Err(Response {
headers,
response: bytes,
status_code,
}))
}
_ => {
info_log(
"UNEXPECTED_RESPONSE",
&json!("Unexpected response from server."),
);
Err(report!(ApiClientError::UnexpectedServerResponse))
}
}
})
.await?
}
/// Helper function to remove BOM from response bytes and convert to string
fn strip_bom_and_convert_to_string(response_bytes: &[u8]) -> Option<String> {
String::from_utf8(response_bytes.to_vec()).ok().map(|s| {
// Remove BOM if present (UTF-8 BOM is 0xEF, 0xBB, 0xBF)
if s.starts_with('\u{FEFF}') {
s.trim_start_matches('\u{FEFF}').to_string()
} else {
s
}
})
}
fn extract_raw_connector_request(connector_request: &Request) -> String {
// Extract actual body content
let body_content = match connector_request.body.as_ref() {
Some(request) => {
let inner_value = request.get_inner_value();
serde_json::from_str(&inner_value.expose()).unwrap_or_else(|_| {
tracing::warn!("failed to parse JSON body in extract_raw_connector_request");
json!({ "error": "failed to parse JSON body" })
})
}
None => serde_json::Value::Null,
};
// Extract unmasked headers
let headers_content = connector_request
.headers
.iter()
.map(|(k, v)| {
let value = match v {
Maskable::Normal(val) => val.clone(),
Maskable::Masked(val) => val.clone().expose().to_string(),
};
(k.clone(), value)
})
.collect::<HashMap<_, _>>();
// Create complete request with actual content
json!({
"url": connector_request.url,
"method": connector_request.method.to_string(),
"headers": headers_content,
"body": body_content
})
.to_string()
}
/// Helper function to parse JSON from response bytes with BOM handling
fn parse_json_with_bom_handling(
response_bytes: &[u8],
) -> Result<serde_json::Value, serde_json::Error> {
// Try direct parsing first (most common case)
match serde_json::from_slice::<serde_json::Value>(response_bytes) {
Ok(value) => Ok(value),
Err(_) => {
// If direct parsing fails, try after removing BOM
let cleaned_response = if response_bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
| {
"chunk": 9,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_external-services_-7416499650036175072_10 | clm | mini_chunk | // connector-service/backend/external-services/src/service.rs
// UTF-8 BOM detected, remove it
#[allow(clippy::indexing_slicing)]
&response_bytes[3..]
} else {
response_bytes
};
serde_json::from_slice::<serde_json::Value>(cleaned_response)
}
}
}
pub(super) trait HeaderExt {
fn construct_header_map(self) -> CustomResult<reqwest::header::HeaderMap, ApiClientError>;
}
impl HeaderExt for Headers {
fn construct_header_map(self) -> CustomResult<reqwest::header::HeaderMap, ApiClientError> {
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
self.into_iter().try_fold(
HeaderMap::new(),
|mut header_map, (header_name, header_value)| {
let header_name = HeaderName::from_str(&header_name)
.change_context(ApiClientError::HeaderMapConstructionFailed)?;
let header_value = header_value.into_inner();
let header_value = HeaderValue::from_str(&header_value)
.change_context(ApiClientError::HeaderMapConstructionFailed)?;
header_map.append(header_name, header_value);
Ok(header_map)
},
)
}
}
pub(super) trait RequestBuilderExt {
fn add_headers(self, headers: reqwest::header::HeaderMap) -> Self;
}
impl RequestBuilderExt for reqwest::RequestBuilder {
fn add_headers(mut self, headers: reqwest::header::HeaderMap) -> Self {
self = self.headers(headers);
self
}
}
#[derive(Debug, Default, serde::Deserialize, Clone, strum::EnumString)]
pub enum Tag {
/// General.
#[default]
General,
/// Redis: get.
RedisGet,
/// Redis: set.
RedisSet,
/// API: incoming web request.
ApiIncomingRequest,
/// API: outgoing web request body.
ApiOutgoingRequestBody,
/// API: outgoingh headers
ApiOutgoingRequestHeaders,
/// End Request
EndRequest,
/// Call initiated to connector.
InitiatedToConnector,
/// Incoming response
IncomingApi,
/// Api Outgoing Request
OutgoingApi,
}
#[inline]
pub fn debug_log(action: &str, message: &serde_json::Value) {
tracing::debug!(tags = %action, json_value= %message);
}
#[inline]
pub fn info_log(action: &str, message: &serde_json::Value) {
tracing::info!(tags = %action, json_value= %message);
}
#[inline]
pub fn error_log(action: &str, message: &serde_json::Value) {
tracing::error!(tags = %action, json_value= %message);
}
#[inline]
pub fn warn_log(action: &str, message: &serde_json::Value) {
tracing::warn!(tags = %action, json_value= %message);
}
| {
"chunk": 10,
"crate": "external-services",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_3648700667243119668_0 | clm | mini_chunk | // connector-service/backend/domain_types/src/router_request_types.rs
use std::str::FromStr;
use common_enums::{self, CaptureMethod, Currency};
use common_utils::{
pii::{self, IpAddress},
types::SemanticVersion,
Email, MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_masking::Secret;
use serde::Serialize;
use crate::utils::ForeignFrom;
use grpc_api_types::payments;
use crate::{
errors,
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes},
utils,
};
pub type Error = error_stack::Report<crate::errors::ConnectorError>;
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct BrowserInformation {
pub color_depth: Option<u8>,
pub java_enabled: Option<bool>,
pub java_script_enabled: Option<bool>,
pub language: Option<String>,
pub screen_height: Option<u32>,
pub screen_width: Option<u32>,
pub time_zone: Option<i32>,
pub ip_address: Option<std::net::IpAddr>,
pub accept_header: Option<String>,
pub user_agent: Option<String>,
pub os_type: Option<String>,
pub os_version: Option<String>,
pub device_model: Option<String>,
pub accept_language: Option<String>,
pub referer: Option<String>,
}
impl BrowserInformation {
pub fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> {
let ip_address = self
.ip_address
.ok_or_else(utils::missing_field_err("browser_info.ip_address"))?;
Ok(Secret::new(ip_address.to_string()))
}
pub fn get_accept_header(&self) -> Result<String, Error> {
self.accept_header
.clone()
.ok_or_else(utils::missing_field_err("browser_info.accept_header"))
}
pub fn get_language(&self) -> Result<String, Error> {
self.language
.clone()
.ok_or_else(utils::missing_field_err("browser_info.language"))
}
pub fn get_screen_height(&self) -> Result<u32, Error> {
self.screen_height
.ok_or_else(utils::missing_field_err("browser_info.screen_height"))
}
pub fn get_screen_width(&self) -> Result<u32, Error> {
self.screen_width
.ok_or_else(utils::missing_field_err("browser_info.screen_width"))
}
pub fn get_color_depth(&self) -> Result<u8, Error> {
self.color_depth
.ok_or_else(utils::missing_field_err("browser_info.color_depth"))
}
pub fn get_user_agent(&self) -> Result<String, Error> {
self.user_agent
.clone()
.ok_or_else(utils::missing_field_err("browser_info.user_agent"))
}
pub fn get_time_zone(&self) -> Result<i32, Error> {
self.time_zone
.ok_or_else(utils::missing_field_err("browser_info.time_zone"))
}
pub fn get_java_enabled(&self) -> Result<bool, Error> {
self.java_enabled
.ok_or_else(utils::missing_field_err("browser_info.java_enabled"))
}
pub fn get_java_script_enabled(&self) -> Result<bool, Error> {
self.java_script_enabled
.ok_or_else(utils::missing_field_err("browser_info.java_script_enabled"))
}
pub fn get_referer(&self) -> Result<String, Error> {
self.referer
.clone()
.ok_or_else(utils::missing_field_err("browser_info.referer"))
}
}
#[derive(Debug, Default, Clone)]
pub enum SyncRequestType {
MultipleCaptureSync(Vec<String>),
#[default]
SinglePaymentSync,
}
#[derive(Debug, Default, Clone)]
pub struct PaymentsCancelData {
pub amount: Option<i64>,
pub currency: Option<Currency>,
pub connector_transaction_id: String,
pub cancellation_reason: Option<String>,
pub connector_meta: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
// minor amount data for amount framework
pub minor_amount: Option<MinorUnit>,
pub webhook_url: Option<String>,
pub capture_method: Option<CaptureMethod>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AuthenticationData {
pub trans_status: Option<common_enums::TransactionStatus>,
pub eci: Option<String>,
pub cavv: Option<Secret<String>>,
// This is mastercard specific field
pub ucaf_collection_indicator: Option<String>,
pub threeds_server_transaction_id: Option<String>,
| {
"chunk": 0,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_3648700667243119668_1 | clm | mini_chunk | // connector-service/backend/domain_types/src/router_request_types.rs
pub message_version: Option<SemanticVersion>,
pub ds_trans_id: Option<String>,
pub acs_transaction_id: Option<String>,
pub transaction_id: Option<String>,
}
impl TryFrom<payments::AuthenticationData> for AuthenticationData {
type Error = error_stack::Report<errors::ApplicationErrorResponse>;
fn try_from(value: payments::AuthenticationData) -> Result<Self, Self::Error> {
let payments::AuthenticationData {
eci,
cavv,
threeds_server_transaction_id,
message_version,
ds_transaction_id,
trans_status,
acs_transaction_id,
transaction_id,
ucaf_collection_indicator,
} = value;
let threeds_server_transaction_id =
utils::extract_optional_connector_request_reference_id(&threeds_server_transaction_id);
let message_version = message_version.map(|message_version|{
SemanticVersion::from_str(&message_version).change_context(errors::ApplicationErrorResponse::BadRequest(errors::ApiError{
sub_code: "INVALID_SEMANTIC_VERSION_DATA".to_owned(),
error_identifier: 400,
error_message: "Invalid semantic version format. Expected format: 'major.minor.patch' (e.g., '2.1.0')".to_string(),
error_object: Some(serde_json::json!({
"field": "message_version",
"provided_value": message_version,
"expected_format": "major.minor.patch",
"examples": ["1.0.0", "2.1.0", "2.2.0"],
"validation_rule": "Must be in format X.Y.Z where X, Y, Z are non-negative integers"
})),
}))
}).transpose()?;
let trans_status = trans_status.map(|trans_status|{
grpc_api_types::payments::TransactionStatus::try_from(trans_status).change_context(errors::ApplicationErrorResponse::BadRequest(errors::ApiError{
sub_code: "INVALID_TRANSACTION_STATUS".to_owned(),
error_identifier: 400,
error_message: "Invalid transaction status format. Expected one of the valid 3DS transaction status values".to_string(),
error_object: Some(serde_json::json!({
"field": "transaction_status",
"provided_value": trans_status,
"expected_values": [
"Y (Success)",
"N (Failure)",
"U (Verification Not Performed)",
"A (Not Verified)",
"R (Rejected)",
"C (Challenge Required)",
"D (Challenge Required - Decoupled Authentication)",
"I (Information Only)"
],
"validation_rule": "Must be one of the valid 3DS transaction status codes (Y, N, U, A, R, C, D, I)",
"description": "Transaction status represents the result of 3D Secure authentication/verification process"
})),
}))}).transpose()?.map(common_enums::TransactionStatus::foreign_from);
Ok(Self {
ucaf_collection_indicator,
trans_status,
eci,
cavv: cavv.map(Secret::new),
threeds_server_transaction_id,
message_version,
ds_trans_id: ds_transaction_id,
acs_transaction_id,
transaction_id,
})
}
}
impl utils::ForeignFrom<AuthenticationData> for payments::AuthenticationData {
fn foreign_from(value: AuthenticationData) -> Self {
use hyperswitch_masking::ExposeInterface;
Self {
ucaf_collection_indicator: value.ucaf_collection_indicator,
eci: value.eci,
cavv: value.cavv.map(|cavv| cavv.expose()),
threeds_server_transaction_id: value.threeds_server_transaction_id.map(|id| {
payments::Identifier {
id_type: Some(payments::identifier::IdType::Id(id)),
}
}),
message_version: value.message_version.map(|v| v.to_string()),
ds_transaction_id: value.ds_trans_id,
trans_status: value
.trans_status
| {
"chunk": 1,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_3648700667243119668_2 | clm | mini_chunk | // connector-service/backend/domain_types/src/router_request_types.rs
.map(payments::TransactionStatus::foreign_from)
.map(i32::from),
acs_transaction_id: value.acs_transaction_id,
transaction_id: value.transaction_id,
}
}
}
#[derive(Debug, Clone)]
pub struct ConnectorCustomerData<T: PaymentMethodDataTypes> {
pub description: Option<String>,
pub email: Option<pii::Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
pub preprocessing_id: Option<String>,
pub payment_method_data: Option<PaymentMethodData<T>>,
// pub split_payments: Option<SplitPaymentsRequest>,
}
impl<T: PaymentMethodDataTypes> ConnectorCustomerData<T> {
pub fn get_email(&self) -> Result<Email, Error> {
self.email
.clone()
.ok_or_else(utils::missing_field_err("email"))
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AuthoriseIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CreateOrderIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SetupMandateIntegrityObject {
/// Authorise amount
pub amount: Option<MinorUnit>,
/// Authorise currency
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RepeatPaymentIntegrityObject {
/// Payment amount
pub amount: i64,
/// Payment currency
pub currency: Currency,
/// Mandate reference
pub mandate_reference: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PaymentSynIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PaymentVoidIntegrityObject {
pub connector_transaction_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PaymentVoidPostCaptureIntegrityObject {
pub connector_transaction_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RefundIntegrityObject {
pub refund_amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CaptureIntegrityObject {
pub amount_to_capture: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AcceptDisputeIntegrityObject {
pub connector_dispute_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DefendDisputeIntegrityObject {
pub connector_dispute_id: String,
pub defense_reason_code: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RefundSyncIntegrityObject {
pub connector_transaction_id: String,
pub connector_refund_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SubmitEvidenceIntegrityObject {
pub connector_dispute_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SessionTokenIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AccessTokenIntegrityObject {
pub grant_type: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CreateConnectorCustomerIntegrityObject {
pub customer_id: Option<Secret<String>>,
pub email: Option<Secret<String>>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PaymentMethodTokenIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PreAuthenticateIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AuthenticateIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PostAuthenticateIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
| {
"chunk": 2,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_0 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
use core::result::Result;
use std::{borrow::Cow, collections::HashMap, fmt::Debug, str::FromStr};
use crate::utils::extract_connector_request_reference_id;
use common_enums::{CaptureMethod, CardNetwork, CountryAlpha2, PaymentMethod, PaymentMethodType};
use common_utils::{
consts::{self, NO_ERROR_CODE, X_EXTERNAL_VAULT_METADATA},
id_type::CustomerId,
metadata::MaskedMetadata,
pii::Email,
Method,
};
use error_stack::{report, ResultExt};
use grpc_api_types::payments::{
AcceptDisputeResponse, ConnectorState, DisputeDefendRequest, DisputeDefendResponse,
DisputeResponse, DisputeServiceSubmitEvidenceResponse, PaymentServiceAuthorizeRequest,
PaymentServiceAuthorizeResponse, PaymentServiceCaptureResponse, PaymentServiceGetResponse,
PaymentServiceRegisterRequest, PaymentServiceRegisterResponse,
PaymentServiceVoidPostCaptureResponse, PaymentServiceVoidRequest, PaymentServiceVoidResponse,
RefundResponse,
};
use hyperswitch_masking::{ExposeInterface, Secret};
use serde::Serialize;
use tracing::info;
use utoipa::ToSchema;
/// Extract vault-related headers from gRPC metadata
fn extract_headers_from_metadata(
metadata: &MaskedMetadata,
) -> Option<HashMap<String, Secret<String>>> {
let mut vault_headers = HashMap::new();
if let Some(vault_creds) = metadata.get(X_EXTERNAL_VAULT_METADATA) {
vault_headers.insert(X_EXTERNAL_VAULT_METADATA.to_string(), vault_creds);
}
if vault_headers.is_empty() {
None
} else {
Some(vault_headers)
}
}
// For decoding connector_meta_data and Engine trait - base64 crate no longer needed here
use crate::{
connector_flow::{
Accept, Authorize, Capture, CreateOrder, CreateSessionToken, DefendDispute, PSync,
PaymentMethodToken, RSync, Refund, RepeatPayment, SetupMandate, SubmitEvidence, Void,
VoidPC,
},
connector_types::{
AcceptDisputeData, AccessTokenRequestData, ConnectorCustomerData,
ConnectorMandateReferenceId, ConnectorResponseHeaders, ContinueRedirectionResponse,
DisputeDefendData, DisputeFlowData, DisputeResponseData, DisputeWebhookDetailsResponse,
MandateReferenceId, MultipleCaptureRequestData, PaymentCreateOrderData,
PaymentCreateOrderResponse, PaymentFlowData, PaymentMethodTokenResponse,
PaymentMethodTokenizationData, PaymentVoidData, PaymentsAuthenticateData,
PaymentsAuthorizeData, PaymentsCaptureData, PaymentsPostAuthenticateData,
PaymentsPreAuthenticateData, PaymentsResponseData, PaymentsSyncData,
RawConnectorRequestResponse, RefundFlowData, RefundSyncData, RefundWebhookDetailsResponse,
RefundsData, RefundsResponseData, RepeatPaymentData, ResponseId, SessionTokenRequestData,
SessionTokenResponseData, SetupMandateRequestData, SubmitEvidenceData,
WebhookDetailsResponse,
},
errors::{ApiError, ApplicationErrorResponse},
mandates::{self, MandateData},
payment_address,
payment_address::{Address, AddressDetails, PaymentAddress, PhoneDetails},
payment_method_data,
payment_method_data::{
DefaultPCIHolder, PaymentMethodData, PaymentMethodDataTypes, RawCardNumber,
VaultTokenHolder,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
RecurringMandatePaymentData,
},
router_data_v2::RouterDataV2,
router_request_types,
router_request_types::BrowserInformation,
router_response_types,
utils::{extract_merchant_id_from_metadata, ForeignFrom, ForeignTryFrom},
};
#[derive(Clone, serde::Deserialize, Debug, Default)]
pub struct Connectors {
// Added pub
pub adyen: ConnectorParams,
pub razorpay: ConnectorParams,
pub razorpayv2: ConnectorParams,
pub fiserv: ConnectorParams,
pub elavon: ConnectorParams, // Add your connector params
pub xendit: ConnectorParams,
pub checkout: ConnectorParams,
pub authorizedotnet: ConnectorParams, // Add your connector params
pub mifinity: ConnectorParams,
pub phonepe: ConnectorParams,
pub cashfree: ConnectorParams,
pub paytm: ConnectorParams,
pub fiuu: ConnectorParams,
pub payu: ConnectorParams,
pub cashtocode: ConnectorParams,
pub novalnet: ConnectorParams,
pub nexinets: ConnectorParams,
| {
"chunk": 0,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_1 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
pub noon: ConnectorParams,
pub braintree: ConnectorParams,
pub volt: ConnectorParams,
pub bluecode: ConnectorParams,
pub cryptopay: ConnectorParams,
pub helcim: ConnectorParams,
pub dlocal: ConnectorParams,
pub placetopay: ConnectorParams,
pub rapyd: ConnectorParams,
pub aci: ConnectorParams,
pub trustpay: ConnectorParamsWithMoreUrls,
pub stripe: ConnectorParams,
pub cybersource: ConnectorParams,
pub worldpay: ConnectorParams,
pub worldpayvantiv: ConnectorParams,
pub payload: ConnectorParams,
}
#[derive(Clone, serde::Deserialize, Debug, Default)]
pub struct ConnectorParams {
/// base url
#[serde(default)]
pub base_url: String,
#[serde(default)]
pub dispute_base_url: Option<String>,
#[serde(default)]
pub secondary_base_url: Option<String>,
}
impl ConnectorParams {
pub fn new(base_url: String, dispute_base_url: Option<String>) -> Self {
Self {
base_url,
dispute_base_url,
secondary_base_url: None,
}
}
}
#[derive(Debug, serde::Deserialize, Clone, Default)]
pub struct ConnectorParamsWithMoreUrls {
/// base url
pub base_url: String,
/// base url for bank redirects
pub base_url_bank_redirects: String,
}
// Trait to provide access to connectors field
pub trait HasConnectors {
fn connectors(&self) -> &Connectors;
}
impl HasConnectors for PaymentFlowData {
fn connectors(&self) -> &Connectors {
&self.connectors
}
}
impl HasConnectors for RefundFlowData {
fn connectors(&self) -> &Connectors {
&self.connectors
}
}
impl HasConnectors for DisputeFlowData {
fn connectors(&self) -> &Connectors {
&self.connectors
}
}
#[derive(Debug, serde::Deserialize, Clone)]
pub struct Proxy {
pub http_url: Option<String>,
pub https_url: Option<String>,
pub idle_pool_connection_timeout: Option<u64>,
pub bypass_proxy_urls: Vec<String>,
pub mitm_proxy_enabled: bool,
pub mitm_ca_cert: Option<String>,
}
impl ForeignTryFrom<grpc_api_types::payments::CaptureMethod> for common_enums::CaptureMethod {
type Error = ApplicationErrorResponse;
fn foreign_try_from(
value: grpc_api_types::payments::CaptureMethod,
) -> Result<Self, error_stack::Report<Self::Error>> {
match value {
grpc_api_types::payments::CaptureMethod::Automatic => Ok(Self::Automatic),
grpc_api_types::payments::CaptureMethod::Manual => Ok(Self::Manual),
grpc_api_types::payments::CaptureMethod::ManualMultiple => Ok(Self::ManualMultiple),
grpc_api_types::payments::CaptureMethod::Scheduled => Ok(Self::Scheduled),
_ => Ok(Self::Automatic),
}
}
}
impl ForeignTryFrom<grpc_api_types::payments::CardNetwork> for common_enums::CardNetwork {
type Error = ApplicationErrorResponse;
fn foreign_try_from(
network: grpc_api_types::payments::CardNetwork,
) -> Result<Self, error_stack::Report<Self::Error>> {
match network {
grpc_api_types::payments::CardNetwork::Visa => Ok(Self::Visa),
grpc_api_types::payments::CardNetwork::Mastercard => Ok(Self::Mastercard),
grpc_api_types::payments::CardNetwork::Amex => Ok(Self::AmericanExpress),
grpc_api_types::payments::CardNetwork::Jcb => Ok(Self::JCB),
grpc_api_types::payments::CardNetwork::Diners => Ok(Self::DinersClub),
grpc_api_types::payments::CardNetwork::Discover => Ok(Self::Discover),
grpc_api_types::payments::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires),
grpc_api_types::payments::CardNetwork::Unionpay => Ok(Self::UnionPay),
grpc_api_types::payments::CardNetwork::Rupay => Ok(Self::RuPay),
grpc_api_types::payments::CardNetwork::Maestro => Ok(Self::Maestro),
grpc_api_types::payments::CardNetwork::Unspecified => {
Err(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSPECIFIED_CARD_NETWORK".to_owned(),
error_identifier: 401,
error_message: "Card network must be specified".to_owned(),
error_object: None,
})
.into())
}
}
}
}
impl<
| {
"chunk": 1,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_2 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
T: PaymentMethodDataTypes
+ Default
+ Debug
+ Send
+ Eq
+ PartialEq
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ CardConversionHelper<T>,
> ForeignTryFrom<grpc_api_types::payments::PaymentMethod> for PaymentMethodData<T>
{
type Error = ApplicationErrorResponse;
fn foreign_try_from(
value: grpc_api_types::payments::PaymentMethod,
) -> Result<Self, error_stack::Report<Self::Error>> {
tracing::info!("PaymentMethod data received: {:?}", value);
match value.payment_method {
Some(data) => match data {
grpc_api_types::payments::payment_method::PaymentMethod::Card(card_type) => {
match card_type.card_type {
Some(grpc_api_types::payments::card_payment_method_type::CardType::Credit(card)) => {
let card = payment_method_data::Card::<T>::foreign_try_from(card)?;
Ok(PaymentMethodData::Card(card))
},
Some(grpc_api_types::payments::card_payment_method_type::CardType::Debit(card)) => {
let card = payment_method_data::Card::<T>::foreign_try_from(card)?;
Ok(PaymentMethodData::Card(card))},
Some(grpc_api_types::payments::card_payment_method_type::CardType::CardRedirect(_card_redirect)) => {
Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "Card redirect payments are not yet supported".to_owned(),
error_object: None,
})))
},
Some(grpc_api_types::payments::card_payment_method_type::CardType::CreditProxy(card)) => {
let x = payment_method_data::Card::<T>::foreign_try_from(card)?;
Ok(PaymentMethodData::Card(x))
},
Some(grpc_api_types::payments::card_payment_method_type::CardType::DebitProxy(card)) => {
let x = payment_method_data::Card::<T>::foreign_try_from(card)?;
Ok(PaymentMethodData::Card(x))
},
None => Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "Card type is required".to_owned(),
error_object: None,
})))
}
}
grpc_api_types::payments::payment_method::PaymentMethod::Token(_token) => Ok(
PaymentMethodData::CardToken(payment_method_data::CardToken {
card_holder_name: None,
card_cvc: None,
}),
),
grpc_api_types::payments::payment_method::PaymentMethod::UpiCollect(
upi_collect,
) => Ok(PaymentMethodData::Upi(
payment_method_data::UpiData::UpiCollect(payment_method_data::UpiCollectData {
vpa_id: upi_collect.vpa_id.map(|vpa| vpa.expose().into()),
}),
)),
grpc_api_types::payments::payment_method::PaymentMethod::UpiIntent(_upi_intent) => {
Ok(PaymentMethodData::Upi(
payment_method_data::UpiData::UpiIntent(
payment_method_data::UpiIntentData {},
),
))
}
grpc_api_types::payments::payment_method::PaymentMethod::UpiQr(_upi_qr) => {
Ok(PaymentMethodData::Upi(
crate::payment_method_data::UpiData::UpiQr(
| {
"chunk": 2,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_3 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
crate::payment_method_data::UpiQrData {},
),
))
}
grpc_api_types::payments::payment_method::PaymentMethod::Reward(_) => {
Ok(PaymentMethodData::Reward)
},
grpc_api_types::payments::payment_method::PaymentMethod::Wallet(wallet_type) => {
match wallet_type.wallet_type {
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::Bluecode(_)) => {
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::BluecodeRedirect{}
))},
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::Mifinity(mifinity_data)) => {
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::Mifinity(
payment_method_data::MifinityData {
date_of_birth: hyperswitch_masking::Secret::<time::Date>::foreign_try_from(mifinity_data.date_of_birth.ok_or(
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_DATE_OF_BIRTH".to_owned(),
error_identifier: 400,
error_message: "Missing Date of Birth".to_owned(),
error_object: None,
})
)?.expose())?,
language_preference: mifinity_data.language_preference,
}
)))
},
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::ApplePay(apple_wallet)) => {
let payment_data = apple_wallet.payment_data.ok_or_else(|| {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_APPLE_PAY_PAYMENT_DATA".to_owned(),
error_identifier: 400,
error_message: "Apple Pay payment data is required".to_owned(),
error_object: None,
})
})?;
let applepay_payment_data = match payment_data.payment_data {
Some(grpc_api_types::payments::apple_wallet::payment_data::PaymentData::EncryptedData(encrypted_data)) => {
Ok(payment_method_data::ApplePayPaymentData::Encrypted(encrypted_data))
},
Some(grpc_api_types::payments::apple_wallet::payment_data::PaymentData::DecryptedData(decrypted_data)) => {
Ok(payment_method_data::ApplePayPaymentData::Decrypted(
payment_method_data::ApplePayPredecryptData {
application_primary_account_number: cards::CardNumber::from_str(&decrypted_data.application_primary_account_number).change_context(
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_CARD_NUMBER".to_owned(),
error_identifier: 400,
error_message: "Invalid card number in Apple Pay data".to_owned(),
error_object: None,
})
)?,
application_expiration_month: Secret::new(decrypted_data.application_expiration_month),
application_expiration_year: Secret::new(decrypted_data.application_expiration_year),
| {
"chunk": 3,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_4 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
payment_data: payment_method_data::ApplePayCryptogramData {
online_payment_cryptogram: Secret::new(decrypted_data.payment_data.clone().map(|pd| pd.online_payment_cryptogram).unwrap_or_default()),
eci_indicator: decrypted_data.payment_data.map(|pd| pd.eci_indicator),
},
}
))
},
None => Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_APPLE_PAY_DATA".to_owned(),
error_identifier: 400,
error_message: "Apple Pay payment data is required".to_owned(),
error_object: None,
})))
}?;
let payment_method = apple_wallet.payment_method.ok_or_else(|| {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_APPLE_PAY_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "Apple Pay payment method is required".to_owned(),
error_object: None,
})
})?;
let wallet_data = payment_method_data::ApplePayWalletData {
payment_data: applepay_payment_data,
payment_method: payment_method_data::ApplepayPaymentMethod {
display_name: payment_method.display_name,
network: payment_method.network,
pm_type: payment_method.r#type,
},
transaction_identifier: apple_wallet.transaction_identifier,
};
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::ApplePay(wallet_data)))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::GooglePay(google_wallet)) => {
let info = google_wallet.info.ok_or_else(|| {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_GOOGLE_PAY_INFO".to_owned(),
error_identifier: 400,
error_message: "Google Pay payment method info is required".to_owned(),
error_object: None,
})
})?;
let tokenization_data = google_wallet.tokenization_data.ok_or_else(|| {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_GOOGLE_PAY_TOKENIZATION_DATA".to_owned(),
error_identifier: 400,
error_message: "Google Pay tokenization data is required".to_owned(),
error_object: None,
})
})?;
// Handle the new oneof tokenization_data structure
let gpay_tokenization_data = match tokenization_data.tokenization_data {
Some(grpc_api_types::payments::google_wallet::tokenization_data::TokenizationData::DecryptedData(predecrypt_data)) => {
Ok(payment_method_data::GpayTokenizationData::Decrypted(
payment_method_data::GPayPredecryptData {
card_exp_month: Secret::new(predecrypt_data.card_exp_month),
| {
"chunk": 4,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_5 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
card_exp_year: Secret::new(predecrypt_data.card_exp_year),
application_primary_account_number: cards::CardNumber::from_str(&predecrypt_data.application_primary_account_number).change_context(
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_CARD_NUMBER".to_owned(),
error_identifier: 400,
error_message: "Invalid card number in Google Pay predecrypted data".to_owned(),
error_object: None,
})
)?,
cryptogram: Some(Secret::new(predecrypt_data.cryptogram)),
eci_indicator: predecrypt_data.eci_indicator,
}
))
},
Some(grpc_api_types::payments::google_wallet::tokenization_data::TokenizationData::EncryptedData(encrypted_data)) => {
Ok(payment_method_data::GpayTokenizationData::Encrypted(
payment_method_data::GpayEcryptedTokenizationData {
token_type: encrypted_data.token_type,
token: encrypted_data.token,
}
))
},
None => Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_GOOGLE_PAY_TOKENIZATION_DATA".to_owned(),
error_identifier: 400,
error_message: "Google Pay tokenization data variant is required".to_owned(),
error_object: None,
})))
}?;
let wallet_data = payment_method_data::GooglePayWalletData {
pm_type: google_wallet.r#type,
description: google_wallet.description,
info: payment_method_data::GooglePayPaymentMethodInfo {
card_network: info.card_network,
card_details: info.card_details,
assurance_details: info.assurance_details.map(|details| {
payment_method_data::GooglePayAssuranceDetails {
card_holder_authenticated: details.card_holder_authenticated,
account_verified: details.account_verified,
}
}),
},
tokenization_data: gpay_tokenization_data,
};
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::GooglePay(wallet_data)))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::AmazonPayRedirect(_)) => {
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::AmazonPayRedirect(Box::new(payment_method_data::AmazonPayRedirectData {}))))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::CashappQr(_)) => {
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::CashappQr(Box::new(payment_method_data::CashappQr {}))))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::RevolutPay(_)) => {
| {
"chunk": 5,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_6 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::RevolutPay(payment_method_data::RevolutPayData {})))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::AliPayRedirect(_)) => {
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::AliPayRedirect(payment_method_data::AliPayRedirection {})))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::WeChatPayQr(_)) => {
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::WeChatPayQr(Box::new(payment_method_data::WeChatPayQr {}))))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::PaypalRedirect(paypal_redirect)) => {
Ok(PaymentMethodData::Wallet(payment_method_data::WalletData::PaypalRedirect(payment_method_data::PaypalRedirection {
email: match paypal_redirect.email {
Some(ref email_str) => Some(Email::try_from(email_str.clone()).change_context(
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_EMAIL_FORMAT".to_owned(),
error_identifier: 400,
error_message: "Invalid email".to_owned(),
error_object: None,
})
)?),
None => None,
},
})))
}
_ => {
Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "This Wallet type is not yet supported".to_owned(),
error_object: None,
})))
},
}
},
grpc_api_types::payments::payment_method::PaymentMethod::OnlineBanking(online_banking_type) => {
match online_banking_type.online_banking_type {
Some(grpc_api_types::payments::online_banking_payment_method_type::OnlineBankingType::OpenBankingUk(open_banking_uk)) => {
Ok(PaymentMethodData::BankRedirect(payment_method_data::BankRedirectData::OpenBankingUk {
issuer: open_banking_uk.issuer.and_then(|i| common_enums::BankNames::from_str(&i).ok()),
country: open_banking_uk.country.and_then(|c| CountryAlpha2::from_str(&c).ok()),
}))
}
Some(grpc_api_types::payments::online_banking_payment_method_type::OnlineBankingType::OnlineBankingFpx(fpx)) => {
Ok(PaymentMethodData::BankRedirect(payment_method_data::BankRedirectData::OnlineBankingFpx{
issuer: common_enums::BankNames::foreign_try_from(
fpx.issuer(),
)?,
}))
}
_ => {
Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "This online banking type is not yet supported".to_owned(),
error_object: None,
})))
},
}
}
grpc_api_types::payments::payment_method::PaymentMethod::MobilePayment(mobile_payment_type) => {
| {
"chunk": 6,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_7 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
match mobile_payment_type.mobile_payment_type {
Some(grpc_api_types::payments::mobile_payment_method_type::MobilePaymentType::DuitNow(_)) => {
Ok(PaymentMethodData::RealTimePayment(Box::new(payment_method_data::RealTimePaymentData::DuitNow { })))
}
_ => Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "This mobile payment type is not yet supported".to_owned(),
error_object: None,
})))
}
}
grpc_api_types::payments::payment_method::PaymentMethod::Crypto(crypto) => {
let crypto_currency = crypto.crypto_currency.ok_or_else( || {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "crypto_currency is required".to_owned(),
error_object: None,
})
})?;
Ok(PaymentMethodData::Crypto(
payment_method_data::CryptoData {
pay_currency: crypto_currency.pay_currency,
network: crypto_currency.network,
},
))
}
},
None => Err(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_PAYMENT_METHOD_DATA".to_owned(),
error_identifier: 400,
error_message: "Payment method data is required".to_owned(),
error_object: None,
})
.into()),
}
}
}
impl ForeignTryFrom<grpc_api_types::payments::PaymentMethodType> for Option<PaymentMethodType> {
type Error = ApplicationErrorResponse;
fn foreign_try_from(
value: grpc_api_types::payments::PaymentMethodType,
) -> Result<Self, error_stack::Report<Self::Error>> {
match value {
grpc_api_types::payments::PaymentMethodType::Unspecified => Ok(None),
grpc_api_types::payments::PaymentMethodType::Credit => {
Ok(Some(PaymentMethodType::Credit))
}
grpc_api_types::payments::PaymentMethodType::Debit => {
Ok(Some(PaymentMethodType::Debit))
}
grpc_api_types::payments::PaymentMethodType::UpiCollect => {
Ok(Some(PaymentMethodType::UpiCollect))
}
grpc_api_types::payments::PaymentMethodType::UpiIntent => {
Ok(Some(PaymentMethodType::UpiIntent))
}
grpc_api_types::payments::PaymentMethodType::UpiQr => {
Ok(Some(PaymentMethodType::UpiIntent))
} // UpiQr not yet implemented, fallback to UpiIntent
grpc_api_types::payments::PaymentMethodType::ClassicReward => {
Ok(Some(PaymentMethodType::ClassicReward))
}
grpc_api_types::payments::PaymentMethodType::Evoucher => {
Ok(Some(PaymentMethodType::Evoucher))
}
grpc_api_types::payments::PaymentMethodType::ApplePay => {
Ok(Some(PaymentMethodType::ApplePay))
}
grpc_api_types::payments::PaymentMethodType::GooglePay => {
Ok(Some(PaymentMethodType::GooglePay))
}
grpc_api_types::payments::PaymentMethodType::AmazonPay => {
Ok(Some(PaymentMethodType::AmazonPay))
}
grpc_api_types::payments::PaymentMethodType::RevolutPay => {
Ok(Some(PaymentMethodType::RevolutPay))
}
grpc_api_types::payments::PaymentMethodType::PayPal => {
Ok(Some(PaymentMethodType::Paypal))
}
grpc_api_types::payments::PaymentMethodType::WeChatPay => {
Ok(Some(PaymentMethodType::WeChatPay))
}
| {
"chunk": 7,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_8 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
grpc_api_types::payments::PaymentMethodType::AliPay => {
Ok(Some(PaymentMethodType::AliPay))
}
grpc_api_types::payments::PaymentMethodType::Cashapp => {
Ok(Some(PaymentMethodType::Cashapp))
}
_ => Err(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_PAYMENT_METHOD_TYPE".to_owned(),
error_identifier: 400,
error_message: "This payment method type is not yet supported".to_owned(),
error_object: None,
})
.into()),
}
}
}
impl ForeignTryFrom<grpc_api_types::payments::PaymentMethod> for Option<PaymentMethodType> {
type Error = ApplicationErrorResponse;
fn foreign_try_from(
value: grpc_api_types::payments::PaymentMethod,
) -> Result<Self, error_stack::Report<Self::Error>> {
match value.payment_method {
Some(data) => match data {
grpc_api_types::payments::payment_method::PaymentMethod::Card(card_type) => {
match card_type.card_type {
Some(grpc_api_types::payments::card_payment_method_type::CardType::Credit(_)) => {
Ok(Some(PaymentMethodType::Credit))
},
Some(grpc_api_types::payments::card_payment_method_type::CardType::Debit(_)) => {
Ok(Some(PaymentMethodType::Debit))
},
Some(grpc_api_types::payments::card_payment_method_type::CardType::CardRedirect(_)) =>
Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "Card redirect payments are not yet supported".to_owned(),
error_object: None,
}))),
Some(grpc_api_types::payments::card_payment_method_type::CardType::CreditProxy(_)) => {
Ok(Some(PaymentMethodType::Credit))
},
Some(grpc_api_types::payments::card_payment_method_type::CardType::DebitProxy(_)) => {
Ok(Some(PaymentMethodType::Debit))
},
None =>
Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "Card type is required".to_owned(),
error_object: None,
})))
}
}
grpc_api_types::payments::payment_method::PaymentMethod::Token(_) => {
Ok(None)
},
grpc_api_types::payments::payment_method::PaymentMethod::UpiCollect(_) => Ok(Some(PaymentMethodType::UpiCollect)),
grpc_api_types::payments::payment_method::PaymentMethod::UpiIntent(_) => Ok(Some(PaymentMethodType::UpiIntent)),
grpc_api_types::payments::payment_method::PaymentMethod::UpiQr(_) => Ok(Some(PaymentMethodType::UpiIntent)), // UpiQr not yet implemented, fallback to UpiIntent
grpc_api_types::payments::payment_method::PaymentMethod::Reward(reward) => {
match reward.reward_type() {
grpc_api_types::payments::RewardType::Classicreward => Ok(Some(PaymentMethodType::ClassicReward)),
grpc_api_types::payments::RewardType::EVoucher => Ok(Some(PaymentMethodType::Evoucher)),
_ => Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_REWARD_TYPE".to_owned(),
error_identifier: 400,
error_message: "Unsupported reward type".to_owned(),
error_object: None,
})))
}
},
| {
"chunk": 8,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_9 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
grpc_api_types::payments::payment_method::PaymentMethod::Wallet(wallet_type) => {
match wallet_type.wallet_type {
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::Bluecode(_)) => {
Ok(Some(PaymentMethodType::Bluecode))
},
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::Mifinity(_mifinity_data)) => {
// For PaymentMethodType conversion, we just need to return the type, not the full data
Ok(Some(PaymentMethodType::Mifinity))
},
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::ApplePay(_)) => {
Ok(Some(PaymentMethodType::ApplePay))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::GooglePay(_)) => {
Ok(Some(PaymentMethodType::GooglePay))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::AmazonPayRedirect(_)) => {
Ok(Some(PaymentMethodType::AmazonPay))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::RevolutPay(_)) => {
Ok(Some(PaymentMethodType::RevolutPay))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::PaypalRedirect(_)) => {
Ok(Some(PaymentMethodType::Paypal))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::WeChatPayQr(_)) => {
Ok(Some(PaymentMethodType::WeChatPay))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::AliPayRedirect(_)) => {
Ok(Some(PaymentMethodType::AliPay))
}
Some(grpc_api_types::payments::wallet_payment_method_type::WalletType::CashappQr(_)) => {
Ok(Some(PaymentMethodType::Cashapp))
}
_ => {
Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "This Wallet type is not yet supported".to_owned(),
error_object: None,
})))
},
}
},
grpc_api_types::payments::payment_method::PaymentMethod::OnlineBanking(online_banking) => {
match online_banking.online_banking_type {
Some(grpc_api_types::payments::online_banking_payment_method_type::OnlineBankingType::OpenBankingUk(_)) => {
Ok(Some(PaymentMethodType::OpenBankingUk))
},
Some(grpc_api_types::payments::online_banking_payment_method_type::OnlineBankingType::OnlineBankingFpx(_))=>{
Ok(Some(PaymentMethodType::OnlineBankingFpx))
}
_ => {
Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "This online banking type is not yet supported".to_owned(),
error_object: None,
})))
},
}
}
grpc_api_types::payments::payment_method::PaymentMethod::MobilePayment(mobile_payment_type) => {
match mobile_payment_type.mobile_payment_type {
| {
"chunk": 9,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_10 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
Some(grpc_api_types::payments::mobile_payment_method_type::MobilePaymentType::DuitNow(_)) =>{
Ok(Some(PaymentMethodType::DuitNow))
}
_ => Err(report!(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "UNSUPPORTED_PAYMENT_METHOD".to_owned(),
error_identifier: 400,
error_message: "This mobile payment type is not yet supported".to_owned(),
error_object: None,
})))
}
}
grpc_api_types::payments::payment_method::PaymentMethod::Crypto(_) => Ok(Some(PaymentMethodType::CryptoCurrency)),
},
None => Err(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_PAYMENT_METHOD_DATA".to_owned(),
error_identifier: 400,
error_message: "Payment method data is required".to_owned(),
error_object: None,
})
.into()),
}
}
}
// Helper trait for generic card conversion
pub trait CardConversionHelper<T: PaymentMethodDataTypes> {
fn convert_card_details(
card: grpc_api_types::payments::CardDetails,
) -> Result<payment_method_data::Card<T>, error_stack::Report<ApplicationErrorResponse>>;
}
// Implementation for DefaultPCIHolder
impl CardConversionHelper<DefaultPCIHolder> for DefaultPCIHolder {
fn convert_card_details(
card: grpc_api_types::payments::CardDetails,
) -> Result<
payment_method_data::Card<DefaultPCIHolder>,
error_stack::Report<ApplicationErrorResponse>,
> {
let card_network = match card.card_network() {
grpc_api_types::payments::CardNetwork::Unspecified => None,
_ => Some(common_enums::CardNetwork::foreign_try_from(
card.card_network(),
)?),
};
Ok(payment_method_data::Card {
card_number: RawCardNumber::<DefaultPCIHolder>(card.card_number.ok_or(
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_CARD_NUMBER".to_owned(),
error_identifier: 400,
error_message: "Missing card number".to_owned(),
error_object: None,
}),
)?),
card_exp_month: card
.card_exp_month
.ok_or(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_EXP_MONTH".to_owned(),
error_identifier: 400,
error_message: "Missing Card Expiry Month".to_owned(),
error_object: None,
}))?,
card_exp_year: card
.card_exp_year
.ok_or(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_EXP_YEAR".to_owned(),
error_identifier: 400,
error_message: "Missing Card Expiry Year".to_owned(),
error_object: None,
}))?,
card_cvc: card
.card_cvc
.ok_or(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_CVC".to_owned(),
error_identifier: 400,
error_message: "Missing CVC".to_owned(),
error_object: None,
}))?,
card_issuer: card.card_issuer,
card_network,
card_type: card.card_type,
card_issuing_country: card.card_issuing_country_alpha2,
bank_code: card.bank_code,
nick_name: card.nick_name.map(|name| name.into()),
card_holder_name: card.card_holder_name,
co_badged_card_data: None,
})
}
}
// Implementation for VaultTokenHolder
impl CardConversionHelper<VaultTokenHolder> for VaultTokenHolder {
fn convert_card_details(
card: grpc_api_types::payments::CardDetails,
) -> Result<
payment_method_data::Card<VaultTokenHolder>,
error_stack::Report<ApplicationErrorResponse>,
> {
Ok(payment_method_data::Card {
card_number: RawCardNumber(
| {
"chunk": 10,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_11 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
card.card_number
.ok_or(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_CARD_NUMBER".to_owned(),
error_identifier: 400,
error_message: "Missing card number".to_owned(),
error_object: None,
}))
.map(|cn| cn.get_card_no())?,
),
card_exp_month: card
.card_exp_month
.ok_or(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_EXP_MONTH".to_owned(),
error_identifier: 400,
error_message: "Missing Card Expiry Month".to_owned(),
error_object: None,
}))?,
card_exp_year: card
.card_exp_year
.ok_or(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_EXP_YEAR".to_owned(),
error_identifier: 400,
error_message: "Missing Card Expiry Year".to_owned(),
error_object: None,
}))?,
card_cvc: card
.card_cvc
.ok_or(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_CVC".to_owned(),
error_identifier: 400,
error_message: "Missing CVC".to_owned(),
error_object: None,
}))?,
card_issuer: card.card_issuer,
card_network: None,
card_type: card.card_type,
card_issuing_country: card.card_issuing_country_alpha2,
bank_code: card.bank_code,
nick_name: card.nick_name.map(|name| name.into()),
card_holder_name: card.card_holder_name,
co_badged_card_data: None,
})
}
}
// Generic ForeignTryFrom implementation using the helper trait
impl<T> ForeignTryFrom<grpc_api_types::payments::CardDetails> for payment_method_data::Card<T>
where
T: PaymentMethodDataTypes
+ Default
+ Debug
+ Send
+ Eq
+ PartialEq
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ CardConversionHelper<T>,
{
type Error = ApplicationErrorResponse;
fn foreign_try_from(
card: grpc_api_types::payments::CardDetails,
) -> Result<Self, error_stack::Report<Self::Error>> {
T::convert_card_details(card)
}
}
impl ForeignTryFrom<grpc_api_types::payments::Currency> for common_enums::Currency {
type Error = ApplicationErrorResponse;
fn foreign_try_from(
value: grpc_api_types::payments::Currency,
) -> Result<Self, error_stack::Report<Self::Error>> {
match value {
grpc_api_types::payments::Currency::Aed => Ok(Self::AED),
grpc_api_types::payments::Currency::All => Ok(Self::ALL),
grpc_api_types::payments::Currency::Amd => Ok(Self::AMD),
grpc_api_types::payments::Currency::Ang => Ok(Self::ANG),
grpc_api_types::payments::Currency::Aoa => Ok(Self::AOA),
grpc_api_types::payments::Currency::Ars => Ok(Self::ARS),
grpc_api_types::payments::Currency::Aud => Ok(Self::AUD),
grpc_api_types::payments::Currency::Awg => Ok(Self::AWG),
grpc_api_types::payments::Currency::Azn => Ok(Self::AZN),
grpc_api_types::payments::Currency::Bam => Ok(Self::BAM),
grpc_api_types::payments::Currency::Bbd => Ok(Self::BBD),
grpc_api_types::payments::Currency::Bdt => Ok(Self::BDT),
grpc_api_types::payments::Currency::Bgn => Ok(Self::BGN),
grpc_api_types::payments::Currency::Bhd => Ok(Self::BHD),
grpc_api_types::payments::Currency::Bif => Ok(Self::BIF),
grpc_api_types::payments::Currency::Bmd => Ok(Self::BMD),
grpc_api_types::payments::Currency::Bnd => Ok(Self::BND),
grpc_api_types::payments::Currency::Bob => Ok(Self::BOB),
grpc_api_types::payments::Currency::Brl => Ok(Self::BRL),
grpc_api_types::payments::Currency::Bsd => Ok(Self::BSD),
grpc_api_types::payments::Currency::Bwp => Ok(Self::BWP),
| {
"chunk": 11,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-7881285798716424113_12 | clm | mini_chunk | // connector-service/backend/domain_types/src/types.rs
grpc_api_types::payments::Currency::Byn => Ok(Self::BYN),
grpc_api_types::payments::Currency::Bzd => Ok(Self::BZD),
grpc_api_types::payments::Currency::Cad => Ok(Self::CAD),
grpc_api_types::payments::Currency::Chf => Ok(Self::CHF),
grpc_api_types::payments::Currency::Clp => Ok(Self::CLP),
grpc_api_types::payments::Currency::Cny => Ok(Self::CNY),
grpc_api_types::payments::Currency::Cop => Ok(Self::COP),
grpc_api_types::payments::Currency::Crc => Ok(Self::CRC),
grpc_api_types::payments::Currency::Cup => Ok(Self::CUP),
grpc_api_types::payments::Currency::Cve => Ok(Self::CVE),
grpc_api_types::payments::Currency::Czk => Ok(Self::CZK),
grpc_api_types::payments::Currency::Djf => Ok(Self::DJF),
grpc_api_types::payments::Currency::Dkk => Ok(Self::DKK),
grpc_api_types::payments::Currency::Dop => Ok(Self::DOP),
grpc_api_types::payments::Currency::Dzd => Ok(Self::DZD),
grpc_api_types::payments::Currency::Egp => Ok(Self::EGP),
grpc_api_types::payments::Currency::Etb => Ok(Self::ETB),
grpc_api_types::payments::Currency::Eur => Ok(Self::EUR),
grpc_api_types::payments::Currency::Fjd => Ok(Self::FJD),
grpc_api_types::payments::Currency::Fkp => Ok(Self::FKP),
grpc_api_types::payments::Currency::Gbp => Ok(Self::GBP),
grpc_api_types::payments::Currency::Gel => Ok(Self::GEL),
grpc_api_types::payments::Currency::Ghs => Ok(Self::GHS),
grpc_api_types::payments::Currency::Gip => Ok(Self::GIP),
grpc_api_types::payments::Currency::Gmd => Ok(Self::GMD),
grpc_api_types::payments::Currency::Gnf => Ok(Self::GNF),
grpc_api_types::payments::Currency::Gtq => Ok(Self::GTQ),
grpc_api_types::payments::Currency::Gyd => Ok(Self::GYD),
grpc_api_types::payments::Currency::Hkd => Ok(Self::HKD),
grpc_api_types::payments::Currency::Hnl => Ok(Self::HNL),
grpc_api_types::payments::Currency::Hrk => Ok(Self::HRK),
grpc_api_types::payments::Currency::Htg => Ok(Self::HTG),
grpc_api_types::payments::Currency::Huf => Ok(Self::HUF),
grpc_api_types::payments::Currency::Idr => Ok(Self::IDR),
grpc_api_types::payments::Currency::Ils => Ok(Self::ILS),
grpc_api_types::payments::Currency::Inr => Ok(Self::INR),
grpc_api_types::payments::Currency::Iqd => Ok(Self::IQD),
grpc_api_types::payments::Currency::Jmd => Ok(Self::JMD),
grpc_api_types::payments::Currency::Jod => Ok(Self::JOD),
grpc_api_types::payments::Currency::Jpy => Ok(Self::JPY),
grpc_api_types::payments::Currency::Kes => Ok(Self::KES),
grpc_api_types::payments::Currency::Kgs => Ok(Self::KGS),
grpc_api_types::payments::Currency::Khr => Ok(Self::KHR),
grpc_api_types::payments::Currency::Kmf => Ok(Self::KMF),
grpc_api_types::payments::Currency::Krw => Ok(Self::KRW),
grpc_api_types::payments::Currency::Kwd => Ok(Self::KWD),
grpc_api_types::payments::Currency::Kyd => Ok(Self::KYD),
grpc_api_types::payments::Currency::Kzt => Ok(Self::KZT),
grpc_api_types::payments::Currency::Lak => Ok(Self::LAK),
grpc_api_types::payments::Currency::Lbp => Ok(Self::LBP),
grpc_api_types::payments::Currency::Lkr => Ok(Self::LKR),
grpc_api_types::payments::Currency::Lrd => Ok(Self::LRD),
grpc_api_types::payments::Currency::Lsl => Ok(Self::LSL),
grpc_api_types::payments::Currency::Lyd => Ok(Self::LYD),
grpc_api_types::payments::Currency::Mad => Ok(Self::MAD),
grpc_api_types::payments::Currency::Mdl => Ok(Self::MDL),
grpc_api_types::payments::Currency::Mga => Ok(Self::MGA),
grpc_api_types::payments::Currency::Mkd => Ok(Self::MKD),
grpc_api_types::payments::Currency::Mmk => Ok(Self::MMK),
grpc_api_types::payments::Currency::Mnt => Ok(Self::MNT),
| {
"chunk": 12,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.