id stringlengths 20 153 | type stringclasses 1
value | granularity stringclasses 14
values | content stringlengths 16 84.3k | metadata dict |
|---|---|---|---|---|
connector-service_mini_connector-integration_2188691800113068569_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
},
)?;
Self::try_from((&item, mandate_id))
}
PaymentMethodData::Crypto(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Aci"),
))?
}
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&WalletData,
)> for AciPaymentsRequest<T>
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let (item, wallet_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((wallet_data, &item.router_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&BankRedirectData,
)> for AciPaymentsRequest<T>
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, bank_redirect_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&PayLaterData,
)> for AciPaymentsRequest<T>
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
| {
"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_2188691800113068569_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
&PayLaterData,
),
) -> Result<Self, Self::Error> {
let (item, _pay_later_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::Klarna;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&Card<T>,
)> for AciPaymentsRequest<T>
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&Card<T>,
),
) -> Result<Self, Self::Error> {
let (item, card_data) = value;
let card_holder_name = item
.router_data
.resource_common_data
.get_optional_billing_full_name();
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((card_data.clone(), card_holder_name))?;
let instruction = get_instruction_details(item);
let recurring_type = get_recurring_type(item);
let three_ds_two_enrolled = item
.router_data
.resource_common_data
.is_three_ds()
.then_some(item.router_data.request.enrolled_for_3ds);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled,
recurring_type,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&NetworkTokenData,
)> for AciPaymentsRequest<T>
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (item, network_token_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, network_token_data))?;
let instruction = get_instruction_details(item);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
MandateIds,
)> for AciPaymentsRequest<T>
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
| {
"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_2188691800113068569_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
PaymentsResponseData,
>,
T,
>,
MandateIds,
),
) -> Result<Self, Self::Error> {
let (item, _mandate_data) = value;
let instruction = get_instruction_details(item);
let txn_details = get_transaction_details(item)?;
let recurring_type = get_recurring_type(item);
Ok(Self {
txn_details,
payment_method: PaymentDetails::Mandate,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type,
})
}
}
fn get_transaction_details<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
item: &AciRouterData<
RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
T,
>,
) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount,
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
let payment_type = if item.router_data.request.is_auto_capture()? {
AciPaymentType::Debit
} else {
AciPaymentType::Preauthorization
};
Ok(TransactionDetails {
entity_id: auth.entity_id,
amount,
currency: item.router_data.request.currency.to_string(),
payment_type,
})
}
fn get_instruction_details<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
item: &AciRouterData<
RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
T,
>,
) -> Option<Instruction> {
if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage
== Some(common_enums::FutureUsage::OffSession)
{
return Some(Instruction {
mode: InstructionMode::Initial,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::CardholderInitiatedTransaction,
create_registration: Some(true),
});
} else if item.router_data.request.mandate_id.is_some() {
return Some(Instruction {
mode: InstructionMode::Repeated,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::MerchantInitiatedTransaction,
create_registration: None,
});
}
None
}
fn get_recurring_type<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
item: &AciRouterData<
RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
T,
>,
) -> Option<AciRecurringType> {
if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage
== Some(common_enums::FutureUsage::OffSession)
{
Some(AciRecurringType::Initial)
} else {
None
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
AciRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
> for AciCancelRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: AciRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let aci_payment_request = Self {
entity_id: auth.entity_id,
payment_type: AciPaymentType::Reversal,
};
Ok(aci_payment_request)
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
| {
"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_2188691800113068569_9 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
AciRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
> for AciMandateRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: AciRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let (payment_brand, payment_details) = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(card_data) => {
let brand = get_aci_payment_brand(card_data.card_network.clone(), false).ok();
match brand.as_ref() {
Some(PaymentBrand::Visa)
| Some(PaymentBrand::Mastercard)
| Some(PaymentBrand::AmericanExpress) => (),
Some(_) => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
None => (),
};
let details = PaymentDetails::AciCard(Box::new(CardDetails {
card_number: card_data.card_number.clone(),
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year: card_data.get_expiry_year_4_digit(),
card_cvv: card_data.card_cvc.clone(),
card_holder: card_data.card_holder_name.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
},
)?,
payment_brand: brand.clone(),
}));
(brand, details)
}
_ => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
};
Ok(Self {
entity_id: auth.entity_id,
payment_brand,
payment_details,
})
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AciPaymentStatus {
Succeeded,
Failed,
#[default]
Pending,
RedirectShopper,
}
fn map_aci_attempt_status(
item: AciPaymentStatus,
auto_capture: bool,
) -> common_enums::AttemptStatus {
match item {
AciPaymentStatus::Succeeded => {
if auto_capture {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Authorized
}
}
AciPaymentStatus::Failed => common_enums::AttemptStatus::Failure,
AciPaymentStatus::Pending => common_enums::AttemptStatus::Authorizing,
AciPaymentStatus::RedirectShopper => common_enums::AttemptStatus::AuthenticationPending,
}
}
impl FromStr for AciPaymentStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsResponse {
id: String,
registration_id: Option<Secret<String>>,
ndc: String,
| {
"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_2188691800113068569_10 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
pub(super) redirect: Option<AciRedirectionData>,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciErrorResponse {
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRedirectionData {
pub method: Option<Method>,
pub parameters: Vec<Parameters>,
pub url: Url,
pub preconditions: Option<Vec<PreconditionData>>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreconditionData {
pub method: Option<Method>,
pub parameters: Vec<Parameters>,
pub url: Url,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct Parameters {
pub name: String,
pub value: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultCode {
pub(super) code: String,
pub(super) description: String,
pub(super) parameter_errors: Option<Vec<ErrorParameters>>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
pub struct ErrorParameters {
pub(super) name: String,
pub(super) value: Option<String>,
pub(super) message: String,
}
impl<F, Req> TryFrom<ResponseRouterData<AciPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>
where
Req: GetCaptureMethod,
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<AciPaymentsResponse, Self>) -> Result<Self, Self::Error> {
let redirection_data = item.response.redirect.map(|data| {
let mut form_fields = std::collections::HashMap::<_, _>::from_iter(
data.parameters
.iter()
.map(|parameter| (parameter.name.clone(), parameter.value.clone())),
);
if let Some(preconditions) = data.preconditions {
if let Some(first_precondition) = preconditions.first() {
for param in &first_precondition.parameters {
form_fields.insert(param.name.clone(), param.value.clone());
}
}
}
// If method is Get, parameters are appended to URL
// If method is post, we http Post the method to URL
RedirectForm::Form {
endpoint: data.url.to_string(),
// Handles method for Bank redirects currently.
// 3DS response have method within preconditions. That would require replacing below line with a function.
method: data.method.unwrap_or(Method::Post),
form_fields,
}
});
let mandate_reference = item
.response
.registration_id
.clone()
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
});
let auto_capture = matches!(
item.router_data.request.get_capture_method(),
Some(common_enums::CaptureMethod::Automatic) | None
);
let status = if redirection_data.is_some() {
map_aci_attempt_status(AciPaymentStatus::RedirectShopper, auto_capture)
} else {
map_aci_attempt_status(
AciPaymentStatus::from_str(&item.response.result.code)?,
auto_capture,
)
};
let response = if status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
})
} else {
| {
"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_2188691800113068569_11 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
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: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
status_code: item.http_code,
})
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureRequest {
#[serde(flatten)]
pub txn_details: TransactionDetails,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
AciRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for AciCaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: AciRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount_to_capture,
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
Ok(Self {
txn_details: TransactionDetails {
entity_id: auth.entity_id,
amount,
currency: item.router_data.request.currency.to_string(),
payment_type: AciPaymentType::Capture,
},
})
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureResponse {
id: String,
referenced_id: String,
payment_type: AciPaymentType,
amount: StringMajorUnit,
currency: String,
descriptor: String,
result: AciCaptureResult,
result_details: Option<AciCaptureResultDetails>,
build_number: String,
timestamp: String,
ndc: Secret<String>,
source: Option<Secret<String>>,
payment_method: Option<String>,
short_id: Option<String>,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureResult {
code: String,
description: String,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct AciCaptureResultDetails {
extended_description: String,
#[serde(rename = "clearingInstituteName")]
clearing_institute_name: Option<String>,
connector_tx_i_d1: Option<String>,
connector_tx_i_d3: Option<String>,
connector_tx_i_d2: Option<String>,
acquirer_response: Option<String>,
}
#[derive(Debug, Default, Clone, Deserialize)]
pub enum AciStatus {
Succeeded,
Failed,
#[default]
Pending,
}
impl FromStr for AciStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
fn map_aci_capture_status(item: AciStatus) -> common_enums::AttemptStatus {
match item {
AciStatus::Succeeded => common_enums::AttemptStatus::Charged,
AciStatus::Failed => common_enums::AttemptStatus::Failure,
AciStatus::Pending => common_enums::AttemptStatus::Pending,
}
}
| {
"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_2188691800113068569_12 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
impl<F, T> TryFrom<ResponseRouterData<AciCaptureResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<AciCaptureResponse, Self>) -> Result<Self, Self::Error> {
let status = map_aci_capture_status(AciStatus::from_str(&item.response.result.code)?);
let response = if status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.referenced_id.clone()),
incremental_authorization_allowed: None,
status_code: item.http_code,
})
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciVoidResponse {
id: String,
referenced_id: String,
payment_type: AciPaymentType,
amount: StringMajorUnit,
currency: String,
descriptor: String,
result: AciCaptureResult,
result_details: Option<AciCaptureResultDetails>,
build_number: String,
timestamp: String,
ndc: Secret<String>,
}
fn map_aci_void_status(item: AciStatus) -> common_enums::AttemptStatus {
match item {
AciStatus::Succeeded => common_enums::AttemptStatus::Voided,
AciStatus::Failed => common_enums::AttemptStatus::VoidFailed,
AciStatus::Pending => common_enums::AttemptStatus::VoidInitiated,
}
}
impl<F, T> TryFrom<ResponseRouterData<AciVoidResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ResponseRouterData<AciVoidResponse, Self>) -> Result<Self, Self::Error> {
let status = map_aci_void_status(AciStatus::from_str(&item.response.result.code)?);
let response = if status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
..Default::default()
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.referenced_id.clone()),
incremental_authorization_allowed: None,
status_code: item.http_code,
})
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRefundRequest {
pub amount: StringMajorUnit,
| {
"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_2188691800113068569_13 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
pub currency: String,
pub payment_type: AciPaymentType,
pub entity_id: Secret<String>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
AciRouterData<RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>, T>,
> for AciRefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: AciRouterData<
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_refund_amount,
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
let currency = item.router_data.request.currency;
let payment_type = AciPaymentType::Refund;
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
amount,
currency: currency.to_string(),
payment_type,
entity_id: auth.entity_id,
})
}
}
#[derive(Debug, Default, Deserialize, Clone)]
pub enum AciRefundStatus {
Succeeded,
Failed,
#[default]
Pending,
}
impl FromStr for AciRefundStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
impl From<AciRefundStatus> for common_enums::RefundStatus {
fn from(item: AciRefundStatus) -> Self {
match item {
AciRefundStatus::Succeeded => Self::Success,
AciRefundStatus::Failed => Self::Failure,
AciRefundStatus::Pending => Self::Pending,
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRefundResponse {
id: String,
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
}
impl<F> TryFrom<ResponseRouterData<AciRefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<AciRefundResponse, Self>) -> Result<Self, Self::Error> {
let refund_status = common_enums::RefundStatus::from(AciRefundStatus::from_str(
&item.response.result.code,
)?);
let response = if refund_status == common_enums::RefundStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_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<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<AciMandateResponse, Self>>
for RouterDataV2<F, PaymentFlowData, SetupMandateRequestData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<AciMandateResponse, Self>) -> Result<Self, Self::Error> {
| {
"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_2188691800113068569_14 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(item.response.id.clone()),
payment_method_id: None,
});
let status = if SUCCESSFUL_CODES.contains(&item.response.result.code.as_str()) {
common_enums::AttemptStatus::Charged
} else if FAILURE_CODES.contains(&item.response.result.code.as_str()) {
common_enums::AttemptStatus::Failure
} else {
common_enums::AttemptStatus::Pending
};
let response = if status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: mandate_reference.map(Box::new),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
status_code: item.http_code,
})
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum AciWebhookEventType {
Payment,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum AciWebhookAction {
Created,
Updated,
Deleted,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookCardDetails {
pub bin: Option<String>,
#[serde(rename = "last4Digits")]
pub last4_digits: Option<String>,
pub holder: Option<String>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookCustomerDetails {
#[serde(rename = "givenName")]
pub given_name: Option<Secret<String>>,
pub surname: Option<Secret<String>>,
#[serde(rename = "merchantCustomerId")]
pub merchant_customer_id: Option<Secret<String>>,
pub sex: Option<Secret<String>>,
pub email: Option<Email>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookAuthenticationDetails {
#[serde(rename = "entityId")]
pub entity_id: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookRiskDetails {
pub score: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentWebhookPayload {
pub id: String,
pub payment_type: String,
pub payment_brand: String,
pub amount: StringMajorUnit,
pub currency: String,
pub presentation_amount: Option<StringMajorUnit>,
pub presentation_currency: Option<String>,
pub descriptor: Option<String>,
pub result: ResultCode,
pub authentication: Option<AciWebhookAuthenticationDetails>,
pub card: Option<AciWebhookCardDetails>,
pub customer: Option<AciWebhookCustomerDetails>,
#[serde(rename = "customParameters")]
pub custom_parameters: Option<serde_json::Value>,
pub risk: Option<AciWebhookRiskDetails>,
pub build_number: Option<String>,
pub timestamp: String,
pub ndc: String,
#[serde(rename = "channelName")]
pub channel_name: Option<String>,
pub source: Option<String>,
pub payment_method: Option<String>,
#[serde(rename = "shortId")]
pub short_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
| {
"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_2188691800113068569_15 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/aci/transformers.rs
pub struct AciWebhookNotification {
#[serde(rename = "type")]
pub event_type: AciWebhookEventType,
pub action: Option<AciWebhookAction>,
pub payload: serde_json::Value,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRepeatPaymentRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
#[serde(flatten)]
pub txn_details: TransactionDetails,
#[serde(flatten)]
pub payment_method: PaymentDetails<T>,
#[serde(flatten)]
pub instruction: Option<Instruction>,
pub shopper_result_url: Option<String>,
#[serde(rename = "customParameters[3DS2_enrolled]")]
pub three_ds_two_enrolled: Option<bool>,
pub recurring_type: Option<AciRecurringType>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
AciRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
> for AciRepeatPaymentRequest<T>
{
type Error = Error;
fn try_from(
item: AciRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount,
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
let payment_type = if item.router_data.request.is_auto_capture()? {
AciPaymentType::Debit
} else {
AciPaymentType::Preauthorization
};
let instruction = Some(Instruction {
mode: InstructionMode::Repeated,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::MerchantInitiatedTransaction,
create_registration: None,
});
let txn_details = TransactionDetails {
entity_id: auth.entity_id,
amount,
currency: item.router_data.request.currency.to_string(),
payment_type,
};
let recurring_type = Some(AciRecurringType::Repeated);
Ok(Self {
txn_details,
payment_method: PaymentDetails::Mandate,
instruction,
shopper_result_url: item.router_data.resource_common_data.return_url.clone(),
three_ds_two_enrolled: None,
recurring_type,
})
}
}
| {
"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_121725801324840430_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
use common_enums::enums;
use common_utils::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
pii,
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use domain_types::{
connector_flow::{Authorize, Capture, PSync, RSync, Refund, Void},
connector_types::{
PaymentFlowData, PaymentVoidData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData,
RefundsResponseData, ResponseId,
},
errors::ConnectorError,
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, RawCardNumber},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
};
use error_stack::{report, ResultExt};
use hyperswitch_masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{connectors::fiserv::FiservRouterData, types::ResponseRouterData};
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservPaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub amount: Amount,
pub source: Source<T>,
pub transaction_details: TransactionDetails,
pub merchant_details: MerchantDetails,
pub transaction_interaction: TransactionInteraction,
}
#[derive(Debug, Serialize)]
#[serde(tag = "sourceType")]
pub enum Source<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
PaymentCard {
card: CardData<T>,
},
#[allow(dead_code)]
GooglePay {
data: Secret<String>,
signature: Secret<String>,
version: String,
},
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub card_data: RawCardNumber<T>,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub security_code: Secret<String>,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayToken {
pub signature: Secret<String>,
pub signed_message: Secret<String>,
pub protocol_version: String,
}
#[derive(Default, Debug, Serialize)]
pub struct Amount {
pub total: FloatMajorUnit,
pub currency: String,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
pub capture_flag: Option<bool>,
pub reversal_reason_code: Option<String>,
pub merchant_transaction_id: String,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDetails {
pub merchant_id: Secret<String>,
pub terminal_id: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionInteraction {
pub origin: TransactionInteractionOrigin,
pub eci_indicator: TransactionInteractionEciIndicator,
pub pos_condition_code: TransactionInteractionPosConditionCode,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TransactionInteractionOrigin {
#[default]
Ecom,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionInteractionEciIndicator {
#[default]
ChannelEncrypted,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionInteractionPosConditionCode {
#[default]
CardNotPresentEcom,
}
fn get_card_expiry_year_4_digit_placeholder(
year_yy: &Secret<String>,
) -> Result<Secret<String>, error_stack::Report<ConnectorError>> {
let year_str = year_yy.peek();
if year_str.len() == 2 && year_str.chars().all(char::is_numeric) {
Ok(Secret::new(format!("20{year_str}")))
} else if year_str.len() == 4 && year_str.chars().all(char::is_numeric) {
Ok(year_yy.clone())
} else {
Err(report!(ConnectorError::RequestEncodingFailed))
.attach_printable("Invalid card expiry year format: expected YY or YYYY")
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FiservAuthType {
pub api_key: Secret<String>,
pub merchant_account: Secret<String>,
| {
"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_121725801324840430_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
pub api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FiservAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
}),
_ => Err(report!(ConnectorError::FailedToObtainAuthType)),
}
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservErrorResponse {
pub details: Option<Vec<FiservErrorDetails>>,
pub error: Option<Vec<FiservErrorDetails>>,
}
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservErrorDetails {
#[serde(rename = "type")]
pub error_type: String,
pub code: Option<String>,
pub message: String,
pub field: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservPaymentStatus {
Succeeded,
Failed,
Captured,
Declined,
Voided,
Authorized,
#[default]
Processing,
}
impl From<FiservPaymentStatus> for enums::AttemptStatus {
fn from(item: FiservPaymentStatus) -> Self {
match item {
FiservPaymentStatus::Captured | FiservPaymentStatus::Succeeded => Self::Charged,
FiservPaymentStatus::Declined | FiservPaymentStatus::Failed => Self::Failure,
FiservPaymentStatus::Processing => Self::Authorizing,
FiservPaymentStatus::Voided => Self::Voided,
FiservPaymentStatus::Authorized => Self::Authorized,
}
}
}
impl From<FiservPaymentStatus> for enums::RefundStatus {
fn from(item: FiservPaymentStatus) -> Self {
match item {
FiservPaymentStatus::Captured
| FiservPaymentStatus::Succeeded
| FiservPaymentStatus::Authorized => Self::Success,
FiservPaymentStatus::Declined | FiservPaymentStatus::Failed => Self::Failure,
FiservPaymentStatus::Voided | FiservPaymentStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FiservPaymentsResponse {
pub gateway_response: GatewayResponse,
}
// Create a new response type for Capture that's a clone of the payments response
// This resolves the naming conflict in the macro framework
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FiservCaptureResponse {
pub gateway_response: GatewayResponse,
}
// Create a response type for Void
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FiservVoidResponse {
pub gateway_response: GatewayResponse,
}
// Create Refund response type
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FiservRefundResponse {
pub gateway_response: GatewayResponse,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(transparent)]
pub struct FiservSyncResponse {
pub sync_responses: Vec<FiservPaymentsResponse>,
}
// Create a distinct type for RefundSync to avoid templating conflicts
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(transparent)]
pub struct FiservRefundSyncResponse {
pub sync_responses: Vec<FiservPaymentsResponse>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct GatewayResponse {
pub gateway_transaction_id: Option<String>,
pub transaction_state: FiservPaymentStatus,
pub transaction_processing_details: TransactionProcessingDetails,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TransactionProcessingDetails {
pub order_id: String,
pub transaction_id: String,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
| {
"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_121725801324840430_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
pub struct FiservCaptureRequest {
pub amount: Amount,
pub transaction_details: TransactionDetails,
pub merchant_details: MerchantDetails,
pub reference_transaction_details: ReferenceTransactionDetails,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceTransactionDetails {
pub reference_transaction_id: String,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct FiservSessionObject {
pub terminal_id: Secret<String>,
}
// The TryFrom<&Option<pii::SecretSerdeValue>> for FiservSessionObject might not be needed
// if FiservSessionObject is always parsed from the string within connector_meta_data directly
// in the TryFrom implementations for FiservPaymentsRequest, FiservCaptureRequest, etc.
impl TryFrom<&Option<pii::SecretSerdeValue>> for FiservSessionObject {
type Error = error_stack::Report<ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let secret_value_str = meta_data
.as_ref()
.ok_or_else(|| {
report!(ConnectorError::MissingRequiredField {
field_name: "connector_meta_data (FiservSessionObject)"
})
})
.and_then(|secret_value| match secret_value.peek() {
serde_json::Value::String(s) => Ok(s.clone()),
_ => Err(report!(ConnectorError::InvalidConnectorConfig {
config: "FiservSessionObject in connector_meta_data was not a JSON string",
})),
})?;
serde_json::from_str(&secret_value_str).change_context(
ConnectorError::InvalidConnectorConfig {
config: "Deserializing FiservSessionObject from connector_meta_data string",
},
)
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservVoidRequest {
pub transaction_details: TransactionDetails,
pub merchant_details: MerchantDetails,
pub reference_transaction_details: ReferenceTransactionDetails,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservRefundRequest {
pub amount: Amount,
pub merchant_details: MerchantDetails,
pub reference_transaction_details: ReferenceTransactionDetails,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservSyncRequest {
pub merchant_details: MerchantDetails,
pub reference_transaction_details: ReferenceTransactionDetails,
}
// Create a distinct type for RefundSync to avoid templating conflicts
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservRefundSyncRequest {
pub merchant_details: MerchantDetails,
pub reference_transaction_details: ReferenceTransactionDetails,
}
// Implementations for FiservRouterData - needed for the macro framework
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
FiservRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for FiservPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: FiservRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let auth: FiservAuthType = FiservAuthType::try_from(&router_data.connector_auth_type)?;
// Use FloatMajorUnitForConnector to properly convert minor to major unit
let converter = FloatMajorUnitForConnector;
let amount_major = converter
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(ConnectorError::RequestEncodingFailed)?;
let amount = Amount {
total: amount_major,
| {
"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_121725801324840430_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
currency: router_data.request.currency.to_string(),
};
let transaction_details = TransactionDetails {
capture_flag: Some(matches!(
router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
reversal_reason_code: None,
merchant_transaction_id: router_data
.resource_common_data
.connector_request_reference_id
.clone(),
};
let session_meta_value = router_data
.resource_common_data
.connector_meta_data
.as_ref()
.ok_or_else(|| {
report!(ConnectorError::MissingRequiredField {
field_name: "connector_meta_data for FiservSessionObject"
})
})?
.peek();
let session_str = match session_meta_value {
serde_json::Value::String(s) => s,
_ => {
return Err(report!(ConnectorError::InvalidConnectorConfig {
config: "connector_meta_data was not a JSON string for FiservSessionObject",
}))
}
};
let session: FiservSessionObject = serde_json::from_str(session_str).change_context(
ConnectorError::InvalidConnectorConfig {
config: "Deserializing FiservSessionObject from connector_meta_data string",
},
)?;
let merchant_details = MerchantDetails {
merchant_id: auth.merchant_account.clone(),
terminal_id: Some(session.terminal_id.clone()),
};
let transaction_interaction = TransactionInteraction::default();
let source = match router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref ccard) => {
let card = CardData {
card_data: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: get_card_expiry_year_4_digit_placeholder(
&ccard.card_exp_year,
)?,
security_code: ccard.card_cvc.clone(),
};
Source::PaymentCard { card }
}
_ => Err(report!(ConnectorError::NotImplemented(
"Payment method not implemented for Fiserv".to_string(),
)))?,
};
Ok(Self {
amount,
source,
transaction_details,
merchant_details,
transaction_interaction,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
FiservRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for FiservCaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: FiservRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let router_data = item.router_data;
let auth: FiservAuthType = FiservAuthType::try_from(&router_data.connector_auth_type)?;
// Prioritize connector_metadata from PaymentsCaptureData if available,
// otherwise fall back to resource_common_data.connector_meta_data.
// Try to get session string from different sources - converting both paths to String for type consistency
let session_str = if let Some(meta) = router_data
.resource_common_data
.connector_meta_data
.as_ref()
{
// Use connector_meta_data from resource_common_data (which is Secret<Value>)
match meta.peek() {
serde_json::Value::String(s) => s.to_string(), // Convert &str to String
_ => return Err(report!(ConnectorError::InvalidConnectorConfig {
config: "connector_meta_data was not a JSON string for FiservSessionObject in Capture",
})),
}
| {
"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_121725801324840430_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
} else if let Some(connector_meta) = router_data.request.connector_metadata.as_ref() {
// Use connector_metadata from request (which is Value)
match connector_meta {
serde_json::Value::String(s) => s.clone(), // String
_ => return Err(report!(ConnectorError::InvalidConnectorConfig {
config: "connector_metadata was not a JSON string for FiservSessionObject in Capture",
})),
}
} else {
// No metadata available
return Err(report!(ConnectorError::MissingRequiredField {
field_name:
"connector_metadata or connector_meta_data for FiservSessionObject in Capture"
}));
};
let session: FiservSessionObject =
serde_json::from_str(&session_str)
.change_context(ConnectorError::InvalidConnectorConfig {
config:
"Deserializing FiservSessionObject from connector_metadata string in Capture",
})?;
let merchant_details = MerchantDetails {
merchant_id: auth.merchant_account.clone(),
terminal_id: Some(session.terminal_id.clone()),
};
// Use FloatMajorUnitForConnector to properly convert minor to major unit
let converter = FloatMajorUnitForConnector;
let amount_major = converter
.convert(
router_data.request.minor_amount_to_capture,
router_data.request.currency,
)
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
amount: Amount {
total: amount_major,
currency: router_data.request.currency.to_string(),
},
transaction_details: TransactionDetails {
capture_flag: Some(true),
reversal_reason_code: None,
merchant_transaction_id: router_data
.resource_common_data
.connector_request_reference_id
.clone(),
},
merchant_details,
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: router_data
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(ConnectorError::MissingConnectorTransactionID)?,
},
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
FiservRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
> for FiservSyncRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: FiservRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let auth: FiservAuthType = FiservAuthType::try_from(&router_data.connector_auth_type)?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account.clone(),
terminal_id: None,
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: router_data
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(ConnectorError::MissingConnectorTransactionID)?,
},
})
}
}
// Implementation for the Void request
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
FiservRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
> for FiservVoidRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: FiservRouterData<
| {
"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_121725801324840430_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let auth: FiservAuthType = FiservAuthType::try_from(&router_data.connector_auth_type)?;
// Get session information
let session_meta_value = router_data
.resource_common_data
.connector_meta_data
.as_ref()
.ok_or_else(|| {
report!(ConnectorError::MissingRequiredField {
field_name: "connector_meta_data for FiservSessionObject in Void"
})
})?
.peek();
let session_str = match session_meta_value {
serde_json::Value::String(s) => s,
_ => {
return Err(report!(ConnectorError::InvalidConnectorConfig {
config:
"connector_meta_data was not a JSON string for FiservSessionObject in Void",
}))
}
};
let session: FiservSessionObject = serde_json::from_str(session_str).change_context(
ConnectorError::InvalidConnectorConfig {
config: "Deserializing FiservSessionObject from connector_meta_data string in Void",
},
)?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account.clone(),
terminal_id: Some(session.terminal_id.clone()),
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: router_data.request.connector_transaction_id.clone(),
},
transaction_details: TransactionDetails {
capture_flag: None,
reversal_reason_code: router_data.request.cancellation_reason.clone(),
merchant_transaction_id: router_data
.resource_common_data
.connector_request_reference_id
.clone(),
},
})
}
}
// Implementation for the Refund request
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
FiservRouterData<RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>, T>,
> for FiservRefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: FiservRouterData<
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let auth: FiservAuthType = FiservAuthType::try_from(&router_data.connector_auth_type)?;
// Try to get session information - use only connector_metadata from request since
// RefundFlowData doesn't have connector_meta_data field in resource_common_data
let session_str = if let Some(connector_meta) =
router_data.request.connector_metadata.as_ref()
{
// Use connector_metadata from request
match connector_meta {
serde_json::Value::String(s) => s.clone(),
_ => return Err(report!(ConnectorError::InvalidConnectorConfig {
config:
"connector_metadata was not a JSON string for FiservSessionObject in Refund",
})),
}
} else {
// No metadata available
return Err(report!(ConnectorError::MissingRequiredField {
field_name:
"connector_metadata or connector_meta_data for FiservSessionObject in Refund"
}));
};
let session: FiservSessionObject = serde_json::from_str(&session_str).change_context(
ConnectorError::InvalidConnectorConfig {
config: "Deserializing FiservSessionObject from metadata string in Refund",
},
)?;
// Convert minor amount to float major unit
let converter = FloatMajorUnitForConnector;
let amount_major = converter
.convert(
router_data.request.minor_refund_amount,
| {
"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_121725801324840430_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
router_data.request.currency,
)
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
amount: Amount {
total: amount_major,
currency: router_data.request.currency.to_string(),
},
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account.clone(),
terminal_id: Some(session.terminal_id.clone()),
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: router_data.request.connector_transaction_id.to_string(),
},
})
}
}
// Implementation for the RefundSync request
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
FiservRouterData<
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
T,
>,
> for FiservRefundSyncRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: FiservRouterData<
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let auth: FiservAuthType = FiservAuthType::try_from(&router_data.connector_auth_type)?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account.clone(),
terminal_id: None,
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: router_data.request.connector_transaction_id.clone(),
},
})
}
}
// Response handling TryFrom implementations for macro framework
// Standard payment response handling for Authorize flow
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<FiservPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<FiservPaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let gateway_resp = &response.gateway_response;
let status = enums::AttemptStatus::from(gateway_resp.transaction_state.clone());
// Update the status in router_data
let mut router_data_out = router_data;
router_data_out.resource_common_data.status = status;
let response_payload = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp
.gateway_transaction_id
.clone()
.unwrap_or_else(|| {
gateway_resp
.transaction_processing_details
.transaction_id
.clone()
}),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id.clone(),
),
incremental_authorization_allowed: None,
status_code: item.http_code,
};
if status == enums::AttemptStatus::Failure || status == enums::AttemptStatus::Voided {
router_data_out.response = Err(ErrorResponse {
code: gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
message: format!("Payment status: {:?}", gateway_resp.transaction_state),
reason: None,
status_code: http_code,
attempt_status: Some(status),
| {
"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_121725801324840430_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
connector_transaction_id: gateway_resp.gateway_transaction_id.clone(),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
} else {
router_data_out.response = Ok(response_payload);
}
Ok(router_data_out)
}
}
// Implementation for the Capture flow response
impl<F> TryFrom<ResponseRouterData<FiservCaptureResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<FiservCaptureResponse, Self>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let gateway_resp = &response.gateway_response;
let status = enums::AttemptStatus::from(gateway_resp.transaction_state.clone());
// Update the status in router_data
let mut router_data_out = router_data;
router_data_out.resource_common_data.status = status;
let response_payload = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp
.gateway_transaction_id
.clone()
.unwrap_or_else(|| {
gateway_resp
.transaction_processing_details
.transaction_id
.clone()
}),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id.clone(),
),
incremental_authorization_allowed: None,
status_code: item.http_code,
};
if status == enums::AttemptStatus::Failure || status == enums::AttemptStatus::Voided {
router_data_out.response = Err(ErrorResponse {
code: gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
message: format!("Payment status: {:?}", gateway_resp.transaction_state),
reason: None,
status_code: http_code,
attempt_status: Some(status),
connector_transaction_id: gateway_resp.gateway_transaction_id.clone(),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
} else {
router_data_out.response = Ok(response_payload);
}
Ok(router_data_out)
}
}
// Implementation for the Void flow response
impl<F> TryFrom<ResponseRouterData<FiservVoidResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentVoidData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<FiservVoidResponse, Self>) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let gateway_resp = &response.gateway_response;
let status = enums::AttemptStatus::from(gateway_resp.transaction_state.clone());
// Update the status in router_data
let mut router_data_out = router_data;
router_data_out.resource_common_data.status = status;
let response_payload = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp
.gateway_transaction_id
.clone()
.unwrap_or_else(|| {
gateway_resp
.transaction_processing_details
.transaction_id
.clone()
}),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
| {
"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_121725801324840430_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id.clone(),
),
incremental_authorization_allowed: None,
status_code: item.http_code,
};
if status == enums::AttemptStatus::Failure {
router_data_out.response = Err(ErrorResponse {
code: gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
message: format!("Void status: {:?}", gateway_resp.transaction_state),
reason: None,
status_code: http_code,
attempt_status: Some(status),
connector_transaction_id: gateway_resp.gateway_transaction_id.clone(),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
} else {
router_data_out.response = Ok(response_payload);
}
Ok(router_data_out)
}
}
// Payment Sync response handling
impl<F> TryFrom<ResponseRouterData<FiservSyncResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<FiservSyncResponse, Self>) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
// Get first transaction from array
let fiserv_payment_response = response
.sync_responses
.first()
.ok_or(ConnectorError::ResponseHandlingFailed)
.attach_printable("Fiserv Sync response array was empty")?;
let gateway_resp = &fiserv_payment_response.gateway_response;
let status = enums::AttemptStatus::from(gateway_resp.transaction_state.clone());
// Update the status in router_data
let mut router_data_out = router_data;
router_data_out.resource_common_data.status = status;
let response_payload = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp
.gateway_transaction_id
.clone()
.unwrap_or_else(|| {
gateway_resp
.transaction_processing_details
.transaction_id
.clone()
}),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id.clone(),
),
incremental_authorization_allowed: None,
status_code: item.http_code,
};
if status == enums::AttemptStatus::Failure || status == enums::AttemptStatus::Voided {
router_data_out.response = Err(ErrorResponse {
code: gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
message: format!("Payment status: {:?}", gateway_resp.transaction_state),
reason: None,
status_code: http_code,
attempt_status: Some(status),
connector_transaction_id: gateway_resp.gateway_transaction_id.clone(),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
} else {
router_data_out.response = Ok(response_payload);
}
Ok(router_data_out)
}
}
// Refund flow response handling
impl<F> TryFrom<ResponseRouterData<FiservRefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<FiservRefundResponse, Self>) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
| {
"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_121725801324840430_9 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
let gateway_resp = &response.gateway_response;
let refund_status = enums::RefundStatus::from(gateway_resp.transaction_state.clone());
// Update the status in router_data
let mut router_data_out = router_data;
let response_payload = RefundsResponseData {
connector_refund_id: gateway_resp
.gateway_transaction_id
.clone()
.unwrap_or_else(|| {
gateway_resp
.transaction_processing_details
.transaction_id
.clone()
}),
refund_status,
status_code: http_code,
};
if refund_status == enums::RefundStatus::Failure {
router_data_out.response = Err(ErrorResponse {
code: gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
message: format!("Refund status: {:?}", gateway_resp.transaction_state),
reason: None,
status_code: http_code,
attempt_status: None,
connector_transaction_id: gateway_resp.gateway_transaction_id.clone(),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
} else {
router_data_out.response = Ok(response_payload);
}
Ok(router_data_out)
}
}
// Refund Sync response handling
impl<F> TryFrom<ResponseRouterData<FiservRefundSyncResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<FiservRefundSyncResponse, Self>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
// Get first transaction from array
let fiserv_payment_response = response
.sync_responses
.first()
.ok_or(ConnectorError::ResponseHandlingFailed)
.attach_printable("Fiserv Sync response array was empty")?;
let gateway_resp = &fiserv_payment_response.gateway_response;
let refund_status = enums::RefundStatus::from(gateway_resp.transaction_state.clone());
// Update the router data
let mut router_data_out = router_data;
let response_payload = RefundsResponseData {
connector_refund_id: gateway_resp
.gateway_transaction_id
.clone()
.unwrap_or_else(|| {
gateway_resp
.transaction_processing_details
.transaction_id
.clone()
}),
refund_status,
status_code: http_code,
};
if refund_status == enums::RefundStatus::Failure {
router_data_out.response = Err(ErrorResponse {
code: gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
message: format!("Refund status: {:?}", gateway_resp.transaction_state),
reason: None,
status_code: http_code,
attempt_status: None,
connector_transaction_id: gateway_resp.gateway_transaction_id.clone(),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
} else {
router_data_out.response = Ok(response_payload);
}
Ok(router_data_out)
}
}
// Error response handling
impl<F, Req, Res> TryFrom<ResponseRouterData<FiservErrorResponse, Self>>
for RouterDataV2<F, PaymentFlowData, Req, Res>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<FiservErrorResponse, Self>) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let error_details = response
.error
.as_ref()
.or(response.details.as_ref())
| {
"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_121725801324840430_10 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/fiserv/transformers.rs
.and_then(|e| e.first());
let message = error_details.map_or(NO_ERROR_MESSAGE.to_string(), |e| e.message.clone());
let code = error_details
.and_then(|e| e.code.clone())
.unwrap_or_else(|| NO_ERROR_CODE.to_string());
let reason = error_details.and_then(|e| e.field.clone());
let mut router_data_out = router_data;
router_data_out.response = Err(ErrorResponse {
code,
message,
reason,
status_code: http_code,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
Ok(router_data_out)
}
}
| {
"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_4134908991275845488_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/checkout/transformers.rs
use common_enums::enums;
use common_utils::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors::CustomResult,
types::MinorUnit,
};
use domain_types::{
connector_flow::{Authorize, Capture, PSync, RSync, Refund, Void},
connector_types::{
PaymentFlowData, PaymentVoidData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData,
RefundsResponseData, ResponseId,
},
errors::{self, ConnectorError},
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, RawCardNumber},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
};
use error_stack::report;
use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use crate::types::ResponseRouterData;
// Import the CheckoutRouterData from the parent module
// Create type aliases for response types to avoid template conflicts
pub type CheckoutAuthorizeResponse = CheckoutPaymentsResponse;
pub type CheckoutPSyncResponse = CheckoutPaymentsResponse;
// Define auth type
pub struct CheckoutAuthType {
#[allow(dead_code)]
pub(super) api_key: Secret<String>,
pub(super) processing_channel_id: Secret<String>,
pub(super) api_secret: Secret<String>,
}
// Sync request structure needed for PSync
#[derive(Debug, Serialize, Default)]
pub struct CheckoutSyncRequest {}
// Empty request structure for RSync
#[derive(Debug, Serialize, Default)]
pub struct CheckoutRefundSyncRequest {}
// Define the source types enum
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutSourceTypes {
Card,
Token,
}
// Card source structure
#[derive(Debug, Serialize)]
pub struct CardSource<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
pub number: RawCardNumber<T>,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvv: Secret<String>,
}
// Simple payment request structure
#[derive(Debug, Serialize)]
pub struct CheckoutPaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub source: CardSource<T>,
pub amount: MinorUnit,
pub currency: String,
pub processing_channel_id: Secret<String>,
pub capture: bool,
pub reference: String,
}
// Payment response structure
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct CheckoutPaymentsResponse {
pub id: String,
pub amount: Option<MinorUnit>,
pub currency: Option<String>,
pub status: CheckoutPaymentStatus,
pub reference: Option<String>,
pub response_code: Option<String>,
pub response_summary: Option<String>,
pub action_id: Option<String>,
pub balances: Option<Balances>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Balances {
pub available_to_capture: i32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutMeta {
pub psync_flow: CheckoutPaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum CheckoutPaymentIntent {
Capture,
Authorize,
}
fn to_connector_meta(
connector_meta: Option<serde_json::Value>,
) -> CustomResult<CheckoutMeta, ConnectorError> {
connector_meta
.map(|meta| {
serde_json::from_value::<CheckoutMeta>(meta)
.map_err(|_| report!(errors::ConnectorError::ResponseDeserializationFailed))
})
.unwrap_or(Ok(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
}))
}
fn get_connector_meta(
capture_method: enums::CaptureMethod,
) -> CustomResult<serde_json::Value, ConnectorError> {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => {
Ok(serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
}))
}
enums::CaptureMethod::Manual | enums::CaptureMethod::ManualMultiple => {
Ok(serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Authorize,
}))
}
enums::CaptureMethod::Scheduled => {
| {
"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_4134908991275845488_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/checkout/transformers.rs
Err(errors::ConnectorError::CaptureMethodNotSupported.into())
}
}
}
#[derive(Debug, Serialize)]
pub enum CaptureType {
Final,
NonFinal,
}
#[derive(Debug, Serialize)]
pub struct PaymentCaptureRequest {
pub amount: Option<MinorUnit>,
pub capture_type: Option<CaptureType>,
pub processing_channel_id: Secret<String>,
pub reference: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentCaptureResponse {
pub action_id: String,
pub reference: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefundRequest {
pub amount: Option<MinorUnit>,
pub reference: String,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
action_id: String,
reference: String,
}
// Wrapper struct to match HS implementation
#[derive(Deserialize)]
pub struct CheckoutRefundResponse {
pub(super) status: u16,
pub(super) response: RefundResponse,
}
impl From<&CheckoutRefundResponse> for enums::RefundStatus {
fn from(item: &CheckoutRefundResponse) -> Self {
if item.status == 202 {
Self::Success
} else {
Self::Failure
}
}
}
#[derive(Deserialize, Debug, Serialize)]
pub struct ActionResponse {
#[serde(rename = "id")]
pub action_id: String,
pub amount: MinorUnit,
pub approved: Option<bool>,
pub reference: Option<String>,
}
impl From<&ActionResponse> for enums::RefundStatus {
fn from(item: &ActionResponse) -> Self {
match item.approved {
Some(true) => Self::Success,
Some(false) => Self::Failure,
None => Self::Pending,
}
}
}
// Payment void request structure
#[derive(Clone, Default, Debug, Eq, PartialEq, Serialize)]
pub struct PaymentVoidRequest {
pub reference: String,
}
// Payment void response structure
#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentVoidResponse {
#[serde(skip)]
pub(super) status: u16,
pub action_id: String,
pub reference: String,
}
impl From<&PaymentVoidResponse> for enums::AttemptStatus {
fn from(item: &PaymentVoidResponse) -> Self {
if item.status == 202 {
Self::Voided
} else {
Self::VoidFailed
}
}
}
// Payment status enum
#[derive(Default, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum CheckoutPaymentStatus {
Authorized,
#[default]
Pending,
#[serde(rename = "Card Verified")]
CardVerified,
Declined,
Captured,
#[serde(rename = "Retry Scheduled")]
RetryScheduled,
Voided,
#[serde(rename = "Partially Captured")]
PartiallyCaptured,
#[serde(rename = "Partially Refunded")]
PartiallyRefunded,
Refunded,
Canceled,
Expired,
}
// Helper functions to get attempt status based on different contexts
fn get_attempt_status_cap(
item: (CheckoutPaymentStatus, Option<enums::CaptureMethod>),
) -> enums::AttemptStatus {
let (status, capture_method) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if capture_method == Some(enums::CaptureMethod::Automatic) || capture_method.is_none() {
enums::AttemptStatus::Pending
} else {
enums::AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded => enums::AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => enums::AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => enums::AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => enums::AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
enums::AttemptStatus::Pending
}
CheckoutPaymentStatus::Voided => enums::AttemptStatus::Voided,
}
}
fn get_attempt_status_intent(
item: (CheckoutPaymentStatus, CheckoutPaymentIntent),
) -> enums::AttemptStatus {
let (status, psync_flow) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if psync_flow == CheckoutPaymentIntent::Capture {
enums::AttemptStatus::Pending
} else {
| {
"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_4134908991275845488_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/checkout/transformers.rs
enums::AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded => enums::AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => enums::AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => enums::AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => enums::AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
enums::AttemptStatus::Pending
}
CheckoutPaymentStatus::Voided => enums::AttemptStatus::Voided,
}
}
fn get_attempt_status_bal(item: (CheckoutPaymentStatus, Option<Balances>)) -> enums::AttemptStatus {
let (status, balances) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if let Some(Balances {
available_to_capture: 0,
}) = balances
{
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded => enums::AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => enums::AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => enums::AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => enums::AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
enums::AttemptStatus::Pending
}
CheckoutPaymentStatus::Voided => enums::AttemptStatus::Voided,
}
}
// Map payment status to attempt status for simple cases
impl From<CheckoutPaymentStatus> for enums::AttemptStatus {
fn from(status: CheckoutPaymentStatus) -> Self {
get_attempt_status_bal((status, None))
}
}
// Error response structure
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutErrorResponse {
pub request_id: Option<String>,
pub error_type: Option<String>,
pub error_codes: Option<Vec<String>>,
}
// Auth type conversion
impl TryFrom<&ConnectorAuthType> for CheckoutAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
processing_channel_id: key1.to_owned(),
})
} else {
Err(report!(ConnectorError::FailedToObtainAuthType))
}
}
}
// Payment request conversion
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
super::CheckoutRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for CheckoutPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: super::CheckoutRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
// Get card details from payment method data
let card_details = match router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(card) => Ok(card),
_ => Err(report!(ConnectorError::NotImplemented(
"Payment method not supported by Checkout".to_string(),
))),
}?;
| {
"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_4134908991275845488_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/checkout/transformers.rs
// Create card source
let source = CardSource {
source_type: CheckoutSourceTypes::Card,
number: card_details.card_number.clone(),
expiry_month: card_details.card_exp_month.clone(),
expiry_year: card_details.card_exp_year.clone(),
cvv: card_details.card_cvc,
};
// Determine capture mode
let capture = matches!(
router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
);
// Get processing channel ID
let connector_auth = &router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
let processing_channel_id = auth_type.processing_channel_id;
Ok(Self {
source,
amount: router_data.request.minor_amount,
currency: router_data.request.currency.to_string(),
processing_channel_id,
capture,
reference: router_data
.resource_common_data
.connector_request_reference_id
.clone(),
})
}
}
// Payment response conversion
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
ResponseRouterData<
CheckoutPaymentsResponse,
RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
>,
> for RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
CheckoutPaymentsResponse,
RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
// Get attempt status from payment status based on capture method
let status = get_attempt_status_cap((response.status, router_data.request.capture_method));
let mut router_data = router_data;
router_data.resource_common_data.status = status;
// Check if the response indicates an error
if status == enums::AttemptStatus::Failure {
router_data.response = Err(ErrorResponse {
status_code: http_code,
code: response
.response_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.response_summary
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.response_summary,
attempt_status: None,
connector_transaction_id: Some(response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
} else {
let connector_meta =
get_connector_meta(router_data.request.capture_method.unwrap_or_default())?;
// Handle successful response
router_data.response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: Some(response.reference.unwrap_or(response.id)),
incremental_authorization_allowed: None,
status_code: http_code,
});
}
Ok(router_data)
}
}
// Implementation for PaymentCaptureRequest
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
super::CheckoutRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for PaymentCaptureRequest
{
| {
"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_4134908991275845488_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/checkout/transformers.rs
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: super::CheckoutRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let connector_auth = &router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
let processing_channel_id = auth_type.processing_channel_id;
// Determine if this is a multiple capture by checking if multiple_capture_data exists
let capture_type = if router_data.request.multiple_capture_data.is_some() {
CaptureType::NonFinal
} else {
CaptureType::Final
};
// Get optional reference for multiple captures
let reference = router_data
.request
.multiple_capture_data
.as_ref()
.map(|mcd| mcd.capture_reference.clone());
Ok(Self {
amount: Some(router_data.request.minor_amount_to_capture),
capture_type: Some(capture_type),
processing_channel_id,
reference,
})
}
}
// Implementation for RefundRequest
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
super::CheckoutRouterData<
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
> for RefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: super::CheckoutRouterData<
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(MinorUnit::new(item.router_data.request.refund_amount)),
reference: item.router_data.request.refund_id.clone(),
})
}
}
// Implementation for PaymentVoidRequest with the router data generated by the macro
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
super::CheckoutRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
> for PaymentVoidRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: super::CheckoutRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let connector_transaction_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
reference: connector_transaction_id,
})
}
}
// Implementation for PaymentVoidRequest with direct RouterDataV2
impl TryFrom<RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>>
for PaymentVoidRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_transaction_id = item.request.connector_transaction_id.clone();
Ok(Self {
reference: connector_transaction_id,
})
}
}
// Also implement for reference version
impl TryFrom<&RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>>
for PaymentVoidRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_transaction_id = item.request.connector_transaction_id.clone();
Ok(Self {
reference: connector_transaction_id,
})
}
}
// Payment capture response conversion
impl<F>
TryFrom<
ResponseRouterData<
PaymentCaptureResponse,
RouterDataV2<F, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
>,
> for RouterDataV2<F, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
{
| {
"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_4134908991275845488_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/checkout/transformers.rs
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
PaymentCaptureResponse,
RouterDataV2<F, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let mut router_data = router_data;
// Set status based on HTTP response code
let (status, amount_captured) = if http_code == 202 {
(
enums::AttemptStatus::Charged,
Some(router_data.request.amount_to_capture),
)
} else {
(enums::AttemptStatus::Pending, None)
};
router_data.resource_common_data.status = status;
router_data.resource_common_data.amount_captured = amount_captured;
// Determine the resource_id to return
// If multiple capture, return action_id, otherwise return the original transaction ID
let resource_id = if router_data.request.multiple_capture_data.is_some() {
response.action_id.clone()
} else {
// Extract the String from the ResponseId
match &router_data.request.connector_transaction_id {
ResponseId::ConnectorTransactionId(id) => id.clone(),
_ => response.action_id.clone(), // Fallback
}
};
let connector_meta = serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
});
router_data.response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resource_id),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: response.reference,
incremental_authorization_allowed: None,
status_code: http_code,
});
Ok(router_data)
}
}
// Payment void response conversion
impl<F>
TryFrom<
ResponseRouterData<
PaymentVoidResponse,
RouterDataV2<F, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
>,
> for RouterDataV2<F, PaymentFlowData, PaymentVoidData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
PaymentVoidResponse,
RouterDataV2<F, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
mut response,
router_data,
http_code,
} = item;
let mut router_data = router_data;
// Set the HTTP status code in the response object
response.status = http_code;
// Get the attempt status using the From implementation
let status = enums::AttemptStatus::from(&response);
router_data.resource_common_data.status = status;
let connector_meta = serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Authorize,
});
router_data.response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.action_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code: http_code,
});
Ok(router_data)
}
}
// Payment sync response conversion
impl<F>
TryFrom<
ResponseRouterData<
CheckoutPaymentsResponse,
RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
>,
> for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
CheckoutPaymentsResponse,
RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
| {
"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_4134908991275845488_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/checkout/transformers.rs
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
// For PSync, extract connector_meta if available or create default based on balances
let checkout_meta = to_connector_meta(router_data.request.connector_meta.clone())?;
// Determine status based on both the payment intent from metadata and balances
// This ensures we have the correct status even if metadata is missing
let status = if let Some(balances) = &response.balances {
get_attempt_status_bal((response.status.clone(), Some(balances.clone())))
} else {
get_attempt_status_intent((response.status.clone(), checkout_meta.psync_flow.clone()))
};
let mut router_data = router_data;
router_data.resource_common_data.status = status;
if status == enums::AttemptStatus::Failure {
router_data.response = Err(ErrorResponse {
status_code: http_code,
code: response
.response_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.response_summary
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.response_summary,
attempt_status: None,
connector_transaction_id: Some(response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
});
} else {
// Always include the connector metadata in the response
// This preserves the payment intent information for subsequent operations
let connector_meta = serde_json::json!(CheckoutMeta {
psync_flow: checkout_meta.psync_flow.clone(),
});
router_data.response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: Some(response.reference.unwrap_or(response.id)),
incremental_authorization_allowed: None,
status_code: http_code,
});
}
Ok(router_data)
}
}
// Refund response conversion
impl<F>
TryFrom<
ResponseRouterData<
RefundResponse,
RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
>,
> for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
RefundResponse,
RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
// Create the wrapper structure with status code
let checkout_refund_response = CheckoutRefundResponse {
status: http_code,
response,
};
// Get the refund status using the From implementation
let refund_status = enums::RefundStatus::from(&checkout_refund_response);
let mut router_data = router_data;
router_data.response = Ok(RefundsResponseData {
connector_refund_id: checkout_refund_response.response.action_id,
refund_status,
status_code: http_code,
});
Ok(router_data)
}
}
// Refund sync response conversion
impl<F>
TryFrom<
ResponseRouterData<
ActionResponse,
RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>,
>,
> for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
ActionResponse,
RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>,
>,
) -> Result<Self, Self::Error> {
| {
"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_4134908991275845488_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/checkout/transformers.rs
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
// Get the refund status using the From implementation
let refund_status = enums::RefundStatus::from(&response);
let mut router_data = router_data;
router_data.response = Ok(RefundsResponseData {
connector_refund_id: response.action_id,
refund_status,
status_code: http_code,
});
Ok(router_data)
}
}
// Implementation for CheckoutSyncRequest with CheckoutRouterData - needed for PSync flow
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
super::CheckoutRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
> for CheckoutSyncRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
_item: super::CheckoutRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {})
}
}
// Implementation for CheckoutRefundSyncRequest with CheckoutRouterData
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
super::CheckoutRouterData<
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
T,
>,
> for CheckoutRefundSyncRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
_item: super::CheckoutRouterData<
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {})
}
}
// Also implement for borrowed ActionResponse
impl<F>
TryFrom<
ResponseRouterData<
&ActionResponse,
RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>,
>,
> for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
&ActionResponse,
RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>,
>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
// Get the refund status using the From implementation
let refund_status = enums::RefundStatus::from(response);
let mut router_data = router_data;
router_data.response = Ok(RefundsResponseData {
connector_refund_id: response.action_id.clone(),
refund_status,
status_code: http_code,
});
Ok(router_data)
}
}
| {
"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_4269101882135321764_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashtocode/transformers.rs
use std::collections::HashMap;
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, id_type, request::Method, types::FloatMajorUnit,
Email,
};
use domain_types::{
connector_flow::Authorize,
connector_types::{PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData, ResponseId},
errors::{self, ConnectorError},
payment_method_data::PaymentMethodDataTypes,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
utils,
};
use error_stack::ResultExt;
use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{connectors::cashtocode::CashtocodeRouterData, types::ResponseRouterData};
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsRequest {
amount: FloatMajorUnit,
transaction_id: String,
user_id: Secret<id_type::CustomerId>,
currency: common_enums::Currency,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
user_alias: Secret<id_type::CustomerId>,
requested_url: String,
cancel_url: String,
email: Option<Email>,
mid: Secret<String>,
}
fn get_mid(
connector_auth_type: &ConnectorAuthType,
payment_method_type: Option<common_enums::PaymentMethodType>,
currency: common_enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
match CashtocodeAuth::try_from((connector_auth_type, ¤cy)) {
Ok(cashtocode_auth) => match payment_method_type {
Some(common_enums::PaymentMethodType::ClassicReward) => Ok(cashtocode_auth
.merchant_id_classic
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
Some(common_enums::PaymentMethodType::Evoucher) => Ok(cashtocode_auth
.merchant_id_evoucher
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
},
Err(_) => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CashtocodeRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for CashtocodePaymentsRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: CashtocodeRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let customer_id = item.router_data.resource_common_data.get_customer_id()?;
let url = item.router_data.request.get_router_return_url()?;
let mid = get_mid(
&item.router_data.connector_auth_type,
item.router_data.request.payment_method_type,
item.router_data.request.currency,
)?;
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount,
item.router_data.request.currency,
)
.change_context(ConnectorError::RequestEncodingFailed)?;
match item.router_data.resource_common_data.payment_method {
common_enums::PaymentMethod::Reward => Ok(Self {
amount,
transaction_id: item
.router_data
.resource_common_data
.connector_request_reference_id,
currency: item.router_data.request.currency,
user_id: Secret::new(customer_id.to_owned()),
first_name: None,
last_name: None,
user_alias: Secret::new(customer_id),
requested_url: url.to_owned(),
cancel_url: url,
email: item.router_data.request.email.clone(),
mid,
}),
| {
"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_4269101882135321764_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashtocode/transformers.rs
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuthType {
pub auths: HashMap<common_enums::Currency, CashtocodeAuth>,
}
#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuth {
pub password_classic: Option<Secret<String>>,
pub password_evoucher: Option<Secret<String>>,
pub username_classic: Option<Secret<String>>,
pub username_evoucher: Option<Secret<String>>,
pub merchant_id_classic: Option<Secret<String>>,
pub merchant_id_evoucher: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let transformed_auths = auth_key_map
.iter()
.map(|(currency, identity_auth_key)| {
let cashtocode_auth = identity_auth_key
.to_owned()
.parse_value::<CashtocodeAuth>("CashtocodeAuth")
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "auth_key_map",
})?;
Ok((currency.to_owned(), cashtocode_auth))
})
.collect::<Result<_, Self::Error>>()?;
Ok(Self {
auths: transformed_auths,
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<(&ConnectorAuthType, &common_enums::Currency)> for CashtocodeAuth {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&ConnectorAuthType, &common_enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
if let Some(identity_auth_key) = auth_key_map.get(currency) {
let cashtocode_auth: Self = identity_auth_key
.to_owned()
.parse_value("CashtocodeAuth")
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(cashtocode_auth)
} else {
Err(errors::ConnectorError::CurrencyNotSupported {
message: currency.to_string(),
connector: "CashToCode",
}
.into())
}
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CashtocodePaymentStatus {
Succeeded,
#[default]
Processing,
}
impl From<CashtocodePaymentStatus> for common_enums::AttemptStatus {
fn from(item: CashtocodePaymentStatus) -> Self {
match item {
CashtocodePaymentStatus::Succeeded => Self::Charged,
CashtocodePaymentStatus::Processing => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct CashtocodeErrors {
pub message: String,
pub path: String,
#[serde(rename = "type")]
pub event_type: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CashtocodePaymentsResponse {
CashtoCodeError(CashtocodeErrorResponse),
CashtoCodeData(CashtocodePaymentsResponseData),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsResponseData {
pub pay_url: url::Url,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsSyncResponse {
pub transaction_id: String,
pub amount: FloatMajorUnit,
}
fn get_redirect_form_data(
payment_method_type: common_enums::PaymentMethodType,
response_data: CashtocodePaymentsResponseData,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
match payment_method_type {
| {
"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_4269101882135321764_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashtocode/transformers.rs
common_enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
method: Method::Post,
form_fields: Default::default(),
}),
common_enums::PaymentMethodType::Evoucher => Ok(RedirectForm::Form {
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
endpoint: response_data.pay_url.to_string(),
method: Method::Get,
form_fields: Default::default(),
}),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("CashToCode"),
))?,
}
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize
+ Serialize,
> TryFrom<ResponseRouterData<CashtocodePaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CashtocodePaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let (status, response) = match response {
CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
common_enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: error_data.error.to_string(),
status_code: item.http_code,
message: error_data.error_description.clone(),
reason: Some(error_data.error_description),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
),
CashtocodePaymentsResponse::CashtoCodeData(response_data) => {
let payment_method_type = router_data
.request
.payment_method_type
.ok_or(errors::ConnectorError::MissingPaymentMethodType)?;
let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
(
common_enums::AttemptStatus::AuthenticationPending,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
redirection_data: Some(Box::new(redirection_data)),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code: http_code,
}),
)
}
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..router_data.resource_common_data
},
response,
..router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CashtocodeErrorResponse {
pub error: serde_json::Value,
pub error_description: String,
pub errors: Option<Vec<CashtocodeErrors>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodeIncomingWebhook {
pub amount: FloatMajorUnit,
pub currency: String,
pub foreign_transaction_id: String,
#[serde(rename = "type")]
pub event_type: String,
pub transaction_id: String,
}
| {
"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_4931700295577699981_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
use base64::Engine;
use jsonwebtoken as jwt;
use serde_json::Value;
use common_utils::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
ext_traits::{OptionExt, ValueExt},
pii,
types::{SemanticVersion, StringMajorUnit},
};
use crate::unimplemented_payment_method;
use crate::{connectors::cybersource::CybersourceRouterData, types::ResponseRouterData, utils};
use cards;
use domain_types::{
connector_flow::{
Authenticate, Authorize, Capture, PostAuthenticate, PreAuthenticate, RepeatPayment,
SetupMandate, Void,
},
connector_types::{
MandateReference, MandateReferenceId, PaymentFlowData, PaymentVoidData,
PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsResponseData,
PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData, RefundsResponseData,
RepeatPaymentData, ResponseId, SetupMandateRequestData,
},
errors::{self, ConnectorError},
payment_address::Address,
payment_method_data::{
self, ApplePayWalletData, GPayPredecryptData, GooglePayWalletData, NetworkTokenData,
PaymentMethodData, PaymentMethodDataTypes, RawCardNumber, SamsungPayWalletData, WalletData,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType,
ErrorResponse, GooglePayDecryptedData, NetworkTokenNumber, PaymentMethodToken,
PazeDecryptedData,
},
router_data_v2::RouterDataV2,
router_request_types,
router_response_types::RedirectForm,
utils::CardIssuer,
};
use error_stack::{report, ResultExt};
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
pub const REFUND_VOIDED: &str = "Refund request has been voided.";
fn card_issuer_to_string(card_issuer: CardIssuer) -> String {
let card_type = match card_issuer {
CardIssuer::AmericanExpress => "003",
CardIssuer::Master => "002",
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
CardIssuer::Maestro => "042",
CardIssuer::Visa => "001",
CardIssuer::Discover => "004",
CardIssuer::DinersClub => "005",
CardIssuer::CarteBlanche => "006",
CardIssuer::JCB => "007",
CardIssuer::CartesBancaires => "036",
};
card_type.to_string()
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CybersourceConnectorMetadataObject {
pub disable_avs: Option<bool>,
pub disable_cvn: Option<bool>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for CybersourceConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceZeroMandateRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
processing_information: ProcessingInformation,
payment_information: PaymentInformation<T>,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
> for CybersourceZeroMandateRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: CybersourceRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
| {
"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_4931700295577699981_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let email = item
.router_data
.resource_common_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill {
amount_details: Amount {
total_amount: StringMajorUnit::zero(),
currency: item.router_data.request.currency,
},
bill_to: Some(bill_to),
};
let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(
&item
.router_data
.request
.metadata
.clone()
.map(pii::SecretSerdeValue::new),
)?;
let (action_list, action_token_types, authorization_options) = (
Some(vec![CybersourceActionsList::TokenCreate]),
Some(vec![
CybersourceActionsTokenType::PaymentInstrument,
CybersourceActionsTokenType::Customer,
]),
Some(CybersourceAuthorizationOptions {
initiator: Some(CybersourcePaymentInitiator {
initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
credential_stored_on_file: Some(true),
stored_credential_used: None,
}),
merchant_initiated_transaction: None,
ignore_avs_result: connector_merchant_config.disable_avs,
ignore_cv_result: connector_merchant_config.disable_cvn,
}),
);
let client_reference_information = ClientReferenceInformation {
code: Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
};
let (payment_information, solution) = match item
.router_data
.request
.payment_method_data
.clone()
{
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_cybersource_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => domain_types::utils::get_card_issuer(
&(format!("{:?}", ccard.card_number.0)),
)
.ok()
.map(card_issuer_to_string),
};
(
PaymentInformation::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
})),
None,
)
}
PaymentMethodData::Wallet(wallet_data) => {
match wallet_data {
WalletData::ApplePay(apple_pay_data) => match item
.router_data
.resource_common_data
.payment_method_token
.clone()
{
Some(payment_method_token) => {
match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
let expiration_month =
decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
| {
"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_4931700295577699981_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
},
)?;
let expiration_year =
decrypt_data.get_four_digit_expiry_year()?;
(
PaymentInformation::ApplePay(Box::new(
ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: cards::CardNumber::try_from(decrypt_data.application_primary_account_number.expose().to_string())
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "application_primary_account_number",
})?,
cryptogram: Some(
decrypt_data.payment_data.online_payment_cryptogram,
),
transaction_type: TransactionType::InApp,
expiration_year,
expiration_month,
},
},
)),
Some(PaymentSolution::ApplePay),
)
}
PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Cybersource"
))?
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Cybersource"))?
}
}
}
None => {
let apple_pay_encrypted_data = apple_pay_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
(
PaymentInformation::ApplePayToken(Box::new(
ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_encrypted_data.clone()),
descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
tokenized_card: ApplePayTokenizedCard {
transaction_type: TransactionType::InApp,
},
},
)),
Some(PaymentSolution::ApplePay),
)
}
},
WalletData::GooglePay(google_pay_data) => (
PaymentInformation::GooglePayToken(Box::new(
GooglePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
BASE64_ENGINE.encode(
google_pay_data
.tokenization_data
| {
"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_4931700295577699981_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
.get_encrypted_google_pay_token()
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
},
)?,
),
),
descriptor: None,
},
tokenized_card: GooglePayTokenizedCard {
transaction_type: TransactionType::InApp,
},
},
)),
Some(PaymentSolution::GooglePay),
),
WalletData::SamsungPay(samsung_pay_data) => (
(get_samsung_pay_payment_information(&samsung_pay_data)
.attach_printable("Failed to get samsung pay payment information")?),
Some(PaymentSolution::SamsungPay),
),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
domain_types::utils::get_unimplemented_payment_method_error_message(
"Cybersource",
),
))?,
}
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| 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(errors::ConnectorError::NotImplemented(
domain_types::utils::get_unimplemented_payment_method_error_message(
"Cybersource",
),
))?
}
};
let processing_information = ProcessingInformation {
capture: Some(false),
capture_options: None,
action_list,
action_token_types,
authorization_options,
commerce_indicator: String::from("internet"),
| {
"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_4931700295577699981_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
payment_solution: solution.map(String::from),
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
processing_information: ProcessingInformation,
payment_information: PaymentInformation<T>,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
consumer_authentication_information: Option<CybersourceConsumerAuthInformation>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformation {
action_list: Option<Vec<CybersourceActionsList>>,
action_token_types: Option<Vec<CybersourceActionsTokenType>>,
authorization_options: Option<CybersourceAuthorizationOptions>,
commerce_indicator: String,
capture: Option<bool>,
capture_options: Option<CaptureOptions>,
payment_solution: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum CybersourceParesStatus {
#[serde(rename = "C")]
CardChallenged,
#[serde(rename = "R")]
AuthenticationRejected,
#[serde(rename = "Y")]
AuthenticationSuccessful,
#[serde(rename = "A")]
AuthenticationAttempted,
#[serde(rename = "N")]
AuthenticationFailed,
#[serde(rename = "U")]
AuthenticationNotCompleted,
}
impl From<CybersourceParesStatus> for common_enums::TransactionStatus {
fn from(status: CybersourceParesStatus) -> Self {
match status {
CybersourceParesStatus::AuthenticationSuccessful => {
common_enums::TransactionStatus::Success
}
CybersourceParesStatus::AuthenticationAttempted => {
common_enums::TransactionStatus::NotVerified
}
CybersourceParesStatus::AuthenticationFailed => {
common_enums::TransactionStatus::Failure
}
CybersourceParesStatus::AuthenticationNotCompleted => {
common_enums::TransactionStatus::VerificationNotPerformed
}
CybersourceParesStatus::CardChallenged => {
common_enums::TransactionStatus::ChallengeRequired
}
CybersourceParesStatus::AuthenticationRejected => {
common_enums::TransactionStatus::Rejected
}
}
}
}
impl From<common_enums::TransactionStatus> for CybersourceParesStatus {
fn from(status: common_enums::TransactionStatus) -> Self {
match status {
common_enums::TransactionStatus::Success => Self::AuthenticationSuccessful,
common_enums::TransactionStatus::Failure => Self::AuthenticationFailed,
common_enums::TransactionStatus::VerificationNotPerformed => {
Self::AuthenticationNotCompleted
}
common_enums::TransactionStatus::NotVerified => Self::AuthenticationAttempted,
common_enums::TransactionStatus::Rejected => Self::AuthenticationRejected,
common_enums::TransactionStatus::ChallengeRequired => Self::CardChallenged,
common_enums::TransactionStatus::ChallengeRequiredDecoupledAuthentication => {
Self::CardChallenged
}
common_enums::TransactionStatus::InformationOnly => Self::AuthenticationNotCompleted,
}
}
}
fn get_authentication_data_for_check_enrollment_response(
response: CybersourceConsumerAuthInformationEnrollmentResponse,
) -> router_request_types::AuthenticationData {
let trans_status = response
.validate_response
.pares_status
.map(common_enums::TransactionStatus::from);
// CAVV is populated from UCAF data if available(for mastercard), else from CAVV field
let cavv = response
.validate_response
.ucaf_authentication_data
.or(response.validate_response.cavv);
| {
"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_4931700295577699981_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
let eci = response.validate_response.ecommerce_indicator;
let ucaf_collection_indicator = response.validate_response.ucaf_collection_indicator.clone();
let ds_trans_id = response
.validate_response
.directory_server_transaction_id
.map(|id| id.expose());
router_request_types::AuthenticationData {
ucaf_collection_indicator,
eci,
cavv,
threeds_server_transaction_id: response.validate_response.three_d_s_server_transaction_id,
message_version: response.validate_response.specification_version,
trans_status,
ds_trans_id,
acs_transaction_id: response.validate_response.acs_transaction_id,
transaction_id: response.validate_response.xid,
}
}
fn get_authentication_data_for_validation_response(
response: CybersourceConsumerAuthInformationEnrollmentResponse,
) -> router_request_types::AuthenticationData {
let trans_status = response
.validate_response
.pares_status
.map(common_enums::TransactionStatus::from);
// CAVV is populated from UCAF data if available(for mastercard), else from CAVV field
let cavv = response
.validate_response
.ucaf_authentication_data
.or(response.validate_response.cavv);
let eci = response.validate_response.indicator;
let ucaf_collection_indicator = response.validate_response.ucaf_collection_indicator.clone();
let ds_trans_id = response
.validate_response
.directory_server_transaction_id
.map(|id| id.expose());
router_request_types::AuthenticationData {
ucaf_collection_indicator,
eci,
cavv,
threeds_server_transaction_id: response.validate_response.three_d_s_server_transaction_id,
message_version: response.validate_response.specification_version,
trans_status,
ds_trans_id,
acs_transaction_id: response.validate_response.acs_transaction_id,
transaction_id: response.validate_response.xid,
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<SemanticVersion>,
/// This field specifies the 3ds version
pa_specification_version: Option<SemanticVersion>,
/// Verification response enrollment status.
///
/// This field is supported only on Asia, Middle East, and Africa Gateway.
///
/// For external authentication, this field will always be "Y"
veres_enrolled: Option<String>,
/// Raw electronic commerce indicator (ECI)
eci_raw: Option<String>,
/// This field is supported only on Asia, Middle East, and Africa Gateway
/// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions
/// This field is only applicable for Mastercard and Visa Transactions
pares_status: Option<CybersourceParesStatus>,
//This field is used to send the authentication date in yyyyMMDDHHMMSS format
authentication_date: Option<String>,
/// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France.
/// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless)
effective_authentication_type: Option<EffectiveAuthenticationType>,
/// This field indicates the authentication type or challenge presented to the cardholder at checkout.
challenge_code: Option<String>,
/// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France.
signed_pares_status_reason: Option<String>,
/// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France.
challenge_cancel_code: Option<String>,
/// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France.
network_score: Option<u32>,
| {
"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_4931700295577699981_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
/// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France.
acs_transaction_id: Option<String>,
/// This is the algorithm for generating a cardholder authentication verification value (CAVV) or universal cardholder authentication field (UCAF) data.
cavv_algorithm: Option<String>,
}
impl From<router_request_types::AuthenticationData> for CybersourceConsumerAuthInformation {
fn from(value: router_request_types::AuthenticationData) -> Self {
let router_request_types::AuthenticationData {
eci: _,
cavv,
threeds_server_transaction_id: _,
message_version,
ds_trans_id,
trans_status: _,
acs_transaction_id: _,
transaction_id,
ucaf_collection_indicator,
} = value;
CybersourceConsumerAuthInformation {
pares_status: None,
ucaf_collection_indicator,
ucaf_authentication_data: cavv.clone(),
xid: transaction_id,
cavv,
directory_server_transaction_id: ds_trans_id.map(Secret::new),
specification_version: None,
pa_specification_version: message_version,
veres_enrolled: None,
eci_raw: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
signed_pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
cavv_algorithm: None,
}
}
}
#[derive(Debug, Serialize)]
pub enum EffectiveAuthenticationType {
CH,
FR,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDefinedInformation {
key: u8,
value: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceActionsList {
TokenCreate,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum CybersourceActionsTokenType {
Customer,
PaymentInstrument,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceAuthorizationOptions {
initiator: Option<CybersourcePaymentInitiator>,
merchant_initiated_transaction: Option<MerchantInitiatedTransaction>,
ignore_avs_result: Option<bool>,
ignore_cv_result: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInitiatedTransaction {
reason: Option<String>,
previous_transaction_id: Option<Secret<String>>,
//Required for recurring mandates payment
original_authorized_amount: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentInitiator {
#[serde(rename = "type")]
initiator_type: Option<CybersourcePaymentInitiatorTypes>,
credential_stored_on_file: Option<bool>,
stored_credential_used: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum CybersourcePaymentInitiatorTypes {
Customer,
Merchant,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureOptions {
capture_sequence_number: u32,
total_capture_count: u32,
is_final: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenizedCard {
number: NetworkTokenNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Option<Secret<String>>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenPaymentInformation {
tokenized_card: NetworkTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentInformation<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
card: Card<T>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCard {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Option<Secret<String>>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenizedCard {
| {
"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_4931700295577699981_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: ApplePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPaymentInformation {
tokenized_card: TokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandatePaymentTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandateCard {
type_selection_indicator: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandatePaymentInformation {
payment_instrument: CybersoucrePaymentInstrument,
#[serde(skip_serializing_if = "Option::is_none")]
tokenized_card: Option<MandatePaymentTokenizedCard>,
card: Option<MandateCard>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FluidData {
value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
descriptor: Option<String>,
}
pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U";
pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT";
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: GooglePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
tokenized_card: TokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayPaymentInformation {
fluid_data: FluidData,
tokenized_card: SamsungPayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayFluidDataValue {
public_key_hash: Secret<String>,
version: String,
data: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MessageExtensionAttribute {
pub id: String,
pub name: String,
pub criticality_indicator: bool,
pub data: serde_json::Value,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
Cards(Box<CardPaymentInformation<T>>),
GooglePayToken(Box<GooglePayTokenPaymentInformation>),
GooglePay(Box<GooglePayPaymentInformation>),
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
MandatePayment(Box<MandatePaymentInformation>),
SamsungPay(Box<SamsungPayPaymentInformation>),
NetworkToken(Box<NetworkTokenPaymentInformation>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CybersoucrePaymentInstrument {
id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
number: RawCardNumber<T>,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Option<Secret<String>>,
#[serde(rename = "type")]
card_type: Option<String>,
type_selection_indicator: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationWithBill {
amount_details: Amount,
bill_to: Option<BillTo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationIncrementalAuthorization {
amount_details: AdditionalAmount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformation {
amount_details: Amount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: StringMajorUnit,
currency: common_enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalAmount {
| {
"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_4931700295577699981_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
additional_amount: StringMajorUnit,
currency: String,
}
#[derive(Debug, Serialize)]
pub enum PaymentSolution {
ApplePay,
GooglePay,
SamsungPay,
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "1")]
InApp,
#[serde(rename = "2")]
ContactlessNFC,
#[serde(rename = "3")]
StoredCredentials,
}
impl From<PaymentSolution> for String {
fn from(solution: PaymentSolution) -> Self {
let payment_solution = match solution {
PaymentSolution::ApplePay => "001",
PaymentSolution::GooglePay => "012",
PaymentSolution::SamsungPay => "008",
};
payment_solution.to_string()
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address1: Option<Secret<String>>,
locality: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
country: Option<common_enums::CountryAlpha2>,
email: pii::Email,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
From<
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for ClientReferenceInformation
{
fn from(
item: &CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Self {
Self {
code: Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
From<
&CybersourceRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
> for ClientReferenceInformation
{
fn from(
item: &CybersourceRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
) -> Self {
Self {
code: Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
From<
&CybersourceRouterData<
RouterDataV2<
PreAuthenticate,
PaymentFlowData,
PaymentsPreAuthenticateData<T>,
PaymentsResponseData,
>,
T,
>,
> for ClientReferenceInformation
{
fn from(
item: &CybersourceRouterData<
RouterDataV2<
PreAuthenticate,
PaymentFlowData,
PaymentsPreAuthenticateData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Self {
Self {
code: Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
| {
"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_4931700295577699981_9 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let commerce_indicator = solution
.as_ref()
.map(|pm_solution| match pm_solution {
PaymentSolution::ApplePay | PaymentSolution::SamsungPay => network
.as_ref()
.map(|card_network| match card_network.to_lowercase().as_str() {
"mastercard" => "spa",
_ => "internet",
})
.unwrap_or("internet"),
PaymentSolution::GooglePay => "internet",
})
.unwrap_or("internet")
.to_string();
let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(
&item.router_data.resource_common_data.connector_meta_data,
)?;
let (action_list, action_token_types, authorization_options) =
if item.router_data.request.setup_future_usage
== Some(common_enums::FutureUsage::OffSession)
&& (item.router_data.request.customer_acceptance.is_some())
{
(
Some(vec![CybersourceActionsList::TokenCreate]),
Some(vec![
CybersourceActionsTokenType::PaymentInstrument,
CybersourceActionsTokenType::Customer,
]),
Some(CybersourceAuthorizationOptions {
initiator: Some(CybersourcePaymentInitiator {
initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
credential_stored_on_file: Some(true),
stored_credential_used: None,
}),
ignore_avs_result: connector_merchant_config.disable_avs,
ignore_cv_result: connector_merchant_config.disable_cvn,
merchant_initiated_transaction: None,
}),
)
} else {
(
None,
None,
Some(CybersourceAuthorizationOptions {
initiator: None,
merchant_initiated_transaction: None,
ignore_avs_result: connector_merchant_config.disable_avs,
ignore_cv_result: connector_merchant_config.disable_cvn,
}),
)
};
// this logic is for external authenticated card
let commerce_indicator_for_external_authentication = item
.router_data
.request
.authentication_data
.as_ref()
.and_then(|authentication_data| authentication_data.eci.clone());
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(common_enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
action_list,
action_token_types,
authorization_options,
capture_options: None,
commerce_indicator: commerce_indicator_for_external_authentication
.unwrap_or(commerce_indicator),
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Option<BillTo>,
)> for OrderInformationWithBill
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
| {
"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_4931700295577699981_10 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
(item, bill_to): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Option<BillTo>,
),
) -> Result<Self, Self::Error> {
let total_amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount.to_owned(),
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
Ok(Self {
amount_details: Amount {
total_amount,
currency: item.router_data.request.currency,
},
bill_to,
})
}
}
fn truncate_string(state: &Secret<String>, max_len: usize) -> Secret<String> {
let exposed = state.clone().expose();
let truncated = exposed.get(..max_len).unwrap_or(&exposed);
Secret::new(truncated.to_string())
}
fn build_bill_to(
address_details: Option<&Address>,
email: pii::Email,
) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
let default_address = BillTo {
first_name: None,
last_name: None,
address1: None,
locality: None,
administrative_area: None,
postal_code: None,
country: None,
email: email.clone(),
};
Ok(address_details
.and_then(|addr| {
addr.address.as_ref().map(|addr| BillTo {
first_name: addr.first_name.remove_new_line(),
last_name: addr.last_name.remove_new_line(),
address1: addr.line1.remove_new_line(),
locality: addr.city.remove_new_line(),
administrative_area: addr.to_state_code_as_optional().unwrap_or_else(|_| {
addr.state
.remove_new_line()
.as_ref()
.map(|state| truncate_string(state, 20)) //NOTE: Cybersource connector throws error if billing state exceeds 20 characters, so truncation is done to avoid payment failure
}),
postal_code: addr.zip.remove_new_line(),
country: addr.country,
email,
})
})
.unwrap_or(default_address))
}
fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
let hashmap: std::collections::BTreeMap<String, Value> =
serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
let mut vector = Vec::new();
let mut iter = 1;
for (key, value) in hashmap {
vector.push(MerchantDefinedInformation {
key: iter,
value: format!("{key}={value}"),
});
iter += 1;
}
vector
}
impl From<common_enums::DecoupledAuthenticationType> for EffectiveAuthenticationType {
fn from(auth_type: common_enums::DecoupledAuthenticationType) -> Self {
match auth_type {
common_enums::DecoupledAuthenticationType::Challenge => Self::CH,
common_enums::DecoupledAuthenticationType::Frictionless => Self::FR,
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
payment_method_data::Card<T>,
)> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
payment_method_data::Card<T>,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.resource_common_data
| {
"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_4931700295577699981_11 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill::try_from((item, Some(bill_to)))?;
let raw_card_type = ccard.card_network.clone();
let card_type = match raw_card_type.clone().and_then(get_cybersource_card_type) {
Some(card_network) => Some(card_network.to_string()),
None => domain_types::utils::get_card_issuer(&(format!("{:?}", ccard.card_number.0)))
.ok()
.map(card_issuer_to_string),
};
let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type: card_type.clone(),
type_selection_indicator: Some("1".to_owned()),
},
}));
let processing_information = ProcessingInformation::try_from((
item,
None,
raw_card_type.map(|network| network.to_string()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let consumer_authentication_information = item
.router_data
.request
.authentication_data
.clone()
.map(From::from);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information,
merchant_defined_information,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
NetworkTokenData,
)> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, token_data): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let transaction_type = if item.router_data.request.off_session == Some(true) {
TransactionType::StoredCredentials
} else {
TransactionType::InApp
};
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill::try_from((item, Some(bill_to)))?;
let card_issuer =
domain_types::utils::get_card_issuer(token_data.get_network_token().peek());
let card_type = match card_issuer {
Ok(issuer) => Some(card_issuer_to_string(issuer)),
Err(_) => None,
};
let payment_information =
PaymentInformation::NetworkToken(Box::new(NetworkTokenPaymentInformation {
tokenized_card: NetworkTokenizedCard {
number: token_data.get_network_token(),
expiration_month: token_data.get_network_token_expiry_month(),
expiration_year: token_data.get_network_token_expiry_year(),
cryptogram: token_data.get_cryptogram().clone(),
transaction_type,
},
}));
| {
"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_4931700295577699981_12 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
let processing_information = ProcessingInformation::try_from((item, None, card_type))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: None,
merchant_defined_information,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<PazeDecryptedData>,
)> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, paze_data): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<PazeDecryptedData>,
),
) -> Result<Self, Self::Error> {
let transaction_type = if item.router_data.request.off_session == Some(true) {
TransactionType::StoredCredentials
} else {
TransactionType::InApp
};
let email = item.router_data.request.get_email()?;
let (first_name, last_name) = match paze_data.billing_address.name {
Some(name) => {
let (first_name, last_name) = name
.peek()
.split_once(' ')
.map(|(first, last)| (first.to_string(), last.to_string()))
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.name",
})?;
(Secret::from(first_name), Secret::from(last_name))
}
None => (
item.router_data
.resource_common_data
.get_billing_first_name()?,
item.router_data
.resource_common_data
.get_billing_last_name()?,
),
};
let bill_to = BillTo {
first_name: Some(first_name),
last_name: Some(last_name),
address1: paze_data.billing_address.line1,
locality: paze_data.billing_address.city.map(|city| city.expose()),
administrative_area: Some(Secret::from(
//Paze wallet is currently supported in US only
domain_types::utils::convert_us_state_to_code(
paze_data
.billing_address
.state
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.state",
})?
.peek(),
),
)),
postal_code: paze_data.billing_address.zip,
country: paze_data.billing_address.country_code,
email,
};
let order_information = OrderInformationWithBill::try_from((item, Some(bill_to)))?;
let payment_information =
PaymentInformation::NetworkToken(Box::new(NetworkTokenPaymentInformation {
tokenized_card: NetworkTokenizedCard {
number: paze_data.token.payment_token,
expiration_month: paze_data.token.token_expiration_month,
expiration_year: paze_data.token.token_expiration_year,
cryptogram: Some(paze_data.token.payment_account_reference),
transaction_type,
},
}));
let processing_information = ProcessingInformation::try_from((item, None, None))?;
| {
"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_4931700295577699981_13 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: None,
merchant_defined_information,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
)> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
input: (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let (item, apple_pay_data, apple_pay_wallet_data) = input;
let transaction_type = if item.router_data.request.off_session == Some(true) {
TransactionType::StoredCredentials
} else {
TransactionType::InApp
};
let email = item
.router_data
.resource_common_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill::try_from((item, Some(bill_to)))?;
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_wallet_data.payment_method.network.clone()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let expiration_month = apple_pay_data.get_expiry_month()?;
if let Err(parse_err) = expiration_month.peek().parse::<u8>() {
tracing::warn!(
"Invalid expiration month format in Apple Pay data: {}. Error: {}",
expiration_month.peek(),
parse_err
);
}
let expiration_year = apple_pay_data.get_four_digit_expiry_year()?;
let payment_information =
PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: apple_pay_data
.application_primary_account_number
.expose()
.parse::<cards::CardNumber>()
.map_err(|err| {
tracing::error!(
"Failed to parse Apple Pay account number as CardNumber: {:?}",
err
);
report!(ConnectorError::RequestEncodingFailed)
})?,
cryptogram: Some(apple_pay_data.payment_data.online_payment_cryptogram),
transaction_type,
expiration_year,
expiration_month,
},
}));
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
| {
"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_4931700295577699981_14 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: Some(CybersourceConsumerAuthInformation {
pares_status: None,
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
pa_specification_version: None,
veres_enrolled: None,
eci_raw: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
signed_pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
cavv_algorithm: None,
}),
merchant_defined_information,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
GooglePayWalletData,
)> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.resource_common_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill::try_from((item, Some(bill_to)))?;
let payment_information =
PaymentInformation::GooglePayToken(Box::new(GooglePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
BASE64_ENGINE.encode(
google_pay_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?,
),
),
descriptor: None,
},
tokenized_card: GooglePayTokenizedCard {
transaction_type: TransactionType::InApp,
},
}));
let processing_information =
ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: None,
merchant_defined_information,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
| {
"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_4931700295577699981_15 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<GPayPredecryptData>,
GooglePayWalletData,
)> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_decrypted_data, google_pay_data): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<GPayPredecryptData>,
GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let transaction_type = if item.router_data.request.off_session == Some(true) {
TransactionType::StoredCredentials
} else {
TransactionType::InApp
};
let email = item
.router_data
.resource_common_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill::try_from((item, Some(bill_to)))?;
let payment_information =
PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation {
tokenized_card: TokenizedCard {
number: google_pay_decrypted_data
.application_primary_account_number
.clone(),
cryptogram: google_pay_decrypted_data.cryptogram.clone(),
transaction_type,
expiration_year: google_pay_decrypted_data
.get_four_digit_expiry_year()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_year",
})?,
expiration_month: google_pay_decrypted_data
.get_expiry_month()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
})?,
},
}));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::GooglePay),
Some(google_pay_data.info.card_network.clone()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator =
match google_pay_data.info.card_network.to_lowercase().as_str() {
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: Some(CybersourceConsumerAuthInformation {
pares_status: None,
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
pa_specification_version: None,
veres_enrolled: None,
eci_raw: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
signed_pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
cavv_algorithm: None,
}),
merchant_defined_information,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
| {
"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_4931700295577699981_16 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<GooglePayDecryptedData>,
GooglePayWalletData,
)> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_decrypted_data, google_pay_data): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<GooglePayDecryptedData>,
GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let transaction_type = if item.router_data.request.off_session == Some(true) {
TransactionType::StoredCredentials
} else {
TransactionType::InApp
};
let email = item
.router_data
.resource_common_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill::try_from((item, Some(bill_to)))?;
let payment_information =
PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation {
tokenized_card: TokenizedCard {
number: google_pay_decrypted_data.payment_method_details.pan.clone(),
cryptogram: google_pay_decrypted_data
.payment_method_details
.cryptogram
.clone(),
transaction_type,
expiration_year: Secret::new(
google_pay_decrypted_data
.payment_method_details
.expiration_year
.get_year()
.to_string(),
),
expiration_month: Secret::new(
google_pay_decrypted_data
.payment_method_details
.expiration_month
.two_digits(),
),
},
}));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::GooglePay),
Some(google_pay_data.info.card_network.clone()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator =
match google_pay_data.info.card_network.to_lowercase().as_str() {
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: Some(CybersourceConsumerAuthInformation {
pares_status: None,
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
pa_specification_version: None,
veres_enrolled: None,
eci_raw: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
signed_pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
cavv_algorithm: None,
}),
merchant_defined_information,
})
}
}
impl<
| {
"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_4931700295577699981_17 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<SamsungPayWalletData>,
)> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, samsung_pay_data): (
&CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
Box<SamsungPayWalletData>,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.resource_common_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill::try_from((item, Some(bill_to)))?;
let payment_information = get_samsung_pay_payment_information(&samsung_pay_data)
.attach_printable("Failed to get samsung pay payment information")?;
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::SamsungPay),
Some(samsung_pay_data.payment_credential.card_brand.to_string()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: None,
merchant_defined_information,
})
}
}
fn get_samsung_pay_payment_information<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
samsung_pay_data: &payment_method_data::SamsungPayWalletData,
) -> Result<PaymentInformation<T>, error_stack::Report<errors::ConnectorError>> {
let samsung_pay_fluid_data_value =
get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?;
let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to serialize samsung pay fluid data")?;
let payment_information =
PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation {
fluid_data: FluidData {
value: Secret::new(BASE64_ENGINE.encode(samsung_pay_fluid_data_str)),
descriptor: Some(BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY)),
},
tokenized_card: SamsungPayTokenizedCard {
transaction_type: TransactionType::InApp,
},
}));
Ok(payment_information)
}
fn get_samsung_pay_fluid_data_value(
samsung_pay_token_data: &payment_method_data::SamsungPayTokenData,
) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> {
let samsung_pay_header = jwt::decode_header(samsung_pay_token_data.data.clone().peek())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to decode samsung pay header")?;
let samsung_pay_kid_optional = samsung_pay_header.kid;
let samsung_pay_fluid_data_value = SamsungPayFluidDataValue {
public_key_hash: Secret::new(
samsung_pay_kid_optional
.get_required_value("samsung pay public_key_hash")
.change_context(errors::ConnectorError::RequestEncodingFailed)?
| {
"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_4931700295577699981_18 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
.to_string(),
),
version: samsung_pay_token_data.version.clone(),
data: Secret::new(BASE64_ENGINE.encode(samsung_pay_token_data.data.peek())),
};
Ok(samsung_pay_fluid_data_value)
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for CybersourcePaymentsRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CybersourceRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Self::try_from((&item, ccard)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(apple_pay_data) => {
match item
.router_data
.resource_common_data
.payment_method_token
.clone()
{
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
Self::try_from((&item, decrypt_data, apple_pay_data))
}
PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Cybersource"
))?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Cybersource"))?
}
},
None => {
let transaction_type =
if item.router_data.request.off_session == Some(true) {
TransactionType::StoredCredentials
} else {
TransactionType::InApp
};
let email = item
.router_data
.resource_common_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information =
OrderInformationWithBill::try_from((&item, Some(bill_to)))?;
let processing_information = ProcessingInformation::try_from((
&item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_data.payment_method.network.clone()),
))?;
let client_reference_information =
ClientReferenceInformation::from(&item);
let apple_pay_encrypted_data = apple_pay_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
| {
"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_4931700295577699981_19 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
field_name: "Apple pay encrypted data",
})?;
let payment_information = PaymentInformation::ApplePayToken(Box::new(
ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_encrypted_data.clone()),
descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
tokenized_card: ApplePayTokenizedCard { transaction_type },
},
));
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata)
});
let ucaf_collection_indicator = match apple_pay_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: Some(
CybersourceConsumerAuthInformation {
pares_status: None,
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
pa_specification_version: None,
veres_enrolled: None,
eci_raw: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
signed_pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
cavv_algorithm: None,
},
),
})
}
}
}
WalletData::GooglePay(google_pay_data) => {
match item
.router_data
.resource_common_data
.payment_method_token
.clone()
{
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::GooglePayDecrypt(decrypt_data) => {
Self::try_from((&item, decrypt_data, google_pay_data))
}
PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Cybersource"
))?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
| {
"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_4931700295577699981_20 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
PaymentMethodToken::ApplePayDecrypt(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Simplified",
"Cybersource"
))?
}
},
None => Self::try_from((&item, google_pay_data)),
}
}
WalletData::SamsungPay(samsung_pay_data) => {
Self::try_from((&item, samsung_pay_data))
}
WalletData::Paze(_) => {
match item
.router_data
.resource_common_data
.payment_method_token
.clone()
{
Some(PaymentMethodToken::PazeDecrypt(paze_decrypted_data)) => {
Self::try_from((&item, paze_decrypted_data))
}
Some(PaymentMethodToken::Token(_))
| Some(PaymentMethodToken::ApplePayDecrypt(_))
| Some(PaymentMethodToken::GooglePayDecrypt(_))
| None => Err(errors::ConnectorError::NotImplemented(
domain_types::utils::get_unimplemented_payment_method_error_message(
"Cybersource",
),
)
.into()),
}
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
domain_types::utils::get_unimplemented_payment_method_error_message(
"Cybersource",
),
)
.into()),
},
PaymentMethodData::NetworkToken(token_data) => Self::try_from((&item, token_data)),
PaymentMethodData::MandatePayment
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
domain_types::utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
.into()),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
| {
"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_4931700295577699981_21 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
pub struct CybersourceAuthSetupRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
payment_information: PaymentInformation<T>,
client_reference_information: ClientReferenceInformation,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<
RouterDataV2<
PreAuthenticate,
PaymentFlowData,
PaymentsPreAuthenticateData<T>,
PaymentsResponseData,
>,
T,
>,
> for CybersourceAuthSetupRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CybersourceRouterData<
RouterDataV2<
PreAuthenticate,
PaymentFlowData,
PaymentsPreAuthenticateData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let payment_method_data = item
.router_data
.request
.payment_method_data
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_data",
})?;
match payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_cybersource_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => domain_types::utils::get_card_issuer(
&(format!("{:?}", ccard.card_number.0)),
)
.ok()
.map(card_issuer_to_string),
};
let payment_information =
PaymentInformation::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
}));
let client_reference_information = ClientReferenceInformation::from(&item);
Ok(Self {
payment_information,
client_reference_information,
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| 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(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
.into())
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentsCaptureRequest {
processing_information: ProcessingInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
| {
"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_4931700295577699981_22 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentsIncrementalAuthorizationRequest {
processing_information: ProcessingInformation,
order_information: OrderInformationIncrementalAuthorization,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for CybersourcePaymentsCaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: CybersourceRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = item
.router_data
.request
.connector_metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let is_final = matches!(
item.router_data.request.capture_method,
Some(common_enums::CaptureMethod::Manual)
)
.then_some(true);
let total_amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount_to_capture,
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
Ok(Self {
processing_information: ProcessingInformation {
capture_options: Some(CaptureOptions {
capture_sequence_number: 1,
total_capture_count: 1,
is_final,
}),
action_list: None,
action_token_types: None,
authorization_options: None,
capture: None,
commerce_indicator: String::from("internet"),
payment_solution: None,
},
order_information: OrderInformationWithBill {
amount_details: Amount {
total_amount,
currency: item.router_data.request.currency,
},
bill_to: None,
},
client_reference_information: ClientReferenceInformation {
code: Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
},
merchant_defined_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceVoidRequest {
client_reference_information: ClientReferenceInformation,
reversal_information: ReversalInformation,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
// The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works!
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReversalInformation {
amount_details: Amount,
reason: String,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
> for CybersourceVoidRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
value: CybersourceRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.connector_metadata
.clone()
.map(|connector_metadata| {
convert_metadata_to_merchant_defined_info(connector_metadata.expose())
});
| {
"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_4931700295577699981_23 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
let currency = value.router_data.request.currency.unwrap();
let total_amount = value
.connector
.amount_converter
.convert(value.router_data.request.amount.unwrap(), currency)
.change_context(ConnectorError::AmountConversionFailed)?;
Ok(Self {
client_reference_information: ClientReferenceInformation {
code: Some(
value
.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
},
reversal_information: ReversalInformation {
amount_details: Amount {
total_amount,
currency,
},
reason: value
.router_data
.request
.cancellation_reason
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Cancellation Reason",
})?,
},
merchant_defined_information,
})
}
}
pub struct CybersourceAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CybersourceAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AuthorizationStatus {
Success,
Failure,
Processing,
Unresolved,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourcePaymentStatus {
Authorized,
Succeeded,
Failed,
Voided,
Reversed,
Pending,
Declined,
Rejected,
Challenge,
AuthorizedPendingReview,
AuthorizedRiskDeclined,
Transmitted,
InvalidRequest,
ServerError,
PendingAuthentication,
PendingReview,
Accepted,
Cancelled,
StatusNotReceived,
//PartialAuthorized, not being consumed yet.
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceIncrementalAuthorizationStatus {
Authorized,
Declined,
AuthorizedPendingReview,
}
pub fn map_cybersource_attempt_status(
status: CybersourcePaymentStatus,
capture: bool,
) -> common_enums::AttemptStatus {
match status {
CybersourcePaymentStatus::Authorized => {
if capture {
// Because Cybersource will return Payment Status as Authorized even in AutoCapture Payment
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Authorized
}
}
CybersourcePaymentStatus::Succeeded | CybersourcePaymentStatus::Transmitted => {
common_enums::AttemptStatus::Charged
}
CybersourcePaymentStatus::Voided
| CybersourcePaymentStatus::Reversed
| CybersourcePaymentStatus::Cancelled => common_enums::AttemptStatus::Voided,
CybersourcePaymentStatus::Failed
| CybersourcePaymentStatus::Declined
| CybersourcePaymentStatus::AuthorizedRiskDeclined
| CybersourcePaymentStatus::Rejected
| CybersourcePaymentStatus::InvalidRequest
| CybersourcePaymentStatus::ServerError => common_enums::AttemptStatus::Failure,
CybersourcePaymentStatus::PendingAuthentication => {
common_enums::AttemptStatus::AuthenticationPending
}
CybersourcePaymentStatus::PendingReview
| CybersourcePaymentStatus::StatusNotReceived
| CybersourcePaymentStatus::Challenge
| {
"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_4931700295577699981_24 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
| CybersourcePaymentStatus::Accepted
| CybersourcePaymentStatus::Pending
| CybersourcePaymentStatus::AuthorizedPendingReview => common_enums::AttemptStatus::Pending,
}
}
impl From<CybersourceIncrementalAuthorizationStatus> for AuthorizationStatus {
fn from(item: CybersourceIncrementalAuthorizationStatus) -> Self {
match item {
CybersourceIncrementalAuthorizationStatus::Authorized => Self::Success,
CybersourceIncrementalAuthorizationStatus::AuthorizedPendingReview => Self::Processing,
CybersourceIncrementalAuthorizationStatus::Declined => Self::Failure,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentsResponse {
id: String,
status: Option<CybersourcePaymentStatus>,
client_reference_information: Option<ClientReferenceInformation>,
processor_information: Option<ClientProcessorInformation>,
risk_information: Option<ClientRiskInformation>,
token_information: Option<CybersourceTokenInformation>,
error_information: Option<CybersourceErrorInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceErrorInformationResponse {
id: String,
error_information: CybersourceErrorInformation,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationResponse {
access_token: Secret<String>,
device_data_collection_url: String,
reference_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthSetupInfoResponse {
id: String,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: CybersourceConsumerAuthInformationResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceAuthSetupResponse {
ClientAuthSetupInfo(Box<ClientAuthSetupInfoResponse>),
ErrorInformation(Box<CybersourceErrorInformationResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentsIncrementalAuthorizationResponse {
status: CybersourceIncrementalAuthorizationStatus,
error_information: Option<CybersourceErrorInformation>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceInformation {
code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientProcessorInformation {
network_transaction_id: Option<String>,
avs: Option<Avs>,
card_verification: Option<CardVerification>,
merchant_advice: Option<MerchantAdvice>,
response_code: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAdvice {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardVerification {
result_code: Option<String>,
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Avs {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientRiskInformation {
rules: Option<Vec<ClientRiskInformationRules>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceTokenInformation {
payment_instrument: Option<CybersoucrePaymentInstrument>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CybersourceErrorInformation {
reason: Option<String>,
message: Option<String>,
details: Option<Vec<Details>>,
}
fn get_error_response_if_failure(
(info_response, status, http_code): (
&CybersourcePaymentsResponse,
common_enums::AttemptStatus,
u16,
),
) -> Option<ErrorResponse> {
if domain_types::utils::is_payment_failure(status) {
Some(get_error_response(
&info_response.error_information,
&info_response.processor_information,
| {
"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_4931700295577699981_25 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
&info_response.risk_information,
Some(status),
http_code,
info_response.id.clone(),
))
} else {
None
}
}
fn get_payment_response(
(info_response, status, http_code): (
&CybersourcePaymentsResponse,
common_enums::AttemptStatus,
u16,
),
) -> Result<PaymentsResponseData, Box<ErrorResponse>> {
let error_response = get_error_response_if_failure((info_response, status, http_code));
match error_response {
Some(error) => Err(Box::new(error)),
None => {
let incremental_authorization_allowed =
Some(status == common_enums::AttemptStatus::Authorized);
let mandate_reference =
info_response
.token_information
.clone()
.map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
});
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: None,
mandate_reference: mandate_reference.map(Box::new),
connector_metadata: None,
network_txn_id: info_response.processor_information.as_ref().and_then(
|processor_information| processor_information.network_transaction_id.clone(),
),
connector_response_reference_id: Some(
info_response
.client_reference_information
.clone()
.and_then(|client_reference_information| client_reference_information.code)
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed,
status_code: http_code,
})
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
ResponseRouterData<
CybersourcePaymentsResponse,
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
> for RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
CybersourcePaymentsResponse,
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
) -> Result<Self, Self::Error> {
let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
item.router_data.request.is_auto_capture()?,
);
let response =
get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err);
let connector_response = item
.response
.processor_information
.as_ref()
.map(AdditionalPaymentMethodConnectorResponse::from)
.map(domain_types::router_data::ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
resource_common_data: PaymentFlowData {
status,
connector_response,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<CybersourceAuthSetupResponse, Self>>
| {
"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_4931700295577699981_26 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
for RouterDataV2<F, PaymentFlowData, PaymentsPreAuthenticateData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourceAuthSetupResponse, Self>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self {
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::AuthenticationPending,
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::PreAuthenticateResponse {
redirection_data: Some(Box::new(RedirectForm::CybersourceAuthSetup {
access_token: info_response
.consumer_authentication_information
.access_token
.expose(),
ddc_url: info_response
.consumer_authentication_information
.device_data_collection_url,
reference_id: info_response
.consumer_authentication_information
.reference_id,
})),
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
),
status_code: item.http_code,
}),
..item.router_data
}),
CybersourceAuthSetupResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason;
Ok(Self {
response: Err(ErrorResponse {
code: error_message.clone().unwrap_or(NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::AuthenticationFailed,
..item.router_data.resource_common_data
},
..item.router_data
})
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationRequest {
return_url: String,
reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceAuthEnrollmentRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
payment_information: PaymentInformation<T>,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: CybersourceConsumerAuthInformationRequest,
order_information: OrderInformationWithBill,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
| {
"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_4931700295577699981_27 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
pub struct CybersourceRedirectionAuthResponse {
pub transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationValidateRequest {
authentication_transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceAuthValidateRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
payment_information: PaymentInformation<T>,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: CybersourceConsumerAuthInformationValidateRequest,
order_information: OrderInformation,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<
RouterDataV2<
PostAuthenticate,
PaymentFlowData,
PaymentsPostAuthenticateData<T>,
PaymentsResponseData,
>,
T,
>,
> for CybersourceAuthValidateRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CybersourceRouterData<
RouterDataV2<
PostAuthenticate,
PaymentFlowData,
PaymentsPostAuthenticateData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_cybersource_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => domain_types::utils::get_card_issuer(
&(format!("{:?}", ccard.card_number.0)),
)
.ok()
.map(card_issuer_to_string),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| 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(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
| {
"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_4931700295577699981_28 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let total_amount = item
.connector
.amount_converter
.convert(
item.router_data.request.amount,
item.router_data.request.currency.unwrap(),
)
.change_context(ConnectorError::AmountConversionFailed)?;
let amount_details = Amount {
total_amount,
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
let redirection_response: CybersourceRedirectionAuthResponse = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "request.redirect_response.payload",
})?
.expose()
.parse_value("CybersourceRedirectionAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let order_information = OrderInformation { amount_details };
Ok(Self {
payment_information,
client_reference_information,
consumer_authentication_information:
CybersourceConsumerAuthInformationValidateRequest {
authentication_transaction_id: redirection_response.transaction_id,
},
order_information,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceAuthenticateResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
ErrorInformation(Box<CybersourceErrorInformationResponse>),
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<CybersourceAuthenticateResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsAuthenticateData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourceAuthenticateResponse, Self>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourceAuthenticateResponse::ClientAuthCheckInfo(info_response) => {
let status = common_enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if domain_types::utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token
.clone(),
info_response
.consumer_authentication_information
.step_up_url
.clone(),
) {
(Some(token), Some(step_up_url)) => {
| {
"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_4931700295577699981_29 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
Some(RedirectForm::CybersourceConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::AuthenticateResponse {
redirection_data: redirection_data.map(Box::new),
connector_response_reference_id,
authentication_data: Some(
get_authentication_data_for_check_enrollment_response(
info_response.consumer_authentication_information,
),
),
status_code: item.http_code,
}),
..item.router_data
})
}
}
CybersourceAuthenticateResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
code: error_message.clone().unwrap_or(NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
});
Ok(Self {
response,
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::AuthenticationFailed,
..item.router_data.resource_common_data
},
..item.router_data
})
}
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<
RouterDataV2<
Authenticate,
PaymentFlowData,
PaymentsAuthenticateData<T>,
PaymentsResponseData,
>,
T,
>,
> for CybersourceAuthEnrollmentRequest<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CybersourceRouterData<
RouterDataV2<
Authenticate,
PaymentFlowData,
PaymentsAuthenticateData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
| {
"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_4931700295577699981_30 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_cybersource_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => domain_types::utils::get_card_issuer(
&(format!("{:?}", ccard.card_number.0)),
)
.ok()
.map(card_issuer_to_string),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| 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(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let total_amount = item
.connector
.amount_converter
.convert(
item.router_data.request.amount,
item.router_data.request.currency.unwrap(),
)
.change_context(ConnectorError::AmountConversionFailed)?;
let amount_details = Amount {
total_amount,
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
let param = redirect_response.params.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params",
},
)?;
let reference_id = param
.clone()
.peek()
.split('=')
.next_back()
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.reference_id",
})?
.to_string();
let email = item
.router_data
.resource_common_data
.get_billing_email()
.or(item
.router_data
.request
.email
.clone()
.ok_or_else(utils::missing_field_err("email")))?;
let bill_to = build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)?;
let order_information = OrderInformationWithBill {
amount_details,
bill_to: Some(bill_to),
};
Ok(Self {
| {
"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_4931700295577699981_31 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
payment_information,
client_reference_information,
consumer_authentication_information: CybersourceConsumerAuthInformationRequest {
return_url: item
.router_data
.request
.continue_redirection_url
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "continue_redirection_url",
})?
.to_string(),
reference_id,
},
order_information,
})
}
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<CybersourceAuthenticateResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsPostAuthenticateData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourceAuthenticateResponse, Self>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourceAuthenticateResponse::ClientAuthCheckInfo(info_response) => {
let status = common_enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if domain_types::utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::PostAuthenticateResponse {
authentication_data: Some(
get_authentication_data_for_validation_response(
info_response.consumer_authentication_information,
),
),
connector_response_reference_id,
status_code: item.http_code,
}),
..item.router_data
})
}
}
CybersourceAuthenticateResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
| {
"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_4931700295577699981_32 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
code: error_message.clone().unwrap_or(NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
});
Ok(Self {
response,
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::AuthenticationFailed,
..item.router_data.resource_common_data
},
..item.router_data
})
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceAuthEnrollmentStatus {
PendingAuthentication,
AuthenticationSuccessful,
AuthenticationFailed,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthValidateResponse {
/// This field is supported only on Asia, Middle East, and Africa Gateway
/// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions
/// This field is only applicable for Mastercard and Visa Transactions
pares_status: Option<CybersourceParesStatus>,
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
specification_version: Option<SemanticVersion>,
directory_server_transaction_id: Option<Secret<String>>,
acs_transaction_id: Option<String>,
three_d_s_server_transaction_id: Option<String>,
indicator: Option<String>,
ecommerce_indicator: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CybersourceThreeDSMetadata {
three_ds_data: CybersourceConsumerAuthValidateResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationEnrollmentResponse {
access_token: Option<Secret<String>>,
step_up_url: Option<String>,
authentication_transaction_id: Option<String>,
//Added to segregate the three_ds_data in a separate struct
#[serde(flatten)]
validate_response: CybersourceConsumerAuthValidateResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthCheckInfoResponse {
id: String,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: CybersourceConsumerAuthInformationEnrollmentResponse,
status: CybersourceAuthEnrollmentStatus,
error_information: Option<CybersourceErrorInformation>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourcePreProcessingResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
ErrorInformation(Box<CybersourceErrorInformationResponse>),
}
impl From<CybersourceAuthEnrollmentStatus> for common_enums::AttemptStatus {
fn from(item: CybersourceAuthEnrollmentStatus) -> Self {
match item {
CybersourceAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending,
CybersourceAuthEnrollmentStatus::AuthenticationSuccessful => {
Self::AuthenticationSuccessful
}
CybersourceAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed,
}
}
}
impl From<&ClientProcessorInformation> for AdditionalPaymentMethodConnectorResponse {
fn from(processor_information: &ClientProcessorInformation) -> Self {
let payment_checks = Some(
serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}),
);
Self::Card {
authentication_data: None,
payment_checks,
card_network: None,
domestic_network: None,
}
}
}
impl<F> TryFrom<ResponseRouterData<CybersourcePaymentsResponse, Self>>
| {
"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_4931700295577699981_33 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
for RouterDataV2<F, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourcePaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
true,
);
let response =
get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err);
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
impl<F> TryFrom<ResponseRouterData<CybersourcePaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentVoidData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourcePaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
false,
);
let response =
get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err);
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
impl<F> TryFrom<ResponseRouterData<CybersourcePaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourcePaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
true,
);
let response =
get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err);
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
// zero dollar response
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<CybersourcePaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, SetupMandateRequestData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourcePaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let mandate_reference =
item.response
.token_information
.clone()
.map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
});
let mut mandate_status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
false,
);
if matches!(mandate_status, common_enums::AttemptStatus::Authorized) {
//In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well.
mandate_status = common_enums::AttemptStatus::Charged
}
let error_response =
get_error_response_if_failure((&item.response, mandate_status, item.http_code));
| {
"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_4931700295577699981_34 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
let connector_response = item
.response
.processor_information
.as_ref()
.map(AdditionalPaymentMethodConnectorResponse::from)
.map(domain_types::router_data::ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
resource_common_data: PaymentFlowData {
status: mandate_status,
connector_response,
..item.router_data.resource_common_data
},
response: match error_response {
Some(error) => Err(error),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: mandate_reference.map(Box::new),
connector_metadata: None,
network_txn_id: item.response.processor_information.as_ref().and_then(
|processor_information| {
processor_information.network_transaction_id.clone()
},
),
connector_response_reference_id: Some(
item.response
.client_reference_information
.and_then(|client_reference_information| {
client_reference_information.code.clone()
})
.unwrap_or(item.response.id),
),
incremental_authorization_allowed: Some(
mandate_status == common_enums::AttemptStatus::Authorized,
),
status_code: item.http_code,
}),
},
..item.router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceTransactionResponse {
id: String,
application_information: ApplicationInformation,
processor_information: Option<ClientProcessorInformation>,
client_reference_information: Option<ClientReferenceInformation>,
error_information: Option<CybersourceErrorInformation>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplicationInformation {
status: Option<CybersourcePaymentStatus>,
}
impl<F> TryFrom<ResponseRouterData<CybersourceTransactionResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourceTransactionResponse, Self>,
) -> Result<Self, Self::Error> {
match item.response.application_information.status {
Some(status) => {
let status = map_cybersource_attempt_status(
status,
item.router_data.request.is_auto_capture()?,
);
let incremental_authorization_allowed =
Some(status == common_enums::AttemptStatus::Authorized);
let risk_info: Option<ClientRiskInformation> = None;
if domain_types::utils::is_payment_failure(status) {
Ok(Self {
response: Err(get_error_response(
&item.response.error_information,
&item.response.processor_information,
&risk_info,
Some(status),
item.http_code,
item.response.id.clone(),
)),
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::Failure,
..item.router_data.resource_common_data
},
..item.router_data
})
} else {
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
| {
"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_4931700295577699981_35 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.client_reference_information
.map(|cref| cref.code)
.unwrap_or(Some(item.response.id)),
incremental_authorization_allowed,
status_code: item.http_code,
}),
..item.router_data
})
}
}
None => Ok(Self {
resource_common_data: PaymentFlowData {
status: item.router_data.resource_common_data.status,
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
..item.router_data
}),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRefundRequest {
order_information: OrderInformation,
client_reference_information: ClientReferenceInformation,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>,
> for CybersourceRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CybersourceRouterData<
RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let total_amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_refund_amount.to_owned(),
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
total_amount,
currency: item.router_data.request.currency,
},
},
client_reference_information: ClientReferenceInformation {
code: Some(item.router_data.request.refund_id.clone()),
},
})
}
}
impl From<CybersourceRefundStatus> for common_enums::RefundStatus {
fn from(item: CybersourceRefundStatus) -> Self {
match item {
CybersourceRefundStatus::Succeeded | CybersourceRefundStatus::Transmitted => {
Self::Success
}
CybersourceRefundStatus::Cancelled
| CybersourceRefundStatus::Failed
| CybersourceRefundStatus::Voided => Self::Failure,
CybersourceRefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceRefundStatus {
Succeeded,
Transmitted,
Failed,
Pending,
Voided,
Cancelled,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRefundResponse {
id: String,
status: CybersourceRefundStatus,
error_information: Option<CybersourceErrorInformation>,
}
| {
"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_4931700295577699981_36 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
impl<F> TryFrom<ResponseRouterData<CybersourceRefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourceRefundResponse, Self>,
) -> Result<Self, Self::Error> {
let refund_status = common_enums::RefundStatus::from(item.response.status.clone());
let response = if utils::is_refund_failure(refund_status) {
Err(get_error_response(
&item.response.error_information,
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: common_enums::RefundStatus::from(item.response.status),
status_code: item.http_code,
})
};
Ok(Self {
response,
..item.router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RsyncApplicationInformation {
status: Option<CybersourceRefundStatus>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRsyncResponse {
id: String,
application_information: Option<RsyncApplicationInformation>,
error_information: Option<CybersourceErrorInformation>,
}
impl<F> TryFrom<ResponseRouterData<CybersourceRsyncResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CybersourceRsyncResponse, Self>,
) -> Result<Self, Self::Error> {
let response = match item
.response
.application_information
.and_then(|application_information| application_information.status)
{
Some(status) => {
let refund_status = common_enums::RefundStatus::from(status.clone());
if utils::is_refund_failure(refund_status) {
if status == CybersourceRefundStatus::Voided {
Err(get_error_response(
&Some(CybersourceErrorInformation {
message: Some(REFUND_VOIDED.to_string()),
reason: Some(REFUND_VOIDED.to_string()),
details: None,
}),
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
} else {
Err(get_error_response(
&item.response.error_information,
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
}
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
status_code: item.http_code,
})
}
}
None => Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status: match item.router_data.response {
Ok(response) => response.refund_status,
Err(_) => common_enums::RefundStatus::Pending,
},
status_code: item.http_code,
}),
};
Ok(Self {
response,
..item.router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceStandardErrorResponse {
pub error_information: Option<ErrorInformation>,
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<String>,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
| {
"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_4931700295577699981_37 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
pub struct CybersourceNotAvailableErrorResponse {
pub errors: Vec<CybersourceNotAvailableErrorObject>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceNotAvailableErrorObject {
#[serde(rename = "type")]
pub error_type: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceServerErrorResponse {
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<Reason>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
SystemError,
ServerTimeout,
ServiceTimeout,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CybersourceAuthenticationErrorResponse {
pub response: AuthenticationErrorInformation,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceErrorResponse {
AuthenticationError(Box<CybersourceAuthenticationErrorResponse>),
//If the request resource is not available/exists in cybersource
NotAvailableError(Box<CybersourceNotAvailableErrorResponse>),
StandardError(Box<CybersourceStandardErrorResponse>),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Details {
pub field: String,
pub reason: String,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorInformation {
pub message: String,
pub reason: String,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
pub fn get_error_response(
error_data: &Option<CybersourceErrorInformation>,
processor_information: &Option<ClientProcessorInformation>,
risk_information: &Option<ClientRiskInformation>,
attempt_status: Option<common_enums::AttemptStatus>,
status_code: u16,
transaction_id: String,
) -> ErrorResponse {
let avs_message = risk_information
.clone()
.map(|client_risk_information| {
client_risk_information.rules.map(|rules| {
rules
.iter()
.map(|risk_info| {
risk_info.name.clone().map_or("".to_string(), |name| {
format!(" , {}", name.clone().expose())
})
})
.collect::<Vec<String>>()
.join("")
})
})
.unwrap_or(Some("".to_string()));
let detailed_error_info = error_data.as_ref().and_then(|error_data| {
error_data.details.as_ref().map(|details| {
details
.iter()
.map(|detail| format!("{} : {}", detail.field, detail.reason))
.collect::<Vec<_>>()
.join(", ")
})
});
let network_decline_code = processor_information
.as_ref()
.and_then(|info| info.response_code.clone());
let network_advice_code = processor_information.as_ref().and_then(|info| {
info.merchant_advice
.as_ref()
.and_then(|merchant_advice| merchant_advice.code_raw.clone())
});
let reason = get_error_reason(
error_data
.as_ref()
.and_then(|error_info| error_info.message.clone()),
detailed_error_info,
avs_message,
);
let error_message = error_data
.as_ref()
.and_then(|error_info| error_info.reason.clone());
ErrorResponse {
code: error_message
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason,
status_code,
attempt_status,
connector_transaction_id: Some(transaction_id),
network_advice_code,
network_decline_code,
network_error_message: None,
}
}
pub fn get_error_reason(
error_info: Option<String>,
detailed_error_info: Option<String>,
avs_error_info: Option<String>,
) -> Option<String> {
match (error_info, detailed_error_info, avs_error_info) {
(Some(message), Some(details), Some(avs_message)) => Some(format!(
"{message}, detailed_error_information: {details}, avs_message: {avs_message}",
)),
| {
"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_4931700295577699981_38 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
(Some(message), Some(details), None) => {
Some(format!("{message}, detailed_error_information: {details}"))
}
(Some(message), None, Some(avs_message)) => {
Some(format!("{message}, avs_message: {avs_message}"))
}
(None, Some(details), Some(avs_message)) => {
Some(format!("{details}, avs_message: {avs_message}"))
}
(Some(message), None, None) => Some(message),
(None, Some(details), None) => Some(details),
(None, None, Some(avs_message)) => Some(avs_message),
(None, None, None) => None,
}
}
fn get_cybersource_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
common_enums::CardNetwork::Mastercard => Some("002"),
common_enums::CardNetwork::AmericanExpress => Some("003"),
common_enums::CardNetwork::JCB => Some("007"),
common_enums::CardNetwork::DinersClub => Some("005"),
common_enums::CardNetwork::Discover => Some("004"),
common_enums::CardNetwork::CartesBancaires => Some("036"),
common_enums::CardNetwork::UnionPay => Some("062"),
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
common_enums::CardNetwork::Maestro => Some("042"),
common_enums::CardNetwork::Interac
| common_enums::CardNetwork::RuPay
| common_enums::CardNetwork::Star
| common_enums::CardNetwork::Accel
| common_enums::CardNetwork::Pulse
| common_enums::CardNetwork::Nyce => None,
}
}
pub trait RemoveNewLine {
fn remove_new_line(&self) -> Self;
}
impl RemoveNewLine for Option<Secret<String>> {
fn remove_new_line(&self) -> Self {
self.clone().map(|masked_value| {
let new_string = masked_value.expose().replace("\n", " ");
Secret::new(new_string)
})
}
}
impl RemoveNewLine for Option<String> {
fn remove_new_line(&self) -> Self {
self.clone().map(|value| value.replace("\n", " "))
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRepeatPaymentRequest {
processing_information: ProcessingInformation,
payment_information: RepeatPaymentInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
consumer_authentication_information: Option<CybersourceConsumerAuthInformation>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum RepeatPaymentInformation {
MandatePayment(Box<MandatePaymentInformation>),
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CybersourceRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
> for CybersourceRepeatPaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CybersourceRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let processing_information = ProcessingInformation::try_from((&item, None, None))?;
// Extract connector mandate ID from mandate_reference
let connector_mandate_id = match &item.router_data.request.mandate_reference {
MandateReferenceId::ConnectorMandateId(connector_mandate_data) => {
connector_mandate_data
.get_connector_mandate_id()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
})?
}
MandateReferenceId::NetworkMandateId(_)
| MandateReferenceId::NetworkTokenWithNTI(_) => {
return Err(error_stack::report!(errors::ConnectorError::NotSupported {
| {
"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_4931700295577699981_39 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
message: "Network mandate ID not supported for Cybersource repeat payments"
.to_string(),
connector: "cybersource",
}));
}
};
let payment_instrument = CybersoucrePaymentInstrument {
id: Secret::new(connector_mandate_id),
};
let mandate_card_information = match item.router_data.request.payment_method_type {
Some(common_enums::PaymentMethodType::Credit)
| Some(common_enums::PaymentMethodType::Debit) => Some(MandateCard {
type_selection_indicator: Some("1".to_owned()),
}),
_ => None,
};
let tokenized_card = match item.router_data.request.payment_method_type {
Some(common_enums::PaymentMethodType::GooglePay)
| Some(common_enums::PaymentMethodType::ApplePay)
| Some(common_enums::PaymentMethodType::SamsungPay) => {
Some(MandatePaymentTokenizedCard {
transaction_type: TransactionType::StoredCredentials,
})
}
_ => None,
};
let bill_to = item
.router_data
.resource_common_data
.get_optional_billing_email()
.and_then(|email| {
build_bill_to(
item.router_data.resource_common_data.get_optional_billing(),
email,
)
.ok()
});
let order_information = OrderInformationWithBill::try_from((&item, bill_to))?;
let payment_information =
RepeatPaymentInformation::MandatePayment(Box::new(MandatePaymentInformation {
payment_instrument,
tokenized_card,
card: mandate_card_information,
}));
let client_reference_information = ClientReferenceInformation::from(&item);
let merchant_defined_information = item
.router_data
.request
.metadata
.as_ref()
.map(|metadata_map| {
serde_json::to_value(metadata_map)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.map(convert_metadata_to_merchant_defined_info)
})
.transpose()?;
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
Option<BillTo>,
)> for OrderInformationWithBill
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, bill_to): (
&CybersourceRouterData<
RouterDataV2<
RepeatPayment,
PaymentFlowData,
RepeatPaymentData,
PaymentsResponseData,
>,
T,
>,
Option<BillTo>,
),
) -> Result<Self, Self::Error> {
let total_amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount.to_owned(),
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
Ok(Self {
amount_details: Amount {
total_amount,
currency: item.router_data.request.currency,
},
bill_to,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&CybersourceRouterData<
RouterDataV2<RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData>,
T,
>,
Option<PaymentSolution>,
| {
"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_4931700295577699981_40 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&CybersourceRouterData<
RouterDataV2<
RepeatPayment,
PaymentFlowData,
RepeatPaymentData,
PaymentsResponseData,
>,
T,
>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let commerce_indicator = solution
.as_ref()
.map(|pm_solution| match pm_solution {
PaymentSolution::ApplePay | PaymentSolution::SamsungPay => network
.as_ref()
.map(|card_network| match card_network.to_lowercase().as_str() {
"mastercard" => "spa",
_ => "internet",
})
.unwrap_or("internet"),
PaymentSolution::GooglePay => "internet",
})
.unwrap_or("internet")
.to_string();
let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(
&item.router_data.request.merchant_account_metadata,
)?;
// Extract connector mandate ID from mandate_reference
let connector_mandate_id = match &item.router_data.request.mandate_reference {
MandateReferenceId::ConnectorMandateId(connector_mandate_data) => {
connector_mandate_data
.get_connector_mandate_id()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
})?
}
MandateReferenceId::NetworkMandateId(_)
| MandateReferenceId::NetworkTokenWithNTI(_) => {
return Err(error_stack::report!(errors::ConnectorError::NotSupported {
message: "Network mandate ID not supported for Cybersource repeat payments"
.to_string(),
connector: "cybersource",
}));
}
};
let (action_list, action_token_types, authorization_options) = if !connector_mandate_id
.is_empty()
{
match item.router_data.request.mandate_reference.clone() {
MandateReferenceId::ConnectorMandateId(_) => {
let original_amount = item
.router_data
.request
.recurring_mandate_payment_data
.as_ref()
.and_then(|recurring_mandate_payment_data| {
recurring_mandate_payment_data.original_payment_authorized_amount
});
let original_currency = item
.router_data
.request
.recurring_mandate_payment_data
.as_ref()
.and_then(|recurring_mandate_payment_data| {
recurring_mandate_payment_data.original_payment_authorized_currency
});
let original_authorized_amount = match original_amount.zip(original_currency) {
Some((original_amount, original_currency)) => {
Some(domain_types::utils::get_amount_as_string(
&common_enums::CurrencyUnit::Base,
original_amount,
original_currency,
)?)
}
None => None,
};
(
None,
None,
Some(CybersourceAuthorizationOptions {
initiator: None,
merchant_initiated_transaction: Some(MerchantInitiatedTransaction {
reason: None,
original_authorized_amount,
previous_transaction_id: None,
}),
| {
"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_4931700295577699981_41 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cybersource/transformers.rs
ignore_avs_result: connector_merchant_config.disable_avs,
ignore_cv_result: connector_merchant_config.disable_cvn,
}),
)
}
MandateReferenceId::NetworkMandateId(_)
| MandateReferenceId::NetworkTokenWithNTI(_) => {
return Err(error_stack::report!(errors::ConnectorError::NotSupported {
message: "Network mandate ID not supported for Cybersource repeat payments"
.to_string(),
connector: "cybersource",
}));
}
}
} else {
(
None,
None,
Some(CybersourceAuthorizationOptions {
initiator: None,
merchant_initiated_transaction: None,
ignore_avs_result: connector_merchant_config.disable_avs,
ignore_cv_result: connector_merchant_config.disable_cvn,
}),
)
};
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(common_enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
action_list,
action_token_types,
authorization_options,
capture_options: None,
commerce_indicator,
})
}
}
| {
"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_-2461103467231849077_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cryptopay/transformers.rs
use domain_types::{
connector_flow::Authorize,
connector_types::{
PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData, PaymentsSyncData, ResponseId,
WebhookDetailsResponse,
},
payment_method_data::PaymentMethodDataTypes,
};
use crate::connectors::cryptopay::{CryptopayAmountConvertor, CryptopayRouterData};
use crate::types::ResponseRouterData;
use common_utils::{pii, types::StringMajorUnit};
use url::Url;
use domain_types::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
utils::{get_unimplemented_payment_method_error_message, is_payment_failure},
};
use domain_types::errors::{self, ConnectorError};
use common_utils::consts;
use serde::{Deserialize, Serialize};
use hyperswitch_masking::Secret;
#[derive(Default, Debug, Serialize)]
pub struct CryptopayPaymentsRequest {
price_amount: StringMajorUnit,
price_currency: common_enums::Currency,
pay_currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
network: Option<String>,
success_redirect_url: Option<String>,
unsuccess_redirect_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<pii::SecretSerdeValue>,
custom_id: String,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CryptopayRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for CryptopayPaymentsRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: CryptopayRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let cryptopay_request = match item.router_data.request.payment_method_data {
PaymentMethodData::Crypto(ref cryptodata) => {
let pay_currency = cryptodata.get_pay_currency()?;
let amount = CryptopayAmountConvertor::convert(
item.router_data.request.minor_amount,
item.router_data.request.currency,
)?;
Ok(Self {
price_amount: amount,
price_currency: item.router_data.request.currency,
pay_currency,
network: cryptodata.network.to_owned(),
success_redirect_url: item.router_data.request.router_return_url.clone(),
unsuccess_redirect_url: item.router_data.request.router_return_url.clone(),
//Cryptopay only accepts metadata as Object. If any other type, payment will fail with error.
metadata: item.router_data.request.get_metadata_as_object(),
custom_id: item
.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
})
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
| {
"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_-2461103467231849077_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cryptopay/transformers.rs
get_unimplemented_payment_method_error_message("CryptoPay"),
))
}
}?;
Ok(cryptopay_request)
}
}
// Auth Struct
pub struct CryptopayAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CryptopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CryptopayPaymentStatus {
New,
Completed,
Unresolved,
Refunded,
Cancelled,
}
impl From<CryptopayPaymentStatus> for common_enums::AttemptStatus {
fn from(item: CryptopayPaymentStatus) -> Self {
match item {
CryptopayPaymentStatus::New => Self::AuthenticationPending,
CryptopayPaymentStatus::Completed => Self::Charged,
CryptopayPaymentStatus::Cancelled => Self::Failure,
CryptopayPaymentStatus::Unresolved | CryptopayPaymentStatus::Refunded => {
Self::Unresolved
} //mapped refunded to Unresolved because refund api is not available, also merchant has done the action on the connector dashboard.
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayPaymentsResponse {
pub data: CryptopayPaymentResponseData,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<CryptopayPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CryptopayPaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response: cryptopay_response,
router_data,
http_code,
} = item;
let status = common_enums::AttemptStatus::from(cryptopay_response.data.status.clone());
let response = if is_payment_failure(status) {
let payment_response = &cryptopay_response.data;
Err(ErrorResponse {
code: payment_response
.name
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: payment_response
.status_context
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: payment_response.status_context.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
let redirection_data = cryptopay_response
.data
.hosted_page_url
.map(|x| RedirectForm::from((x, common_utils::request::Method::Get)));
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(cryptopay_response.data.id.clone()),
redirection_data: redirection_data.map(Box::new),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: cryptopay_response
.data
.custom_id
.or(Some(cryptopay_response.data.id)),
incremental_authorization_allowed: None,
status_code: http_code,
})
};
let amount_captured_in_minor_units = match cryptopay_response.data.price_amount {
| {
"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_-2461103467231849077_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cryptopay/transformers.rs
Some(ref amount) => Some(CryptopayAmountConvertor::convert_back(
amount.clone(),
router_data.request.currency,
)?),
None => None,
};
match (amount_captured_in_minor_units, status) {
(Some(minor_amount), common_enums::AttemptStatus::Charged) => {
let amount_captured = Some(minor_amount.get_amount_as_i64());
Ok(Self {
resource_common_data: PaymentFlowData {
status,
amount_captured,
minor_amount_captured: amount_captured_in_minor_units,
..router_data.resource_common_data
},
response,
..router_data
})
}
_ => Ok(Self {
resource_common_data: PaymentFlowData {
status,
..router_data.resource_common_data
},
response,
..router_data
}),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CryptopayErrorData {
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CryptopayErrorResponse {
pub error: CryptopayErrorData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayPaymentResponseData {
pub id: String,
pub custom_id: Option<String>,
pub customer_id: Option<String>,
pub status: CryptopayPaymentStatus,
pub status_context: Option<String>,
pub address: Option<Secret<String>>,
pub network: Option<String>,
pub uri: Option<String>,
pub price_amount: Option<StringMajorUnit>,
pub price_currency: Option<common_enums::Currency>,
pub pay_amount: Option<StringMajorUnit>,
pub pay_currency: Option<String>,
pub fee: Option<String>,
pub fee_currency: Option<String>,
pub paid_amount: Option<String>,
pub name: Option<String>,
pub description: Option<String>,
pub success_redirect_url: Option<String>,
pub unsuccess_redirect_url: Option<String>,
pub hosted_page_url: Option<Url>,
pub created_at: Option<String>,
pub expires_at: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayWebhookDetails {
#[serde(rename = "type")]
pub service_type: String,
pub event: WebhookEvent,
pub data: CryptopayPaymentResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookEvent {
TransactionCreated,
TransactionConfirmed,
StatusChanged,
}
impl<F> TryFrom<ResponseRouterData<CryptopayPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CryptopayPaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response: cryptopay_response,
router_data,
http_code,
} = item;
let status = common_enums::AttemptStatus::from(cryptopay_response.data.status.clone());
let response = if is_payment_failure(status) {
let payment_response = &cryptopay_response.data;
Err(ErrorResponse {
code: payment_response
.name
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: payment_response
.status_context
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: payment_response.status_context.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
let redirection_data = cryptopay_response
.data
.hosted_page_url
.map(|x| RedirectForm::from((x, common_utils::request::Method::Get)));
| {
"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_-2461103467231849077_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cryptopay/transformers.rs
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(cryptopay_response.data.id.clone()),
redirection_data: redirection_data.map(Box::new),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: cryptopay_response
.data
.custom_id
.or(Some(cryptopay_response.data.id)),
incremental_authorization_allowed: None,
status_code: http_code,
})
};
let amount_captured_in_minor_units = match cryptopay_response.data.price_amount {
Some(ref amount) => Some(CryptopayAmountConvertor::convert_back(
amount.clone(),
router_data.request.currency,
)?),
None => None,
};
match (amount_captured_in_minor_units, status) {
(Some(minor_amount), common_enums::AttemptStatus::Charged) => {
let amount_captured = Some(minor_amount.get_amount_as_i64());
Ok(Self {
resource_common_data: PaymentFlowData {
status,
amount_captured,
minor_amount_captured: amount_captured_in_minor_units,
..router_data.resource_common_data
},
response,
..router_data
})
}
_ => Ok(Self {
resource_common_data: PaymentFlowData {
status,
..router_data.resource_common_data
},
response,
..router_data
}),
}
}
}
impl TryFrom<CryptopayWebhookDetails> for WebhookDetailsResponse {
type Error = error_stack::Report<ConnectorError>;
fn try_from(notif: CryptopayWebhookDetails) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(notif.data.status.clone());
if is_payment_failure(status) {
Ok(Self {
error_code: Some(
notif
.data
.name
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
),
error_message: Some(
notif
.data
.status_context
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
),
error_reason: notif.data.status_context.clone(),
status_code: 200,
status: common_enums::AttemptStatus::Unknown,
resource_id: Some(ResponseId::ConnectorTransactionId(notif.data.id.clone())),
connector_response_reference_id: None,
mandate_reference: None,
raw_connector_response: None,
response_headers: None,
transformation_status: common_enums::WebhookTransformationStatus::Complete,
minor_amount_captured: None,
amount_captured: None,
network_txn_id: None,
})
} else {
let amount_captured_in_minor_units =
match (notif.data.price_amount, notif.data.price_currency) {
(Some(amount), Some(currency)) => {
Some(CryptopayAmountConvertor::convert_back(amount, currency)?)
}
_ => None,
};
match (amount_captured_in_minor_units, status) {
(Some(minor_amount), common_enums::AttemptStatus::Charged) => {
let amount_captured = Some(minor_amount.get_amount_as_i64());
Ok(Self {
amount_captured,
minor_amount_captured: amount_captured_in_minor_units,
status,
resource_id: Some(ResponseId::ConnectorTransactionId(
notif.data.id.clone(),
)),
error_reason: None,
| {
"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_-2461103467231849077_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cryptopay/transformers.rs
mandate_reference: None,
status_code: 200,
connector_response_reference_id: notif
.data
.custom_id
.or(Some(notif.data.id)),
error_code: None,
error_message: None,
raw_connector_response: None,
response_headers: None,
network_txn_id: None,
transformation_status: common_enums::WebhookTransformationStatus::Complete,
})
}
_ => Ok(Self {
status,
resource_id: Some(ResponseId::ConnectorTransactionId(notif.data.id.clone())),
mandate_reference: None,
status_code: 200,
connector_response_reference_id: notif.data.custom_id.or(Some(notif.data.id)),
error_code: None,
error_message: None,
raw_connector_response: None,
response_headers: None,
minor_amount_captured: None,
amount_captured: None,
error_reason: None,
network_txn_id: None,
transformation_status: common_enums::WebhookTransformationStatus::Complete,
}),
}
}
}
}
| {
"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_-87029215718539496_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpayv2/test.rs
//! Tests for RazorpayV2 connector
#[cfg(test)]
mod tests {
// use super::super::transformers::*;
#[test]
fn test_upi_flow_determination() {
// Add tests for UPI flow determination logic
// TODO: Implement comprehensive tests
}
#[test]
fn test_create_order_request_building() {
// Add tests for create order request building
// TODO: Implement comprehensive tests
}
#[test]
fn test_payments_request_building() {
// Add tests for payments request building
// TODO: Implement comprehensive tests
}
}
| {
"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_-4688241219082903168_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpayv2/transformers.rs
//! RazorpayV2 transformers for converting between domain types and RazorpayV2 API types
use std::str::FromStr;
use base64::{engine::general_purpose::STANDARD, Engine};
use common_enums::{AttemptStatus, RefundStatus};
use common_utils::{consts, pii::Email, types::MinorUnit};
use domain_types::{
connector_flow::{Authorize, PSync, RSync, Refund},
connector_types::{
PaymentCreateOrderData, PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData,
PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData, RefundsResponseData,
ResponseId,
},
errors,
payment_address::Address,
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, UpiData},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
};
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::connectors::razorpay::transformers::ForeignTryFrom;
// ============ Authentication Types ============
#[derive(Debug)]
pub enum RazorpayV2AuthType {
AuthToken(Secret<String>),
ApiKeySecret {
api_key: Secret<String>,
api_secret: Secret<String>,
},
}
impl RazorpayV2AuthType {
pub fn generate_authorization_header(&self) -> String {
match self {
RazorpayV2AuthType::AuthToken(token) => format!("Bearer {}", token.peek()),
RazorpayV2AuthType::ApiKeySecret {
api_key,
api_secret,
} => {
let credentials = format!("{}:{}", api_key.peek(), api_secret.peek());
let encoded = STANDARD.encode(credentials);
format!("Basic {encoded}")
}
}
}
}
impl TryFrom<&ConnectorAuthType> for RazorpayV2AuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self::AuthToken(api_key.to_owned())),
ConnectorAuthType::SignatureKey {
api_key,
api_secret,
..
} => Ok(Self::ApiKeySecret {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::ApiKeySecret {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// ============ Router Data Wrapper ============
pub struct RazorpayV2RouterData<
T,
U: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub amount: MinorUnit,
pub order_id: Option<String>,
pub router_data: T,
pub billing_address: Option<Address>,
#[allow(dead_code)]
phantom: Option<std::marker::PhantomData<U>>,
}
impl<
T,
U: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<(MinorUnit, T, Option<String>, Option<Address>)> for RazorpayV2RouterData<T, U>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, item, order_id, billing_address): (MinorUnit, T, Option<String>, Option<Address>),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
order_id,
router_data: item,
billing_address,
phantom: None,
})
}
}
// Keep backward compatibility for existing usage
impl<
T,
U: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<(MinorUnit, T, Option<String>)> for RazorpayV2RouterData<T, U>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, item, order_id): (MinorUnit, T, Option<String>),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
order_id,
router_data: item,
| {
"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_-4688241219082903168_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpayv2/transformers.rs
billing_address: None,
phantom: None,
})
}
}
// ============ Create Order Types ============
#[derive(Debug, Serialize)]
pub struct RazorpayV2CreateOrderRequest {
pub amount: MinorUnit,
pub currency: String,
pub receipt: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_capture: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub notes: Option<RazorpayV2Notes>,
}
pub type RazorpayV2Notes = serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayV2CreateOrderResponse {
pub id: String,
pub entity: String,
pub amount: MinorUnit,
pub amount_paid: MinorUnit,
pub amount_due: MinorUnit,
pub currency: String,
pub receipt: String,
pub status: String,
pub attempts: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub notes: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub offer_id: Option<String>,
pub created_at: i64,
}
// ============ Payment Authorization Types ============
#[derive(Debug, Serialize)]
pub struct RazorpayV2PaymentsRequest {
pub amount: MinorUnit,
pub currency: String,
pub order_id: String,
pub email: Email,
pub contact: Secret<String>,
pub method: String,
pub description: Option<String>,
pub notes: Option<RazorpayV2Notes>,
pub callback_url: String,
pub upi: Option<RazorpayV2UpiDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub save: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recurring: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum UpiFlow {
Collect,
Intent,
}
#[derive(Debug, Serialize)]
pub struct RazorpayV2UpiDetails {
#[serde(skip_serializing_if = "Option::is_none")]
pub flow: Option<UpiFlow>,
#[serde(skip_serializing_if = "Option::is_none")]
pub vpa: Option<Secret<String>>, // Only for collect flow
#[serde(skip_serializing_if = "Option::is_none")]
pub expiry_time: Option<i32>, // In minutes (5 to 5760)
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub upi_type: Option<String>, // "recurring" for mandates
#[serde(skip_serializing_if = "Option::is_none")]
pub end_date: Option<i64>, // For recurring payments
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayV2PaymentsResponse {
pub id: String,
pub entity: String,
pub amount: i64,
pub currency: String,
pub status: RazorpayStatus,
pub order_id: Option<String>,
pub invoice_id: Option<String>,
pub international: Option<bool>,
pub method: String,
pub amount_refunded: Option<i64>,
pub refund_status: Option<String>,
pub captured: Option<bool>,
pub description: Option<String>,
pub card_id: Option<String>,
pub bank: Option<String>,
pub wallet: Option<String>,
pub vpa: Option<Secret<String>>,
pub email: Email,
pub contact: Secret<String>,
pub notes: Option<Value>,
pub fee: Option<i64>,
pub tax: Option<i64>,
pub error_code: Option<String>,
pub error_description: Option<String>,
pub error_reason: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RazorpayStatus {
Created,
Authorized,
Captured,
Refunded,
Failed,
}
fn get_psync_razorpay_payment_status(razorpay_status: RazorpayStatus) -> AttemptStatus {
match razorpay_status {
RazorpayStatus::Created => AttemptStatus::Pending,
RazorpayStatus::Authorized => AttemptStatus::Authorized,
RazorpayStatus::Captured => AttemptStatus::Charged,
RazorpayStatus::Refunded => AttemptStatus::AutoRefunded,
RazorpayStatus::Failed => AttemptStatus::Failure,
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayV2OrderPaymentsCollectionResponse {
pub entity: String,
pub count: i32,
pub items: Vec<RazorpayV2PaymentsResponse>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RazorpayV2SyncResponse {
PaymentResponse(Box<RazorpayV2PaymentsResponse>),
OrderPaymentsCollection(RazorpayV2OrderPaymentsCollectionResponse),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
| {
"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_-4688241219082903168_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpayv2/transformers.rs
pub enum RazorpayV2UpiPaymentsResponse {
SuccessIntent {
razorpay_payment_id: String,
link: String,
},
SuccessCollect {
razorpay_payment_id: String,
},
Error {
error: RazorpayV2ErrorResponse,
},
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RazorpayV2ErrorResponse {
StandardError { error: RazorpayV2ErrorDetails },
SimpleError { message: String },
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayV2ErrorDetails {
pub code: String,
pub description: String,
pub source: Option<String>,
pub step: Option<String>,
pub reason: Option<String>,
pub metadata: Option<serde_json::Value>,
pub field: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayV2UpiResponseDetails {
pub flow: Option<String>,
pub vpa: Option<Secret<String>>,
pub expiry_time: Option<i32>,
}
// ============ Error Types ============
// Error response structure is already defined above in the enum
// ============ Request Transformations ============
impl<
U: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<&RazorpayV2RouterData<&PaymentCreateOrderData, U>> for RazorpayV2CreateOrderRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayV2RouterData<&PaymentCreateOrderData, U>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
currency: item.router_data.currency.to_string(),
receipt: item
.order_id
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_request_reference_id",
})?
.clone(),
payment_capture: Some(true),
notes: item.router_data.metadata.clone(),
})
}
}
impl<
U: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
&RazorpayV2RouterData<
&RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<U>,
PaymentsResponseData,
>,
U,
>,
> for RazorpayV2PaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayV2RouterData<
&RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<U>,
PaymentsResponseData,
>,
U,
>,
) -> Result<Self, Self::Error> {
// Determine UPI flow based on payment method data
let (upi_flow, vpa) = match &item.router_data.request.payment_method_data {
PaymentMethodData::Upi(upi_data) => match upi_data {
UpiData::UpiCollect(collect_data) => {
let vpa_string = collect_data
.vpa_id
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "vpa_id",
})?
.peek()
.to_string();
(Some(UpiFlow::Collect), Some(vpa_string))
}
UpiData::UpiIntent(_) | UpiData::UpiQr(_) => (Some(UpiFlow::Intent), None),
// UpiData::UpiQr(_) => {
// return Err(errors::ConnectorError::NotImplemented("UPI QR flow not supported by RazorpayV2".to_string()).into());
// }
},
_ => (None, None),
};
// Build UPI details if this is a UPI payment
let upi_details = if upi_flow.is_some() {
Some(RazorpayV2UpiDetails {
flow: upi_flow,
vpa: vpa.map(Secret::new),
expiry_time: Some(15), // 15 minutes default
upi_type: None,
end_date: None,
})
} else {
None
};
let order_id =
item.order_id
.as_ref()
| {
"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_-4688241219082903168_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpayv2/transformers.rs
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "order_id",
})?;
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency.to_string(),
order_id: order_id.to_string(),
email: item
.router_data
.resource_common_data
.get_billing_email()
.unwrap_or_else(|_| Email::from_str("customer@example.com").unwrap()),
contact: Secret::new(
item.router_data
.resource_common_data
.get_billing_phone_number()
.map(|phone| phone.expose())
.unwrap_or_else(|_| "9999999999".to_string()),
),
method: "upi".to_string(),
description: Some("Payment via RazorpayV2".to_string()),
notes: item.router_data.request.metadata.clone(),
callback_url: item.router_data.request.get_router_return_url()?,
upi: upi_details,
customer_id: None,
save: Some(false),
recurring: None,
})
}
}
// ============ Refund Types ============
#[derive(Debug, Serialize)]
pub struct RazorpayV2RefundRequest {
pub amount: i64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayV2RefundResponse {
pub id: String,
pub entity: String,
pub amount: i64,
pub currency: String,
pub payment_id: String,
pub status: String,
pub speed_requested: Option<String>,
pub speed_processed: Option<String>,
pub receipt: Option<String>,
pub created_at: i64,
}
impl<
U: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<&RazorpayV2RouterData<&RefundsData, U>> for RazorpayV2RefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RazorpayV2RouterData<&RefundsData, U>) -> Result<Self, Self::Error> {
let amount_in_minor_units = item.amount.get_amount_as_i64();
Ok(Self {
amount: amount_in_minor_units,
})
}
}
// ============ Response Transformations ============
impl
ForeignTryFrom<(
RazorpayV2RefundResponse,
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
u16,
Vec<u8>, // raw_response
)> for RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(response, data, _status_code, _raw_response): (
RazorpayV2RefundResponse,
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
u16,
Vec<u8>,
),
) -> Result<Self, Self::Error> {
// Map Razorpay refund status to internal status
let status = match response.status.as_str() {
"processed" => RefundStatus::Success,
"pending" | "created" => RefundStatus::Pending,
"failed" => RefundStatus::Failure,
_ => RefundStatus::Pending,
};
let refunds_response_data = RefundsResponseData {
connector_refund_id: response.id,
refund_status: status,
status_code: _status_code,
};
Ok(RouterDataV2 {
response: Ok(refunds_response_data),
resource_common_data: RefundFlowData {
status,
..data.resource_common_data.clone()
},
..data
})
}
}
impl
ForeignTryFrom<(
RazorpayV2RefundResponse,
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
u16,
Vec<u8>, // raw_response
)> for RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(response, data, _status_code, _raw_response): (
RazorpayV2RefundResponse,
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
u16,
Vec<u8>,
),
) -> Result<Self, Self::Error> {
| {
"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_-4688241219082903168_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpayv2/transformers.rs
// Map Razorpay refund status to internal status
let status = match response.status.as_str() {
"processed" => RefundStatus::Success,
"pending" | "created" => RefundStatus::Pending,
"failed" => RefundStatus::Failure,
_ => RefundStatus::Pending,
};
let refunds_response_data = RefundsResponseData {
connector_refund_id: response.id,
refund_status: status,
status_code: _status_code,
};
Ok(RouterDataV2 {
response: Ok(refunds_response_data),
resource_common_data: RefundFlowData {
status,
..data.resource_common_data.clone()
},
..data
})
}
}
impl
ForeignTryFrom<(
RazorpayV2SyncResponse,
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
u16,
Vec<u8>, // raw_response
)> for RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(sync_response, data, _status_code, _raw_response): (
RazorpayV2SyncResponse,
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
u16,
Vec<u8>,
),
) -> Result<Self, Self::Error> {
// Extract the payment response from either format
let payment_response =
match sync_response {
RazorpayV2SyncResponse::PaymentResponse(payment) => *payment,
RazorpayV2SyncResponse::OrderPaymentsCollection(collection) => {
// Get the first (and typically only) payment from the collection
collection.items.into_iter().next().ok_or_else(|| {
domain_types::errors::ConnectorError::ResponseHandlingFailed
})?
}
};
// Map Razorpay payment status to internal status, preserving original status
let status = get_psync_razorpay_payment_status(payment_response.status);
let payments_response_data = match payment_response.status {
RazorpayStatus::Created
| RazorpayStatus::Authorized
| RazorpayStatus::Captured
| RazorpayStatus::Refunded => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment_response.id),
redirection_data: None,
connector_metadata: None,
mandate_reference: None,
network_txn_id: None,
connector_response_reference_id: payment_response.order_id,
incremental_authorization_allowed: None,
status_code: _status_code,
}),
RazorpayStatus::Failed => Err(ErrorResponse {
code: payment_response
.error_code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: payment_response
.error_description
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: payment_response.error_reason,
status_code: _status_code,
attempt_status: Some(status),
connector_transaction_id: Some(payment_response.id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
Ok(RouterDataV2 {
response: payments_response_data,
resource_common_data: PaymentFlowData {
status,
..data.resource_common_data.clone()
},
..data
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
ForeignTryFrom<(
RazorpayV2UpiPaymentsResponse,
RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
u16,
Vec<u8>, // raw_response
)>
for RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
| {
"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_-4688241219082903168_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpayv2/transformers.rs
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(upi_response, data, _status_code, _raw_response): (
RazorpayV2UpiPaymentsResponse,
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
u16,
Vec<u8>,
),
) -> Result<Self, Self::Error> {
let (transaction_id, redirection_data) = match upi_response {
RazorpayV2UpiPaymentsResponse::SuccessIntent {
razorpay_payment_id,
link,
} => {
let redirect_form = RedirectForm::Uri { uri: link };
(
ResponseId::ConnectorTransactionId(razorpay_payment_id),
Some(redirect_form),
)
}
RazorpayV2UpiPaymentsResponse::SuccessCollect {
razorpay_payment_id,
} => {
// For UPI Collect, there's no link, so no redirection data
(
ResponseId::ConnectorTransactionId(razorpay_payment_id),
None,
)
}
RazorpayV2UpiPaymentsResponse::Error { error: _ } => {
// Handle error case - this should probably return an error instead
return Err(domain_types::errors::ConnectorError::ResponseHandlingFailed);
}
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: transaction_id,
redirection_data: redirection_data.map(Box::new),
connector_metadata: None,
mandate_reference: None,
network_txn_id: None,
connector_response_reference_id: data.resource_common_data.reference_id.clone(),
incremental_authorization_allowed: None,
status_code: _status_code,
};
Ok(RouterDataV2 {
response: Ok(payments_response_data),
resource_common_data: PaymentFlowData {
status: AttemptStatus::AuthenticationPending,
..data.resource_common_data
},
..data
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
ForeignTryFrom<(
RazorpayV2PaymentsResponse,
RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
u16,
Vec<u8>, // raw_response
)>
for RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(response, data, _status_code, __raw_response): (
RazorpayV2PaymentsResponse,
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
u16,
Vec<u8>,
),
) -> Result<Self, Self::Error> {
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id),
redirection_data: None,
connector_metadata: None,
mandate_reference: None,
network_txn_id: None,
connector_response_reference_id: data.resource_common_data.reference_id.clone(),
incremental_authorization_allowed: None,
status_code: _status_code,
};
Ok(RouterDataV2 {
response: Ok(payments_response_data),
resource_common_data: PaymentFlowData {
status: AttemptStatus::AuthenticationPending,
..data.resource_common_data
},
..data
})
}
}
| {
"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_-6897150982326914141_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
use crate::utils;
use crate::{connectors::trustpay::TrustpayRouterData, types::ResponseRouterData};
use common_enums::enums;
use common_utils::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors::CustomResult,
request::Method,
types::{FloatMajorUnit, StringMajorUnit},
Email,
};
use domain_types::{
connector_flow::CreateAccessToken,
connector_types::{
AccessTokenRequestData, AccessTokenResponseData, PaymentFlowData, PaymentsResponseData,
ResponseId,
},
errors::{self, ConnectorError},
payment_method_data::{BankRedirectData, BankTransferData, PaymentMethodDataTypes},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
};
use hyperswitch_masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use reqwest::Url;
use std::collections::HashMap;
type Error = error_stack::Report<errors::ConnectorError>;
#[allow(dead_code)]
pub struct TrustpayAuthType {
pub(super) api_key: Secret<String>,
pub(super) project_id: Secret<String>,
pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for TrustpayAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
project_id: key1.to_owned(),
secret_key: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
const CLIENT_CREDENTIAL: &str = "client_credentials";
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum TrustpayPaymentMethod {
#[serde(rename = "EPS")]
Eps,
Giropay,
IDeal,
Sofort,
Blik,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum TrustpayBankTransferPaymentMethod {
SepaCreditTransfer,
#[serde(rename = "Wire")]
InstantBankTransfer,
InstantBankTransferFI,
InstantBankTransferPL,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct MerchantIdentification {
pub project_id: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct References {
pub merchant_reference: String,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct Amount {
pub amount: StringMajorUnit,
pub currency: String,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct Reason {
pub code: Option<String>,
pub reject_reason: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct StatusReasonInformation {
pub reason: Reason,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct DebtorInformation {
pub name: Secret<String>,
pub email: Email,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct BankPaymentInformation {
pub amount: Amount,
pub references: References,
#[serde(skip_serializing_if = "Option::is_none")]
pub debtor: Option<DebtorInformation>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct BankPaymentInformationResponse {
pub status: TrustpayBankRedirectPaymentStatus,
pub status_reason_information: Option<StatusReasonInformation>,
pub references: ReferencesResponse,
pub amount: WebhookAmount,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct CallbackURLs {
pub success: String,
pub cancel: String,
pub error: String,
}
impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod {
type Error = Error;
fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Ideal { .. } => Ok(Self::IDeal),
| {
"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_-6897150982326914141_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::Blik { .. } => Ok(Self::Blik),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpay"),
)
.into())
}
}
}
}
impl TryFrom<&BankTransferData> for TrustpayBankTransferPaymentMethod {
type Error = Error;
fn try_from(value: &BankTransferData) -> Result<Self, Self::Error> {
match value {
BankTransferData::SepaBankTransfer { .. } => Ok(Self::SepaCreditTransfer),
BankTransferData::InstantBankTransfer {} => Ok(Self::InstantBankTransfer),
BankTransferData::InstantBankTransferFinland {} => Ok(Self::InstantBankTransferFI),
BankTransferData::InstantBankTransferPoland {} => Ok(Self::InstantBankTransferPL),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpay"),
)
.into()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TrustpayPaymentStatusCode {
// CVV and card validation errors
EmptyCvvNotAllowed,
// Authentication and session errors
SessionRejected,
UserAuthenticationFailed,
RiskManagementTimeout,
PaResValidationFailed,
ThreeDSecureSystemError,
DirectoryServerError,
ThreeDSystemError,
AuthenticationInvalidFormat,
AuthenticationSuspectedFraud,
// Input and parameter errors
InvalidInputData,
AmountOutsideBoundaries,
InvalidOrMissingParameter,
// Transaction decline reasons
AdditionalAuthRequired,
CardNotEnrolledIn3DS,
AuthenticationError,
TransactionDeclinedAuth,
InvalidTransaction1,
InvalidTransaction2,
NoDescription,
// Refund errors
CannotRefund,
TooManyTransactions,
TestAccountsNotAllowed,
// General decline reasons
DeclinedUnknownReason,
DeclinedInvalidCard,
DeclinedByAuthSystem,
DeclinedInvalidCvv,
DeclinedExceedsCredit,
DeclinedWrongExpiry,
DeclinedSuspectingManipulation,
DeclinedCardBlocked,
DeclinedLimitExceeded,
DeclinedFrequencyExceeded,
DeclinedCardLost,
DeclinedRestrictedCard,
DeclinedNotPermitted,
DeclinedPickUpCard,
DeclinedAccountBlocked,
DeclinedInvalidConfig,
AccountClosed,
InsufficientFunds,
RejectedByThrottling,
CountryBlacklisted,
BinBlacklisted,
SessionBeingProcessed,
// Communication errors
CommunicationError,
TimeoutUncertainResult,
// Success or other status
Unknown,
}
impl TrustpayPaymentStatusCode {
pub fn error_message(&self) -> &'static str {
match self {
Self::EmptyCvvNotAllowed => "Empty CVV for VISA, MASTER not allowed",
Self::SessionRejected => "Referenced session is rejected (no action possible)",
Self::UserAuthenticationFailed => "User authentication failed",
Self::RiskManagementTimeout => "Risk management transaction timeout",
Self::PaResValidationFailed => "PARes validation failed - problem with signature",
Self::ThreeDSecureSystemError => "Transaction rejected because of technical error in 3DSecure system",
Self::DirectoryServerError => "Communication error to VISA/Mastercard Directory Server",
Self::ThreeDSystemError => "Technical error in 3D system",
Self::AuthenticationInvalidFormat => "Authentication failed due to invalid message format",
| {
"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_-6897150982326914141_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
Self::AuthenticationSuspectedFraud => "Authentication failed due to suspected fraud",
Self::InvalidInputData => "Invalid input data",
Self::AmountOutsideBoundaries => "Amount is outside allowed ticket size boundaries",
Self::InvalidOrMissingParameter => "Invalid or missing parameter",
Self::AdditionalAuthRequired => "Transaction declined (additional customer authentication required)",
Self::CardNotEnrolledIn3DS => "Card not enrolled in 3DS",
Self::AuthenticationError => "Authentication error",
Self::TransactionDeclinedAuth => "Transaction declined (auth. declined)",
Self::InvalidTransaction1 => "Invalid transaction",
Self::InvalidTransaction2 => "Invalid transaction",
Self::NoDescription => "No description available.",
Self::CannotRefund => "Cannot refund (refund volume exceeded or tx reversed or invalid workflow)",
Self::TooManyTransactions => "Referenced session contains too many transactions",
Self::TestAccountsNotAllowed => "Test accounts not allowed in production",
Self::DeclinedUnknownReason => "Transaction declined for unknown reason",
Self::DeclinedInvalidCard => "Transaction declined (invalid card)",
Self::DeclinedByAuthSystem => "Transaction declined by authorization system",
Self::DeclinedInvalidCvv => "Transaction declined (invalid CVV)",
Self::DeclinedExceedsCredit => "Transaction declined (amount exceeds credit)",
Self::DeclinedWrongExpiry => "Transaction declined (wrong expiry date)",
Self::DeclinedSuspectingManipulation => "transaction declined (suspecting manipulation)",
Self::DeclinedCardBlocked => "transaction declined (card blocked)",
Self::DeclinedLimitExceeded => "Transaction declined (limit exceeded)",
Self::DeclinedFrequencyExceeded => "Transaction declined (maximum transaction frequency exceeded)",
Self::DeclinedCardLost => "Transaction declined (card lost)",
Self::DeclinedRestrictedCard => "Transaction declined (restricted card)",
Self::DeclinedNotPermitted => "Transaction declined (transaction not permitted)",
Self::DeclinedPickUpCard => "transaction declined (pick up card)",
Self::DeclinedAccountBlocked => "Transaction declined (account blocked)",
Self::DeclinedInvalidConfig => "Transaction declined (invalid configuration data)",
Self::AccountClosed => "Account Closed",
Self::InsufficientFunds => "Insufficient Funds",
Self::RejectedByThrottling => "Rejected by throttling",
Self::CountryBlacklisted => "Country blacklisted",
Self::BinBlacklisted => "Bin blacklisted",
Self::SessionBeingProcessed => "Transaction for the same session is currently being processed, please try again later",
Self::CommunicationError => "Unexpected communication error with connector/acquirer",
Self::TimeoutUncertainResult => "Timeout, uncertain result",
Self::Unknown => "",
}
}
pub fn is_failure(&self) -> bool {
!matches!(self, Self::Unknown)
}
}
impl From<&str> for TrustpayPaymentStatusCode {
fn from(status_code: &str) -> Self {
match status_code {
"100.100.600" => Self::EmptyCvvNotAllowed,
"100.350.100" => Self::SessionRejected,
"100.380.401" => Self::UserAuthenticationFailed,
"100.380.501" => Self::RiskManagementTimeout,
"100.390.103" => Self::PaResValidationFailed,
"100.390.105" => Self::ThreeDSecureSystemError,
"100.390.111" => Self::DirectoryServerError,
"100.390.112" => Self::ThreeDSystemError,
"100.390.115" => Self::AuthenticationInvalidFormat,
"100.390.118" => Self::AuthenticationSuspectedFraud,
"100.400.304" => Self::InvalidInputData,
"100.550.312" => Self::AmountOutsideBoundaries,
"200.300.404" => Self::InvalidOrMissingParameter,
"300.100.100" => Self::AdditionalAuthRequired,
| {
"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_-6897150982326914141_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
"400.001.301" => Self::CardNotEnrolledIn3DS,
"400.001.600" => Self::AuthenticationError,
"400.001.601" => Self::TransactionDeclinedAuth,
"400.001.602" => Self::InvalidTransaction1,
"400.001.603" => Self::InvalidTransaction2,
"400.003.600" => Self::NoDescription,
"700.400.200" => Self::CannotRefund,
"700.500.001" => Self::TooManyTransactions,
"700.500.003" => Self::TestAccountsNotAllowed,
"800.100.100" => Self::DeclinedUnknownReason,
"800.100.151" => Self::DeclinedInvalidCard,
"800.100.152" => Self::DeclinedByAuthSystem,
"800.100.153" => Self::DeclinedInvalidCvv,
"800.100.155" => Self::DeclinedExceedsCredit,
"800.100.157" => Self::DeclinedWrongExpiry,
"800.100.158" => Self::DeclinedSuspectingManipulation,
"800.100.160" => Self::DeclinedCardBlocked,
"800.100.162" => Self::DeclinedLimitExceeded,
"800.100.163" => Self::DeclinedFrequencyExceeded,
"800.100.165" => Self::DeclinedCardLost,
"800.100.168" => Self::DeclinedRestrictedCard,
"800.100.170" => Self::DeclinedNotPermitted,
"800.100.171" => Self::DeclinedPickUpCard,
"800.100.172" => Self::DeclinedAccountBlocked,
"800.100.190" => Self::DeclinedInvalidConfig,
"800.100.202" => Self::AccountClosed,
"800.100.203" => Self::InsufficientFunds,
"800.120.100" => Self::RejectedByThrottling,
"800.300.102" => Self::CountryBlacklisted,
"800.300.401" => Self::BinBlacklisted,
"800.700.100" => Self::SessionBeingProcessed,
"900.100.100" => Self::CommunicationError,
"900.100.300" => Self::TimeoutUncertainResult,
_ => Self::Unknown,
}
}
}
fn is_payment_failed(payment_status: &str) -> (bool, &'static str) {
let status_code = TrustpayPaymentStatusCode::from(payment_status);
(status_code.is_failure(), status_code.error_message())
}
fn is_payment_successful(payment_status: &str) -> CustomResult<bool, errors::ConnectorError> {
match payment_status {
"000.400.100" => Ok(true),
_ => {
let allowed_prefixes = [
"000.000.",
"000.100.1",
"000.3",
"000.6",
"000.400.01",
"000.400.02",
"000.400.04",
"000.400.05",
"000.400.06",
"000.400.07",
"000.400.08",
"000.400.09",
];
let is_valid = allowed_prefixes
.iter()
.any(|&prefix| payment_status.starts_with(prefix));
Ok(is_valid)
}
}
}
fn get_pending_status_based_on_redirect_url(redirect_url: Option<Url>) -> enums::AttemptStatus {
match redirect_url {
Some(_url) => enums::AttemptStatus::AuthenticationPending,
None => enums::AttemptStatus::Pending,
}
}
fn get_transaction_status(
payment_status: Option<String>,
redirect_url: Option<Url>,
) -> CustomResult<(enums::AttemptStatus, Option<String>), errors::ConnectorError> {
// We don't get payment_status only in case, when the user doesn't complete the authentication step.
// If we receive status, then return the proper status based on the connector response
if let Some(payment_status) = payment_status {
let (is_failed, failure_message) = is_payment_failed(&payment_status);
if is_failed {
Ok((
enums::AttemptStatus::Failure,
Some(failure_message.to_string()),
))
} else if is_payment_successful(&payment_status)? {
Ok((enums::AttemptStatus::Charged, None))
} else {
let pending_status = get_pending_status_based_on_redirect_url(redirect_url);
Ok((pending_status, None))
}
} else {
Ok((enums::AttemptStatus::AuthenticationPending, None))
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
pub enum TrustpayBankRedirectPaymentStatus {
Paid,
Authorized,
Rejected,
Authorizing,
Pending,
}
| {
"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_-6897150982326914141_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
impl From<TrustpayBankRedirectPaymentStatus> for enums::AttemptStatus {
fn from(item: TrustpayBankRedirectPaymentStatus) -> Self {
match item {
TrustpayBankRedirectPaymentStatus::Paid => Self::Charged,
TrustpayBankRedirectPaymentStatus::Rejected => Self::AuthorizationFailed,
TrustpayBankRedirectPaymentStatus::Authorized => Self::Authorized,
TrustpayBankRedirectPaymentStatus::Authorizing => Self::Authorizing,
TrustpayBankRedirectPaymentStatus::Pending => Self::Authorizing,
}
}
}
impl From<TrustpayBankRedirectPaymentStatus> for enums::RefundStatus {
fn from(item: TrustpayBankRedirectPaymentStatus) -> Self {
match item {
TrustpayBankRedirectPaymentStatus::Paid => Self::Success,
TrustpayBankRedirectPaymentStatus::Rejected => Self::Failure,
_ => Self::Pending,
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsResponseCards {
pub status: i64,
pub description: Option<String>,
pub instance_id: String,
pub payment_status: Option<String>,
pub payment_description: Option<String>,
pub redirect_url: Option<Url>,
pub redirect_params: Option<HashMap<String, String>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentsResponseBankRedirect {
pub payment_request_id: i64,
pub gateway_url: Url,
pub payment_result_info: Option<ResultInfo>,
pub payment_method_response: Option<TrustpayPaymentMethod>,
pub merchant_identification_response: Option<MerchantIdentification>,
pub payment_information_response: Option<BankPaymentInformationResponse>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct ErrorResponseBankRedirect {
#[serde(rename = "ResultInfo")]
pub payment_result_info: ResultInfo,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct ReferencesResponse {
pub payment_request_id: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct SyncResponseBankRedirect {
pub payment_information: BankPaymentInformationResponse,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum TrustpayPaymentsResponse {
CardsPayments(Box<PaymentsResponseCards>),
BankRedirectPayments(Box<PaymentsResponseBankRedirect>),
BankRedirectSync(Box<SyncResponseBankRedirect>),
BankRedirectError(Box<ErrorResponseBankRedirect>),
WebhookResponse(Box<WebhookPaymentInformation>),
}
impl<F, T> TryFrom<ResponseRouterData<TrustpayPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<TrustpayPaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let (status, error, payment_response_data) = get_trustpay_response(
item.response,
item.http_code,
item.router_data.resource_common_data.status,
)?;
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response: error.map_or_else(|| Ok(payment_response_data), Err),
..item.router_data
})
}
}
fn handle_cards_response(
response: PaymentsResponseCards,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let (status, message) = get_transaction_status(
response.payment_status.to_owned(),
response.redirect_url.to_owned(),
)?;
let form_fields = response.redirect_params.unwrap_or_default();
let redirection_data = response.redirect_url.map(|url| RedirectForm::Form {
endpoint: url.to_string(),
method: Method::Post,
form_fields,
});
let error = if message.is_some() {
Some(ErrorResponse {
code: response
.payment_status
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: message
.clone()
| {
"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_-6897150982326914141_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: message,
status_code,
attempt_status: None,
connector_transaction_id: Some(response.instance_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.instance_id.clone()),
redirection_data: redirection_data.map(Box::new),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code,
};
Ok((status, error, payment_response_data))
}
fn handle_bank_redirects_response(
response: PaymentsResponseBankRedirect,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::AuthenticationPending;
let error = None;
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.payment_request_id.to_string()),
redirection_data: Some(Box::new(RedirectForm::from((
response.gateway_url,
Method::Get,
)))),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code,
};
Ok((status, error, payment_response_data))
}
fn handle_bank_redirects_error_response(
response: ErrorResponseBankRedirect,
status_code: u16,
previous_attempt_status: enums::AttemptStatus,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = if matches!(response.payment_result_info.result_code, 1132014 | 1132005) {
previous_attempt_status
} else {
enums::AttemptStatus::AuthorizationFailed
};
let error = Some(ErrorResponse {
code: response.payment_result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: response.payment_result_info.result_code.to_string(),
reason: response.payment_result_info.additional_info,
status_code,
attempt_status: Some(status),
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
});
let payment_response_data = 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,
};
Ok((status, error, payment_response_data))
}
fn handle_bank_redirects_sync_response(
response: SyncResponseBankRedirect,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::from(response.payment_information.status);
let error = if domain_types::utils::is_payment_failure(status) {
let reason_info = response
.payment_information
.status_reason_information
.unwrap_or_default();
Some(ErrorResponse {
code: reason_info
.reason
.code
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
// message vary for the same code, so relying on code alone as it is unique
message: reason_info
.reason
.code
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: reason_info.reason.reject_reason,
status_code,
attempt_status: None,
connector_transaction_id: Some(
| {
"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_-6897150982326914141_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
response
.payment_information
.references
.payment_request_id
.clone(),
),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response
.payment_information
.references
.payment_request_id
.clone(),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code,
};
Ok((status, error, payment_response_data))
}
pub fn handle_webhook_response(
payment_information: WebhookPaymentInformation,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::try_from(payment_information.status)?;
let error = if domain_types::utils::is_payment_failure(status) {
let reason_info = payment_information
.status_reason_information
.unwrap_or_default();
Some(ErrorResponse {
code: reason_info
.reason
.code
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
// message vary for the same code, so relying on code alone as it is unique
message: reason_info
.reason
.code
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: reason_info.reason.reject_reason,
status_code,
attempt_status: None,
connector_transaction_id: payment_information.references.payment_request_id.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let payment_response_data = 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,
};
Ok((status, error, payment_response_data))
}
pub fn get_trustpay_response(
response: TrustpayPaymentsResponse,
status_code: u16,
previous_attempt_status: enums::AttemptStatus,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
match response {
TrustpayPaymentsResponse::CardsPayments(response) => {
handle_cards_response(*response, status_code)
}
TrustpayPaymentsResponse::BankRedirectPayments(response) => {
handle_bank_redirects_response(*response, status_code)
}
TrustpayPaymentsResponse::BankRedirectSync(response) => {
handle_bank_redirects_sync_response(*response, status_code)
}
TrustpayPaymentsResponse::BankRedirectError(response) => {
handle_bank_redirects_error_response(*response, status_code, previous_attempt_status)
}
TrustpayPaymentsResponse::WebhookResponse(response) => {
handle_webhook_response(*response, status_code)
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct ResultInfo {
pub result_code: i64,
pub additional_info: Option<String>,
pub correlation_id: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Errors {
pub code: i64,
pub description: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayErrorResponse {
pub status: i64,
pub description: Option<String>,
pub errors: Option<Vec<Errors>>,
pub instance_id: Option<String>,
| {
"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_-6897150982326914141_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
pub payment_description: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum CreditDebitIndicator {
Crdt,
Dbit,
}
#[derive(strum::Display, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WebhookStatus {
Paid,
Rejected,
Refunded,
Chargebacked,
#[serde(other)]
Unknown,
}
impl TryFrom<WebhookStatus> for enums::AttemptStatus {
type Error = errors::ConnectorError;
fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> {
match item {
WebhookStatus::Paid => Ok(Self::Charged),
WebhookStatus::Rejected => Ok(Self::AuthorizationFailed),
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound),
}
}
}
impl TryFrom<WebhookStatus> for enums::RefundStatus {
type Error = errors::ConnectorError;
fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> {
match item {
WebhookStatus::Paid => Ok(Self::Success),
WebhookStatus::Refunded => Ok(Self::Success),
WebhookStatus::Rejected => Ok(Self::Failure),
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct WebhookReferences {
pub merchant_reference: Option<String>,
pub payment_id: Option<String>,
pub payment_request_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct WebhookAmount {
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct WebhookPaymentInformation {
pub credit_debit_indicator: CreditDebitIndicator,
pub references: WebhookReferences,
pub status: WebhookStatus,
pub amount: WebhookAmount,
pub status_reason_information: Option<StatusReasonInformation>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct TrustpayAuthUpdateRequest {
pub grant_type: String,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
TrustpayRouterData<
RouterDataV2<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
>,
T,
>,
> for TrustpayAuthUpdateRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
_item: TrustpayRouterData<
RouterDataV2<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: CLIENT_CREDENTIAL.to_string(),
})
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct TrustpayAuthUpdateResponse {
pub access_token: Option<Secret<String>>,
pub token_type: Option<String>,
pub expires_in: Option<i64>,
#[serde(rename = "ResultInfo")]
pub result_info: ResultInfo,
}
impl
TryFrom<
ResponseRouterData<
TrustpayAuthUpdateResponse,
RouterDataV2<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
>,
>,
>
for RouterDataV2<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
TrustpayAuthUpdateResponse,
RouterDataV2<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
>,
>,
) -> Result<Self, Self::Error> {
match (item.response.access_token, item.response.expires_in) {
(Some(access_token), Some(expires_in)) => Ok(Self {
response: Ok(AccessTokenResponseData {
access_token: access_token.expose(),
| {
"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_-6897150982326914141_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/trustpay/transformers.rs
expires_in: Some(expires_in),
token_type: Some(item.router_data.request.grant_type.clone()),
}),
..item.router_data
}),
_ => Ok(Self {
response: Err(ErrorResponse {
code: item.response.result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: item.response.result_info.result_code.to_string(),
reason: item.response.result_info.additional_info,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
..item.router_data
}),
}
}
}
| {
"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_6700735980109314159_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/xendit/transformers.rs
use std::collections::HashMap;
use common_enums::Currency;
use common_utils::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
pii,
request::Method,
types::FloatMajorUnit,
};
use domain_types::{
connector_flow::{Authorize, Capture},
connector_types::{
MandateReference, PaymentFlowData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData,
RefundsResponseData, ResponseId,
},
errors::{self, ConnectorError},
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, RawCardNumber},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_request_types::{AuthoriseIntegrityObject, RefundIntegrityObject},
router_response_types::RedirectForm,
};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
connectors::xendit::{XenditAmountConvertor, XenditRouterData},
types::ResponseRouterData,
};
pub trait ForeignTryFrom<F>: Sized {
type Error;
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChannelProperties {
pub success_return_url: Option<String>,
pub failure_return_url: Option<String>,
pub skip_three_d_secure: bool,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardInformation<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub card_number: RawCardNumber<T>,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvv: Secret<String>,
pub cardholder_name: Option<Secret<String>>,
pub cardholder_email: Option<pii::Email>,
pub cardholder_phone_number: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardInfo<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub channel_properties: ChannelProperties,
pub card_information: CardInformation<T>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionType {
OneTimeUse,
MultipleUse,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum PaymentMethodType {
CARD,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum PaymentMethod<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
Card(CardPaymentRequest<T>),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardPaymentRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
#[serde(rename = "type")]
pub payment_type: PaymentMethodType,
pub card: CardInfo<T>,
pub reusability: TransactionType,
pub reference_id: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
Pending,
RequiresAction,
Failed,
Succeeded,
AwaitingCapture,
Verified,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum MethodType {
Get,
Post,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
pub method: MethodType,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentMethodInfo {
pub id: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct XenditPaymentResponse {
pub id: String,
pub status: PaymentStatus,
pub actions: Option<Vec<Action>>,
pub payment_method: PaymentMethodInfo,
pub failure_code: Option<String>,
pub reference_id: Secret<String>,
pub amount: FloatMajorUnit,
pub currency: Currency,
}
pub struct XenditAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for XenditAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
| {
"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_6700735980109314159_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/xendit/transformers.rs
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Basic Request Structure from Hyperswitch Xendit
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct XenditPaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub amount: FloatMajorUnit,
pub currency: common_enums::Currency,
pub capture_method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method: Option<PaymentMethod<T>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub channel_properties: Option<ChannelProperties>,
}
#[derive(Debug, Clone, Serialize)]
pub enum XenditPaymentMethodType {
#[serde(rename = "CARD")]
Card,
// ... other types like EWALLET, DIRECT_DEBIT etc.
}
#[derive(Debug, Clone, Serialize)]
pub struct XenditLineItem {
pub name: String,
pub quantity: i32,
pub price: i64,
pub category: Option<String>,
pub url: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum XenditResponse {
Payment(XenditPaymentResponse),
Webhook(XenditWebhookEvent),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct XenditWebhookEvent {
pub event: XenditEventType,
pub data: EventDetails,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum XenditEventType {
#[serde(rename = "payment.succeeded")]
PaymentSucceeded,
#[serde(rename = "payment.awaiting_capture")]
PaymentAwaitingCapture,
#[serde(rename = "payment.failed")]
PaymentFailed,
#[serde(rename = "capture.succeeded")]
CaptureSucceeded,
#[serde(rename = "capture.failed")]
CaptureFailed,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EventDetails {
pub id: String,
pub payment_request_id: Option<String>,
pub amount: FloatMajorUnit,
pub currency: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct XenditPaymentActions {
#[serde(rename = "desktop_web_checkout_url")]
pub desktop_redirect_url: Option<String>,
#[serde(rename = "mobile_web_checkout_url")]
pub mobile_redirect_url: Option<String>,
#[serde(rename = "mobile_deeplink_checkout_url")]
pub mobile_deeplink_url: Option<String>,
// QR code URL if applicable
#[serde(rename = "qr_checkout_string")]
pub qr_code_url: Option<String>,
}
// Xendit Error Response Structure (from Hyperswitch xendit.rs)
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct XenditErrorResponse {
pub error_code: Option<String>,
pub message: Option<String>,
pub reason: Option<String>, // This might not be standard, check Xendit docs
// Xendit might have more structured errors, e.g. a list of errors
// errors: Option<Vec<XenditErrorDetail>>
}
fn is_auto_capture<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
data: &PaymentsAuthorizeData<T>,
) -> Result<bool, ConnectorError> {
match data.capture_method {
Some(common_enums::CaptureMethod::Automatic) | None => Ok(true),
Some(common_enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(ConnectorError::CaptureMethodNotSupported),
}
}
fn is_auto_capture_psync(data: &PaymentsSyncData) -> Result<bool, ConnectorError> {
match data.capture_method {
Some(common_enums::CaptureMethod::Automatic) | None => Ok(true),
Some(common_enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(ConnectorError::CaptureMethodNotSupported),
}
}
fn map_payment_response_to_attempt_status(
response: XenditPaymentResponse,
is_auto_capture: bool,
) -> common_enums::AttemptStatus {
match response.status {
PaymentStatus::Failed => common_enums::AttemptStatus::Failure,
PaymentStatus::Succeeded | PaymentStatus::Verified => {
if is_auto_capture {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Authorized
}
}
| {
"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_6700735980109314159_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/xendit/transformers.rs
PaymentStatus::Pending => common_enums::AttemptStatus::Pending,
PaymentStatus::RequiresAction => common_enums::AttemptStatus::AuthenticationPending,
PaymentStatus::AwaitingCapture => common_enums::AttemptStatus::Authorized,
}
}
impl From<PaymentStatus> for common_enums::AttemptStatus {
fn from(status: PaymentStatus) -> Self {
match status {
PaymentStatus::Failed => common_enums::AttemptStatus::Failure,
PaymentStatus::Succeeded | PaymentStatus::Verified => {
common_enums::AttemptStatus::Charged
}
PaymentStatus::Pending => common_enums::AttemptStatus::Pending,
PaymentStatus::RequiresAction => common_enums::AttemptStatus::AuthenticationPending,
PaymentStatus::AwaitingCapture => common_enums::AttemptStatus::Authorized,
}
}
}
// Transformer for Request: RouterData -> XenditPaymentsRequest
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
XenditRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for XenditPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: XenditRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let card_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(card) => Ok(card),
_ => Err(ConnectorError::RequestEncodingFailed),
}?;
let capture_method = match is_auto_capture(&item.router_data.request)? {
true => "AUTOMATIC".to_string(),
false => "MANUAL".to_string(),
};
let router_data = &item.router_data;
let currency = item.router_data.request.currency;
let amount = XenditAmountConvertor::convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(ConnectorError::RequestEncodingFailed)?;
let payment_method = Some(PaymentMethod::Card(CardPaymentRequest {
payment_type: PaymentMethodType::CARD,
reference_id: Secret::new(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
card: CardInfo {
channel_properties: ChannelProperties {
success_return_url: item.router_data.request.router_return_url.clone(),
failure_return_url: item.router_data.request.router_return_url.clone(),
skip_three_d_secure: !item.router_data.request.enrolled_for_3ds,
},
card_information: CardInformation {
card_number: card_data.card_number.clone(),
expiry_month: card_data.card_exp_month.clone(),
expiry_year: card_data.card_exp_year.clone(),
cvv: card_data.card_cvc.clone(),
cardholder_email: None,
cardholder_name: None,
cardholder_phone_number: None,
},
},
reusability: TransactionType::OneTimeUse,
}));
let payment_method_id = None;
let channel_properties = None;
Ok(XenditPaymentsRequest {
amount,
currency,
capture_method,
payment_method,
payment_method_id,
channel_properties,
})
}
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<XenditPaymentResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
| {
"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_6700735980109314159_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/xendit/transformers.rs
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<XenditPaymentResponse, Self>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let status = map_payment_response_to_attempt_status(
response.clone(),
is_auto_capture(&router_data.request)?,
);
let payment_response = if status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: Some(response.id.clone()),
status_code: http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id.clone()),
redirection_data: match response.actions {
Some(actions) if !actions.is_empty() => actions.first().map(|single_action| {
Box::new(RedirectForm::Form {
endpoint: single_action.url.clone(),
method: match single_action.method {
MethodType::Get => Method::Get,
MethodType::Post => Method::Post,
},
form_fields: HashMap::new(),
})
}),
_ => None,
},
mandate_reference: match is_mandate_payment(&router_data.request) {
true => Some(Box::new(MandateReference {
connector_mandate_id: Some(response.payment_method.id.expose()),
payment_method_id: None,
})),
false => None,
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.reference_id.peek().to_string()),
incremental_authorization_allowed: None,
status_code: http_code,
})
};
let response_amount =
XenditAmountConvertor::convert_back(response.amount, response.currency)?;
let response_integrity_object = Some(AuthoriseIntegrityObject {
amount: response_amount,
currency: response.currency,
});
Ok(Self {
response: payment_response,
request: PaymentsAuthorizeData {
integrity_object: response_integrity_object,
..router_data.request
},
resource_common_data: PaymentFlowData {
status,
..router_data.resource_common_data
},
..router_data
})
}
}
impl<F> TryFrom<ResponseRouterData<XenditResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<XenditResponse, Self>) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
match response {
XenditResponse::Payment(payment_response) => {
let status = map_payment_response_to_attempt_status(
payment_response.clone(),
is_auto_capture_psync(&router_data.request)?,
);
let response = if status == common_enums::AttemptStatus::Failure {
| {
"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_6700735980109314159_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/xendit/transformers.rs
Err(ErrorResponse {
code: payment_response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: payment_response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
payment_response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: Some(payment_response.id.clone()),
status_code: http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
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: http_code,
})
};
Ok(Self {
response,
resource_common_data: PaymentFlowData {
status,
..router_data.resource_common_data
},
..router_data
})
}
XenditResponse::Webhook(webhook_event) => {
let status = match webhook_event.event {
XenditEventType::PaymentSucceeded | XenditEventType::CaptureSucceeded => {
common_enums::AttemptStatus::Charged
}
XenditEventType::PaymentAwaitingCapture => {
common_enums::AttemptStatus::Authorized
}
XenditEventType::PaymentFailed | XenditEventType::CaptureFailed => {
common_enums::AttemptStatus::Failure
}
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..router_data.resource_common_data
},
..router_data
})
}
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
XenditRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for XenditPaymentsCaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: XenditRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let amount = XenditAmountConvertor::convert(
item.router_data.request.minor_amount_to_capture,
item.router_data.request.currency,
)
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
capture_amount: amount,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct XenditCaptureResponse {
pub id: String,
pub status: PaymentStatus,
pub actions: Option<Vec<Action>>,
pub payment_method: PaymentMethodInfo,
pub failure_code: Option<String>,
pub reference_id: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditPaymentsCaptureRequest {
pub capture_amount: FloatMajorUnit,
}
impl<F> TryFrom<ResponseRouterData<XenditCaptureResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
{
| {
"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
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.