text string | file_path string | module string | type string | tokens int64 | language string | struct_name string | type_name string | trait_name string | impl_type string | function_name string | source string | section string | keys list | macro_type string | url string | title string | chunk_index int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
File: crates/router/src/core/utils.rs
Public functions: 40
pub mod refunds_transformers;
pub mod refunds_validator;
use std::{collections::HashSet, marker::PhantomData, str::FromStr};
use api_models::enums::{Connector, DisputeStage, DisputeStatus};
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutVendorAccountDetails;
use common_enums::{IntentStatus, RequestIncrementalAuthorization};
#[cfg(feature = "payouts")]
use common_utils::{crypto::Encryptable, pii::Email};
use common_utils::{
errors::CustomResult,
ext_traits::AsyncExt,
types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit},
};
use diesel_models::refund as diesel_refund;
use error_stack::{report, ResultExt};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::types::VaultRouterData;
use hyperswitch_domain_models::{
merchant_connector_account::MerchantConnectorAccount, payment_address::PaymentAddress,
router_data::ErrorResponse, router_request_types, types::OrderDetailsWithAmount,
};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::VaultConnectorFlowData, types::VaultRouterDataV2,
};
use hyperswitch_interfaces::api::ConnectorSpecifications;
#[cfg(feature = "v2")]
use masking::ExposeOptionInterface;
use masking::Secret;
#[cfg(feature = "payouts")]
use masking::{ExposeInterface, PeekInterface};
use maud::{html, PreEscaped};
use regex::Regex;
use router_env::{instrument, tracing};
use super::payments::helpers;
#[cfg(feature = "payouts")]
use super::payouts::{helpers as payout_helpers, PayoutData};
#[cfg(feature = "payouts")]
use crate::core::payments;
#[cfg(feature = "v2")]
use crate::core::payments::helpers as payment_helpers;
use crate::{
configs::Settings,
consts,
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::PaymentData,
},
db::StorageInterface,
routes::SessionState,
types::{
self, api, domain,
storage::{self, enums},
PollConfig,
},
utils::{generate_id, OptionExt, ValueExt},
};
pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW: &str =
"irrelevant_connector_request_reference_id_in_dispute_flow";
#[cfg(feature = "payouts")]
pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW: &str =
"irrelevant_connector_request_reference_id_in_payouts_flow";
const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_dispute_flow";
#[cfg(all(feature = "payouts", feature = "v2"))]
#[instrument(skip_all)]
pub async fn construct_payout_router_data<'a, F>(
_state: &SessionState,
_connector_data: &api::ConnectorData,
_merchant_context: &domain::MerchantContext,
_payout_data: &mut PayoutData,
) -> RouterResult<types::PayoutsRouterData<F>> {
todo!()
}
#[cfg(all(feature = "payouts", feature = "v1"))]
#[instrument(skip_all)]
pub async fn construct_payout_router_data<'a, F>(
state: &SessionState,
connector_data: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
payout_data: &mut PayoutData,
) -> RouterResult<types::PayoutsRouterData<F>> {
let merchant_connector_account = payout_data
.merchant_connector_account
.clone()
.get_required_value("merchant_connector_account")?;
let connector_name = connector_data.connector_name;
let connector_auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let billing = payout_data.billing_address.to_owned();
let billing_address = billing.map(api_models::payments::Address::from);
let address = PaymentAddress::new(None, billing_address.map(From::from), None, None);
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let payouts = &payout_data.payouts;
let payout_attempt = &payout_data.payout_attempt;
let customer_details = &payout_data.customer_details;
let connector_label = format!(
"{}_{}",
payout_data.profile_id.get_string_repr(),
connector_name
);
let connector_customer_id = customer_details
.as_ref()
.and_then(|c| c.connector_customer.as_ref())
.and_then(|connector_customer_value| {
connector_customer_value
.clone()
.expose()
.get(connector_label)
.cloned()
})
.and_then(|id| serde_json::from_value::<String>(id).ok());
let vendor_details: Option<PayoutVendorAccountDetails> =
match api_models::enums::PayoutConnectors::try_from(connector_name.to_owned()).map_err(
|err| report!(errors::ApiErrorResponse::InternalServerError).attach_printable(err),
)? {
api_models::enums::PayoutConnectors::Stripe => {
payout_data.payouts.metadata.to_owned().and_then(|meta| {
let val = meta
.peek()
.to_owned()
.parse_value("PayoutVendorAccountDetails")
.ok();
val
})
}
_ => None,
};
let connector_transfer_method_id =
payout_helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
customer_id: customer_details.to_owned().map(|c| c.customer_id),
tenant_id: state.tenant.tenant_id.clone(),
connector_customer: connector_customer_id,
connector: connector_name.to_string(),
payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("payout")
.get_string_repr()
.to_owned(),
attempt_id: "".to_string(),
status: enums::AttemptStatus::Failure,
payment_method: enums::PaymentMethod::default(),
connector_auth_type,
description: None,
address,
auth_type: enums::AuthenticationType::default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
minor_amount_captured: None,
payment_method_status: None,
request: types::PayoutsData {
payout_id: payouts.payout_id.clone(),
amount: payouts.amount.get_amount_as_i64(),
minor_amount: payouts.amount,
connector_payout_id: payout_attempt.connector_payout_id.clone(),
destination_currency: payouts.destination_currency,
source_currency: payouts.source_currency,
entity_type: payouts.entity_type.to_owned(),
payout_type: payouts.payout_type,
vendor_details,
priority: payouts.priority,
customer_details: customer_details
.to_owned()
.map(|c| payments::CustomerDetails {
customer_id: Some(c.customer_id),
name: c.name.map(Encryptable::into_inner),
email: c.email.map(Email::from),
phone: c.phone.map(Encryptable::into_inner),
phone_country_code: c.phone_country_code,
tax_registration_id: c.tax_registration_id.map(Encryptable::into_inner),
}),
connector_transfer_method_id,
},
response: Ok(types::PayoutsResponseData::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id: payout_attempt.payout_attempt_id.clone(),
payout_method_data: payout_data.payout_method_data.to_owned(),
quote_id: None,
test_mode,
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
};
Ok(router_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_refund_router_data<'a, F>(
state: &'a SessionState,
connector_enum: Connector,
merchant_context: &domain::MerchantContext,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
refund: &'a diesel_refund::Refund,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<types::RefundsRouterData<F>> {
let auth_type = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let status = payment_attempt.status;
let payment_amount = payment_attempt.get_total_amount();
let currency = payment_intent.get_currency();
let payment_method_type = payment_attempt.payment_method_type;
let webhook_url = match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
merchant_connector_account,
) => Some(helpers::create_webhook_url(
&state.base_url.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_connector_account.get_id().get_string_repr(),
)),
// TODO: Implement for connectors that require a webhook URL to be included in the request payload.
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
};
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
.find_config_by_key(&format!("connector_api_version_{connector_enum}"))
.await
.map(|value| value.config)
.ok()
} else {
None
};
let browser_info = payment_attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
let connector_refund_id = refund.get_optional_connector_refund_id().cloned();
let capture_method = payment_intent.capture_method;
let customer_id = payment_intent
.get_optional_customer_id()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get optional customer id")?;
let braintree_metadata = payment_intent
.get_optional_connector_metadata()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed parsing ConnectorMetadata")?
.and_then(|cm| cm.braintree);
let merchant_account_id = braintree_metadata
.as_ref()
.and_then(|braintree| braintree.merchant_account_id.clone());
let merchant_config_currency =
braintree_metadata.and_then(|braintree| braintree.merchant_config_currency);
let connector_wallets_details = match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
merchant_connector_account,
) => merchant_connector_account.get_connector_wallets_details(),
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
};
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_enum.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.id.get_string_repr().to_string().clone(),
status,
payment_method: payment_method_type,
connector_auth_type: auth_type,
description: None,
// Does refund need shipping/billing address ?
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type,
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details,
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
payment_method_status: None,
minor_amount_captured: payment_intent.amount_captured,
request: types::RefundsData {
refund_id: refund.id.get_string_repr().to_string(),
connector_transaction_id: refund.get_connector_transaction_id().clone(),
refund_amount: refund.refund_amount.get_amount_as_i64(),
minor_refund_amount: refund.refund_amount,
currency,
payment_amount: payment_amount.get_amount_as_i64(),
minor_payment_amount: payment_amount,
webhook_url,
connector_metadata: payment_attempt.connector_metadata.clone().expose_option(),
reason: refund.refund_reason.clone(),
connector_refund_id: connector_refund_id.clone(),
browser_info,
split_refunds: None,
integrity_object: None,
refund_status: refund.refund_status,
merchant_account_id,
merchant_config_currency,
refund_connector_metadata: refund.metadata.clone(),
capture_method: Some(capture_method),
additional_payment_method_data: None,
},
response: Ok(types::RefundsResponseData {
connector_refund_id: connector_refund_id.unwrap_or_default(),
refund_status: refund.refund_status,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id: refund
.merchant_reference_id
.get_string_repr()
.to_string()
.clone(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
payment_method_balance: None,
connector_api_version,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: Some(refund.id.get_string_repr().to_string().clone()),
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
};
Ok(router_data)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_refund_router_data<'a, F>(
state: &'a SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
money: (MinorUnit, enums::Currency),
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
refund: &'a diesel_refund::Refund,
creds_identifier: Option<String>,
split_refunds: Option<router_request_types::SplitRefundsRequest>,
) -> RouterResult<types::RefundsRouterData<F>> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?;
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
creds_identifier.as_deref(),
merchant_context.get_merchant_key_store(),
profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let status = payment_attempt.status;
let (payment_amount, currency) = money;
let payment_method_type = payment_attempt
.payment_method
.get_required_value("payment_method_type")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_connector_account_id_or_connector_name = payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(connector_id);
let webhook_url = Some(helpers::create_webhook_url(
&state.base_url.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_connector_account_id_or_connector_name,
));
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_enum = Connector::from_str(connector_id)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_id:?}"))?;
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
.find_config_by_key(&format!("connector_api_version_{connector_id}"))
.await
.map(|value| value.config)
.ok()
} else {
None
};
let browser_info: Option<types::BrowserInformation> = payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let connector_refund_id = refund.get_optional_connector_refund_id().cloned();
let capture_method = payment_attempt.capture_method;
let braintree_metadata = payment_intent
.connector_metadata
.clone()
.map(|cm| {
cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed parsing ConnectorMetadata")
})
.transpose()?
.and_then(|cm| cm.braintree);
let merchant_account_id = braintree_metadata
.as_ref()
.and_then(|braintree| braintree.merchant_account_id.clone());
let merchant_config_currency =
braintree_metadata.and_then(|braintree| braintree.merchant_config_currency);
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_attempt
.payment_method_data
.clone()
.and_then(|value| match serde_json::from_value(value) {
Ok(data) => Some(data),
Err(e) => {
router_env::logger::error!("Failed to deserialize payment_method_data: {}", e);
None
}
});
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id: payment_intent.customer_id.to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
status,
payment_method: payment_method_type,
connector_auth_type: auth_type,
description: None,
// Does refund need shipping/billing address ?
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
payment_method_status: None,
minor_amount_captured: payment_intent.amount_captured,
request: types::RefundsData {
refund_id: refund.refund_id.clone(),
connector_transaction_id: refund.get_connector_transaction_id().clone(),
refund_amount: refund.refund_amount.get_amount_as_i64(),
minor_refund_amount: refund.refund_amount,
currency,
payment_amount: payment_amount.get_amount_as_i64(),
minor_payment_amount: payment_amount,
webhook_url,
connector_metadata: payment_attempt.connector_metadata.clone(),
refund_connector_metadata: refund.metadata.clone(),
reason: refund.refund_reason.clone(),
connector_refund_id: connector_refund_id.clone(),
browser_info,
split_refunds,
integrity_object: None,
refund_status: refund.refund_status,
merchant_account_id,
merchant_config_currency,
capture_method,
additional_payment_method_data,
},
response: Ok(types::RefundsResponseData {
connector_refund_id: connector_refund_id.unwrap_or_default(),
refund_status: refund.refund_status,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id: refund.refund_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
payment_method_balance: None,
connector_api_version,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: Some(refund.refund_id.clone()),
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
};
Ok(router_data)
}
pub fn get_or_generate_id(
key: &str,
provided_id: &Option<String>,
prefix: &str,
) -> Result<String, errors::ApiErrorResponse> {
let validate_id = |id| validate_id(id, key);
provided_id
.clone()
.map_or(Ok(generate_id(consts::ID_LENGTH, prefix)), validate_id)
}
fn invalid_id_format_error(key: &str) -> errors::ApiErrorResponse {
errors::ApiErrorResponse::InvalidDataFormat {
field_name: key.to_string(),
expected_format: format!(
"length should be less than {} characters",
consts::MAX_ID_LENGTH
),
}
}
pub fn validate_id(id: String, key: &str) -> Result<String, errors::ApiErrorResponse> {
if id.len() > consts::MAX_ID_LENGTH {
Err(invalid_id_format_error(key))
} else {
Ok(id)
}
}
#[cfg(feature = "v1")]
pub fn get_split_refunds(
split_refund_input: refunds_transformers::SplitRefundInput,
) -> RouterResult<Option<router_request_types::SplitRefundsRequest>> {
match split_refund_input.split_payment_request.as_ref() {
Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(stripe_payment)) => {
let (charge_id_option, charge_type_option) = match (
&split_refund_input.payment_charges,
&split_refund_input.split_payment_request,
) {
(
Some(common_types::payments::ConnectorChargeResponseData::StripeSplitPayment(
stripe_split_payment_response,
)),
_,
) => (
stripe_split_payment_response.charge_id.clone(),
Some(stripe_split_payment_response.charge_type.clone()),
),
(
_,
Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment_request,
)),
) => (
split_refund_input.charge_id,
Some(stripe_split_payment_request.charge_type.clone()),
),
(_, _) => (None, None),
};
if let Some(charge_id) = charge_id_option {
let options = refunds_validator::validate_stripe_charge_refund(
charge_type_option,
&split_refund_input.refund_request,
)?;
Ok(Some(
router_request_types::SplitRefundsRequest::StripeSplitRefund(
router_request_types::StripeSplitRefund {
charge_id,
charge_type: stripe_payment.charge_type.clone(),
transfer_account_id: stripe_payment.transfer_account_id.clone(),
options,
},
),
))
} else {
Ok(None)
}
}
Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(_)) => {
match &split_refund_input.payment_charges {
Some(common_types::payments::ConnectorChargeResponseData::AdyenSplitPayment(
adyen_split_payment_response,
)) => {
if let Some(common_types::refunds::SplitRefund::AdyenSplitRefund(
split_refund_request,
)) = split_refund_input.refund_request.clone()
{
refunds_validator::validate_adyen_charge_refund(
adyen_split_payment_response,
&split_refund_request,
)?;
Ok(Some(
router_request_types::SplitRefundsRequest::AdyenSplitRefund(
split_refund_request,
),
))
} else {
Ok(None)
}
}
_ => Ok(None),
}
}
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(_)) => {
match (
&split_refund_input.payment_charges,
&split_refund_input.refund_request,
) {
(
Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
xendit_split_payment_response,
)),
Some(common_types::refunds::SplitRefund::XenditSplitRefund(
split_refund_request,
)),
) => {
let user_id = refunds_validator::validate_xendit_charge_refund(
xendit_split_payment_response,
split_refund_request,
)?;
Ok(user_id.map(|for_user_id| {
router_request_types::SplitRefundsRequest::XenditSplitRefund(
common_types::domain::XenditSplitSubMerchantData { for_user_id },
)
}))
}
(
Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
xendit_split_payment_response,
)),
None,
) => {
let option_for_user_id = match xendit_split_payment_response {
common_types::payments::XenditChargeResponseData::MultipleSplits(
common_types::payments::XenditMultipleSplitResponse {
for_user_id, ..
},
) => for_user_id.clone(),
common_types::payments::XenditChargeResponseData::SingleSplit(
common_types::domain::XenditSplitSubMerchantData { for_user_id },
) => Some(for_user_id.clone()),
};
if option_for_user_id.is_some() {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "split_refunds.xendit_split_refund.for_user_id",
})?
} else {
Ok(None)
}
}
_ => Ok(None),
}
}
_ => Ok(None),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used)]
use super::*;
#[test]
fn validate_id_length_constraint() {
let payment_id =
"abcdefghijlkmnopqrstuvwzyzabcdefghijknlmnopsjkdnfjsknfkjsdnfspoig".to_string(); //length = 65
let result = validate_id(payment_id, "payment_id");
assert!(result.is_err());
}
#[test]
fn validate_id_proper_response() {
let payment_id = "abcdefghijlkmnopqrstjhbjhjhkhbhgcxdfxvmhb".to_string();
let result = validate_id(payment_id.clone(), "payment_id");
assert!(result.is_ok());
let result = result.unwrap_or_default();
assert_eq!(result, payment_id);
}
#[test]
fn test_generate_id() {
let generated_id = generate_id(consts::ID_LENGTH, "ref");
assert_eq!(generated_id.len(), consts::ID_LENGTH + 4)
}
#[test]
fn test_filter_objects_based_on_profile_id_list() {
#[derive(PartialEq, Debug, Clone)]
struct Object {
profile_id: Option<common_utils::id_type::ProfileId>,
}
impl Object {
pub fn new(profile_id: &'static str) -> Self {
Self {
profile_id: Some(
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(
profile_id,
))
.expect("invalid profile ID"),
),
}
}
}
impl GetProfileId for Object {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.profile_id.as_ref()
}
}
fn new_profile_id(profile_id: &'static str) -> common_utils::id_type::ProfileId {
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(profile_id))
.expect("invalid profile ID")
}
// non empty object_list and profile_id_list
let object_list = vec![
Object::new("p1"),
Object::new("p2"),
Object::new("p2"),
Object::new("p4"),
Object::new("p5"),
];
let profile_id_list = vec![
new_profile_id("p1"),
new_profile_id("p2"),
new_profile_id("p3"),
];
let filtered_list =
filter_objects_based_on_profile_id_list(Some(profile_id_list), object_list.clone());
let expected_result = vec![Object::new("p1"), Object::new("p2"), Object::new("p2")];
assert_eq!(filtered_list, expected_result);
// non empty object_list and empty profile_id_list
let empty_profile_id_list = vec![];
let filtered_list = filter_objects_based_on_profile_id_list(
Some(empty_profile_id_list),
object_list.clone(),
);
let expected_result = vec![];
assert_eq!(filtered_list, expected_result);
// non empty object_list and None profile_id_list
let profile_id_list_as_none = None;
let filtered_list =
filter_objects_based_on_profile_id_list(profile_id_list_as_none, object_list);
let expected_result = vec![
Object::new("p1"),
Object::new("p2"),
Object::new("p2"),
Object::new("p4"),
Object::new("p5"),
];
assert_eq!(filtered_list, expected_result);
}
}
// Dispute Stage can move linearly from PreDispute -> Dispute -> PreArbitration -> Arbitration -> DisputeReversal
pub fn validate_dispute_stage(
prev_dispute_stage: DisputeStage,
dispute_stage: DisputeStage,
) -> bool {
match prev_dispute_stage {
DisputeStage::PreDispute => true,
DisputeStage::Dispute => !matches!(dispute_stage, DisputeStage::PreDispute),
DisputeStage::PreArbitration => matches!(
dispute_stage,
DisputeStage::PreArbitration
| DisputeStage::Arbitration
| DisputeStage::DisputeReversal
),
DisputeStage::Arbitration => matches!(
dispute_stage,
DisputeStage::Arbitration | DisputeStage::DisputeReversal
),
DisputeStage::DisputeReversal => matches!(dispute_stage, DisputeStage::DisputeReversal),
}
}
//Dispute status can go from Opened -> (Expired | Accepted | Cancelled | Challenged -> (Won | Lost))
pub fn validate_dispute_status(
prev_dispute_status: DisputeStatus,
dispute_status: DisputeStatus,
) -> bool {
match prev_dispute_status {
DisputeStatus::DisputeOpened => true,
DisputeStatus::DisputeExpired => {
matches!(dispute_status, DisputeStatus::DisputeExpired)
}
DisputeStatus::DisputeAccepted => {
matches!(dispute_status, DisputeStatus::DisputeAccepted)
}
DisputeStatus::DisputeCancelled => {
matches!(dispute_status, DisputeStatus::DisputeCancelled)
}
DisputeStatus::DisputeChallenged => matches!(
dispute_status,
DisputeStatus::DisputeChallenged
| DisputeStatus::DisputeWon
| DisputeStatus::DisputeLost
| DisputeStatus::DisputeAccepted
| DisputeStatus::DisputeCancelled
| DisputeStatus::DisputeExpired
),
DisputeStatus::DisputeWon => matches!(dispute_status, DisputeStatus::DisputeWon),
DisputeStatus::DisputeLost => matches!(dispute_status, DisputeStatus::DisputeLost),
}
}
pub fn validate_dispute_stage_and_dispute_status(
prev_dispute_stage: DisputeStage,
prev_dispute_status: DisputeStatus,
dispute_stage: DisputeStage,
dispute_status: DisputeStatus,
) -> CustomResult<(), errors::WebhooksFlowError> {
let dispute_stage_validation = validate_dispute_stage(prev_dispute_stage, dispute_stage);
let dispute_status_validation = if dispute_stage == prev_dispute_stage {
validate_dispute_status(prev_dispute_status, dispute_status)
} else {
true
};
common_utils::fp_utils::when(
!(dispute_stage_validation && dispute_status_validation),
|| {
super::metrics::INCOMING_DISPUTE_WEBHOOK_VALIDATION_FAILURE_METRIC.add(1, &[]);
Err(errors::WebhooksFlowError::DisputeWebhookValidationFailed)?
},
)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn construct_accept_dispute_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_context: &domain::MerchantContext,
dispute: &storage::Dispute,
) -> RouterResult<types::AcceptDisputeRouterData> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
&dispute.connector,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: dispute.connector.to_string(),
tenant_id: state.tenant.tenant_id.clone(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: types::AcceptDisputeRequestData {
dispute_id: dispute.dispute_id.clone(),
connector_dispute_id: dispute.connector_dispute_id.clone(),
dispute_status: dispute.dispute_status,
},
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
customer_id: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
payment_intent,
payment_attempt,
&dispute.connector,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None, | crates/router/src/core/utils.rs#chunk0 | router | chunk | 8,189 | null | null | null | null | null | null | null | null | null | null | null | null | null |
Ok(get_status(response.kind.as_str()))
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
Ok(Box::new(response))
}
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
Ok(ApplicationResponse::TextPlain("[accepted]".to_string()))
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
match response.dispute {
Some(dispute_data) => Ok(DisputePayload {
amount: convert_amount(
self.amount_converter_webhooks,
dispute_data.amount_disputed,
dispute_data.currency_iso_code,
)?,
currency: dispute_data.currency_iso_code,
dispute_stage: transformers::get_dispute_stage(dispute_data.kind.as_str())?,
connector_dispute_id: dispute_data.id,
connector_reason: dispute_data.reason,
connector_reason_code: dispute_data.reason_code,
challenge_required_by: dispute_data.reply_by_date,
connector_status: dispute_data.status,
created_at: dispute_data.created_at,
updated_at: dispute_data.updated_at,
}),
None => Err(errors::ConnectorError::WebhookResourceObjectNotFound)?,
}
}
}
fn get_matching_webhook_signature(
signature_pairs: Vec<(&str, &str)>,
secret: String,
) -> Option<String> {
for (public_key, signature) in signature_pairs {
if *public_key == secret {
return Some(signature.to_string());
}
}
None
}
fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<transformers::BraintreeWebhookResponse, ParsingError> {
serde_urlencoded::from_bytes::<transformers::BraintreeWebhookResponse>(body)
.change_context(ParsingError::StructParseFailure("BraintreeWebhookResponse"))
}
fn decode_webhook_payload(
payload: &[u8],
) -> CustomResult<transformers::Notification, errors::ConnectorError> {
let decoded_response = BASE64_ENGINE
.decode(payload)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let xml_response = String::from_utf8(decoded_response)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
xml_response
.parse_xml::<transformers::Notification>()
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
impl ConnectorRedirectResponse for Braintree {
fn get_flow_type(
&self,
_query_params: &str,
json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync => match json_payload {
Some(payload) => {
let redirection_response: transformers::BraintreeRedirectionResponse =
serde_json::from_value(payload).change_context(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_response",
},
)?;
let braintree_payload =
serde_json::from_str::<transformers::BraintreeThreeDsErrorResponse>(
&redirection_response.authentication_response,
);
let (error_code, error_message) = match braintree_payload {
Ok(braintree_response_payload) => (
braintree_response_payload.code,
braintree_response_payload.message,
),
Err(_) => (
NO_ERROR_CODE.to_string(),
redirection_response.authentication_response,
),
};
Ok(CallConnectorAction::StatusUpdate {
status: enums::AttemptStatus::AuthenticationFailed,
error_code: Some(error_code),
error_message: Some(error_message),
})
}
None => Ok(CallConnectorAction::Avoid),
},
PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
}
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Braintree
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req =
transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
match PaymentsCompleteAuthorizeRequestData::is_auto_capture(&data.request)? {
true => {
let response: transformers::BraintreeCompleteChargeResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
false => {
let response: transformers::BraintreeCompleteAuthResponse = res
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
static BRAINTREE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut braintree_supported_payment_methods = SupportedPaymentMethods::new();
braintree_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
braintree_supported_payment_methods
});
static BRAINTREE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Braintree",
description:
"Braintree, a PayPal service, offers a full-stack payment platform that simplifies accepting payments in your app or website, supporting various payment methods including credit cards and PayPal.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static BRAINTREE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Braintree {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BRAINTREE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BRAINTREE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BRAINTREE_SUPPORTED_WEBHOOK_FLOWS)
}
}
| crates/hyperswitch_connectors/src/connectors/braintree.rs#chunk1 | hyperswitch_connectors | chunk | 2,475 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl Helcim {
pub fn connector_transaction_id(
&self,
connector_meta: Option<&serde_json::Value>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
let meta: helcim::HelcimMetaData = to_connector_meta(connector_meta.cloned())?;
Ok(Some(meta.preauth_transaction_id.to_string()))
}
} | crates/hyperswitch_connectors/src/connectors/helcim.rs | hyperswitch_connectors | impl_block | 78 | rust | null | Helcim | null | impl Helcim | null | null | null | null | null | null | null | null |
impl api::PayoutCancel for Stripe {} | crates/hyperswitch_connectors/src/connectors/stripe.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Stripe | api::PayoutCancel for | impl api::PayoutCancel for for Stripe | null | null | null | null | null | null | null | null |
pub struct RawPaymentCounterparty<'a, F> {
pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>,
pub raw_payout_method_data: payouts::PayoutMethodData,
} | crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs | hyperswitch_connectors | struct_definition | 49 | rust | RawPaymentCounterparty | null | null | null | null | null | null | null | null | null | null | null |
impl CardsInfoInterface for KafkaStore {
type Error = errors::StorageError;
async fn get_card_info(
&self,
card_iin: &str,
) -> CustomResult<Option<storage::CardInfo>, errors::StorageError> {
self.diesel_store.get_card_info(card_iin).await
}
async fn add_card_info(
&self,
data: storage::CardInfo,
) -> CustomResult<storage::CardInfo, errors::StorageError> {
self.diesel_store.add_card_info(data).await
}
async fn update_card_info(
&self,
card_iin: String,
data: storage::UpdateCardInfo,
) -> CustomResult<storage::CardInfo, errors::StorageError> {
self.diesel_store.update_card_info(card_iin, data).await
}
} | crates/router/src/db/kafka_store.rs | router | impl_block | 183 | rust | null | KafkaStore | CardsInfoInterface for | impl CardsInfoInterface for for KafkaStore | null | null | null | null | null | null | null | null |
pub struct BankAccountDetailsBacs {
pub account_number: Secret<String>,
pub sort_code: Secret<String>,
} | crates/pm_auth/src/types.rs | pm_auth | struct_definition | 25 | rust | BankAccountDetailsBacs | null | null | null | null | null | null | null | null | null | null | null |
pub async fn retrieve_revenue_recovery_process_tracker(
state: SessionState,
id: id_type::GlobalPaymentId,
) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> {
let db = &*state.store;
let task = EXECUTE_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_id = id.get_execute_revenue_recovery_id(task, runner);
let process_tracker = db
.find_process_by_id(&process_tracker_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("error retrieving the process tracker id")?
.get_required_value("Process Tracker")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Entry For the following id doesn't exists".to_owned(),
})?;
let tracking_data = process_tracker
.tracking_data
.clone()
.parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize Pcr Workflow Tracking Data")?;
let psync_task = PSYNC_WORKFLOW;
let process_tracker_id_for_psync = tracking_data
.payment_attempt_id
.get_psync_revenue_recovery_id(psync_task, runner);
let process_tracker_for_psync = db
.find_process_by_id(&process_tracker_id_for_psync)
.await
.map_err(|e| {
logger::error!("Error while retrieving psync task : {:?}", e);
})
.ok()
.flatten();
let schedule_time_for_psync = process_tracker_for_psync.and_then(|pt| pt.schedule_time);
let response = revenue_recovery::RevenueRecoveryResponse {
id: process_tracker.id,
name: process_tracker.name,
schedule_time_for_payment: process_tracker.schedule_time,
schedule_time_for_psync,
status: process_tracker.status,
business_status: process_tracker.business_status,
};
Ok(ApplicationResponse::Json(response))
} | crates/router/src/core/revenue_recovery.rs | router | function_signature | 445 | rust | null | null | null | null | retrieve_revenue_recovery_process_tracker | null | null | null | null | null | null | null |
impl api::PaymentCapture for Nordea {} | crates/hyperswitch_connectors/src/connectors/nordea.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Nordea | api::PaymentCapture for | impl api::PaymentCapture for for Nordea | null | null | null | null | null | null | null | null |
pub async fn create_payment_method_for_intent(
state: &SessionState,
metadata: Option<common_utils::pii::SecretSerdeValue>,
customer_id: &id_type::GlobalCustomerId,
payment_method_id: id_type::GlobalPaymentMethodId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
payment_method_billing_address: Option<
Encryptable<hyperswitch_domain_models::address::Address>,
>,
) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*state.store;
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
&state.into(),
key_store,
domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
id: payment_method_id,
locker_id: None,
payment_method_type: None,
payment_method_subtype: None,
payment_method_data: None,
connector_mandate_details: None,
customer_acceptance: None,
client_secret: None,
status: enums::PaymentMethodStatus::AwaitingData,
network_transaction_id: None,
created_at: current_time,
last_modified: current_time,
last_used_at: current_time,
payment_method_billing_address,
updated_by: None,
version: common_types::consts::API_VERSION,
locker_fingerprint_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
network_token_requestor_reference_id: None,
external_vault_source: None,
external_vault_token_data: None,
},
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
Ok(response)
} | crates/router/src/core/payment_methods.rs | router | function_signature | 412 | rust | null | null | null | null | create_payment_method_for_intent | null | null | null | null | null | null | null |
pub struct PaymentsTokenReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>,
); | crates/diesel_models/src/payment_method.rs | diesel_models | struct_definition | 26 | rust | PaymentsTokenReference | null | null | null | null | null | null | null | null | null | null | null |
pub struct SubmitSingleCaptureResult {
response: CaptureResponse,
} | crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs | hyperswitch_connectors | struct_definition | 14 | rust | SubmitSingleCaptureResult | null | null | null | null | null | null | null | null | null | null | null |
File: crates/openapi/src/routes/payment_method.rs
Public functions: 23
/// PaymentMethods - Create
///
/// Creates and stores a payment method against a customer.
/// In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/payment_methods",
request_body (
content = PaymentMethodCreate,
examples (( "Save a card" =(
value =json!( {
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4242424242424242",
"card_exp_month": "11",
"card_exp_year": "25",
"card_holder_name": "John Doe"
},
"customer_id": "{{customer_id}}"
})
)))
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data")
),
tag = "Payment Methods",
operation_id = "Create a Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn create_payment_method_api() {}
/// List payment methods for a Merchant
///
/// Lists the applicable payment methods for a particular Merchant ID.
/// Use the client secret and publishable key authorization to list all relevant payment methods of the merchant for the payment corresponding to the client secret.
#[utoipa::path(
get,
path = "/account/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = PaymentMethodListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Merchant",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn list_payment_method_api() {}
/// List payment methods for a Customer
///
/// Lists all the applicable payment methods for a particular Customer ID.
#[utoipa::path(
get,
path = "/customers/{customer_id}/payment_methods",
params (
("customer_id" = String, Path, description = "The unique identifier for the customer account"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn list_customer_payment_method_api() {}
/// List customer saved payment methods for a Payment
///
/// Lists all the applicable payment methods for a particular payment tied to the `client_secret`.
#[utoipa::path(
get,
path = "/customers/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List Customer Payment Methods via Client Secret",
security(("publishable_key" = []))
)]
pub async fn list_customer_payment_method_api_client() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Retrieve a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
/// This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.
#[utoipa::path(
post,
path = "/payment_methods/{method_id}/update",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
request_body = PaymentMethodUpdate,
responses(
(status = 200, description = "Payment Method updated", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Update a Payment method",
security(("api_key" = []), ("publishable_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method deleted", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Delete a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Set Default Payment Method for Customer
///
/// Set the Payment Method as Default for the Customer.
#[utoipa::path(
post,
path = "/{customer_id}/payment_methods/{payment_method_id}/default",
params (
("customer_id" = String,Path, description ="The unique identifier for the Customer"),
("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
(status = 400, description = "Payment Method has already been set as default for that customer"),
(status = 404, description = "Payment Method not found for the customer")
),
tag = "Payment Methods",
operation_id = "Set the Payment Method as Default",
security(("ephemeral_key" = []))
)]
pub async fn default_payment_method_set_api() {}
/// Payment Method - Create Intent
///
/// Creates a payment method for customer with billing information and other metadata.
#[utoipa::path(
post,
path = "/v2/payment-methods/create-intent",
request_body(
content = PaymentMethodIntentCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_intent_api() {}
/// Payment Method - Confirm Intent
///
/// Update a payment method with customer's payment method related information.
#[utoipa::path(
post,
path = "/v2/payment-methods/{id}/confirm-intent",
request_body(
content = PaymentMethodIntentConfirm,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Confirmed", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Confirm Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn confirm_payment_method_intent_api() {}
/// Payment Method - Create
///
/// Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/v2/payment-methods",
request_body(
content = PaymentMethodCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_api() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Retrieve Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
#[utoipa::path(
patch,
path = "/v2/payment-methods/{id}/update-saved-payment-method",
request_body(
content = PaymentMethodUpdate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Update", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Update Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Delete Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_delete_api() {}
/// Payment Method - List Customer Saved Payment Methods
///
/// List the payment methods saved for a customer
#[utoipa::path(
get,
path = "/v2/customers/{id}/saved-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the customer"),
),
responses(
(status = 200, description = "Payment Methods Retrieved", body = CustomerPaymentMethodsListResponse),
(status = 404, description = "Customer Not Found"),
),
tag = "Payment Methods",
operation_id = "List Customer Saved Payment Methods",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn list_customer_payment_method_api() {}
/// Payment Method Session - Create
///
/// Create a payment method session for a customer
/// This is used to list the saved payment methods for the customer
/// The customer can also add a new payment method using this session
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/payment-method-sessions",
request_body(
content = PaymentMethodSessionRequest,
examples (( "Create a payment method session with customer_id" = (
value =json!( {
"customer_id": "12345_cus_abcdefghijklmnopqrstuvwxyz"
})
)))
),
responses(
(status = 200, description = "Create the payment method session", body = PaymentMethodSessionResponse),
(status = 400, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Create a payment method session",
security(("api_key" = []))
)]
pub fn payment_method_session_create() {}
/// Payment Method Session - Retrieve
///
/// Retrieve the payment method session
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodSessionResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Retrieve the payment method session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_retrieve() {}
/// Payment Method Session - List Payment Methods
///
/// List payment methods for the given payment method session.
/// This endpoint lists the enabled payment methods for the profile and the saved payment methods of the customer.
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}/list-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponseForSession),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "List Payment methods for a Payment Method Session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_list_payment_methods() {}
/// Payment Method Session - Update a saved payment method
///
/// Update a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/payment-method-sessions/{id}/update-saved-payment-method",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionUpdateSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
"payment_method_data": {
"card": {
"card_holder_name": "Narayan Bhat"
}
}
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Update a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_update_saved_payment_method() {}
/// Payment Method Session - Delete a saved payment method
///
/// Delete a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionDeleteSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodDeleteResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Delete a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_delete_saved_payment_method() {}
/// Card network tokenization - Create using raw card data
///
/// Create a card network token for a customer and store it as a payment method.
/// This API expects raw card details for creating a network token with the card networks.
#[utoipa::path(
post,
path = "/payment_methods/tokenize-card",
request_body = CardNetworkTokenizeRequest,
responses(
(status = 200, description = "Payment Method Created", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_api() {}
/// Card network tokenization - Create using existing payment method
///
/// Create a card network token for a customer for an existing payment method.
/// This API expects an existing payment method ID for a card.
#[utoipa::path(
post,
path = "/payment_methods/{id}/tokenize-card",
request_body = CardNetworkTokenizeRequest,
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Updated", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token using Payment Method ID",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_using_pm_api() {}
/// Payment Method Session - Confirm a payment method session
///
/// **Confirms a payment method session object with the payment method data**
#[utoipa::path(
post,
path = "/v2/payment-method-sessions/{id}/confirm",
params (("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentMethodSessionConfirmRequest,
examples(
(
"Confirm the payment method session with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment Method created", body = PaymentMethodResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payment Method Session",
operation_id = "Confirm the payment method session",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payment_method_session_confirm() {}
| crates/openapi/src/routes/payment_method.rs | openapi | full_file | 5,082 | null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/worldpay.rs
Public structs: 1
mod requests;
mod response;
pub mod transformers;
use std::sync::LazyLock;
use api_models::{payments::PaymentIdType, webhooks::IncomingWebhookEvent};
use common_enums::{enums, PaymentAction};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundExecuteRouterData,
RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, PaymentsVoidType, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::Mask;
use requests::{
WorldpayCompleteAuthorizationRequest, WorldpayPartialRequest, WorldpayPaymentsRequest,
};
use response::{
EventType, ResponseIdStr, WorldpayErrorResponse, WorldpayEventResponse,
WorldpayPaymentsResponse, WorldpayWebhookEventType, WorldpayWebhookTransactionId,
WP_CORRELATION_ID,
};
use ring::hmac;
use self::transformers as worldpay;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
convert_amount, get_header_key_value, is_mandate_supported, ForeignTryFrom,
PaymentMethodDataType, RefundsRequestData,
},
};
#[derive(Clone)]
pub struct Worldpay {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Worldpay {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![
(
headers::ACCEPT.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(headers::WP_API_VERSION.to_string(), "2024-06-01".into()),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut api_key);
Ok(headers)
}
}
impl ConnectorCommon for Worldpay {
fn id(&self) -> &'static str {
"worldpay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.worldpay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = worldpay::WorldpayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response = if !res.response.is_empty() {
res.response
.parse_struct("WorldpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
} else {
WorldpayErrorResponse::default(res.status_code)
};
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_name,
message: response.message,
reason: response.validation_errors.map(|e| e.to_string()),
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Worldpay {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
is_mandate_supported(pm_data.clone(), pm_type, mandate_supported_pmd, self.id())
}
fn is_webhook_source_verification_mandatory(&self) -> bool {
true
}
}
impl api::Payment for Worldpay {}
impl api::MandateSetup for Worldpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Worldpay
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let auth = worldpay::WorldpayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let connector_router_data = worldpay::WorldpayRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.minor_amount.unwrap_or_default(),
req,
))?;
let connector_req =
WorldpayPaymentsRequest::try_from((&connector_router_data, &auth.entity_id))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::SetupMandateType::get_headers(self, req, connectors)?)
.set_body(types::SetupMandateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
optional_correlation_id,
data.request.amount.unwrap_or(0),
))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentToken for Worldpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Worldpay
{
// Not Implemented (R)
}
impl api::PaymentVoid for Worldpay {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Worldpay {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}api/payments/{}/cancellations",
self.base_url(connectors),
urlencoding::encode(&connector_payment_id),
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError>
where
Void: Clone,
PaymentsCancelData: Clone,
PaymentsResponseData: Clone,
{
match res.status_code {
202 => {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
Ok(PaymentsCancelRouterData {
status: enums::AttemptStatus::from(response.outcome.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::foreign_try_from((
response,
Some(data.request.connector_transaction_id.clone()),
))?,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: optional_correlation_id,
incremental_authorization_allowed: None,
charges: None,
}),
..data.clone()
})
}
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::ConnectorAccessToken for Worldpay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Worldpay {}
impl api::PaymentSync for Worldpay {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Worldpay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}api/payments/{}",
self.base_url(connectors),
urlencoding::encode(&connector_payment_id),
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response = if !res.response.is_empty() {
res.response
.parse_struct("WorldpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
} else {
WorldpayErrorResponse::default(res.status_code)
};
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_name,
message: response.message,
reason: response.validation_errors.map(|e| e.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: WorldpayEventResponse =
res.response
.parse_struct("Worldpay EventResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
let attempt_status = data.status;
let worldpay_status = response.last_event;
let status = match (attempt_status, worldpay_status.clone()) {
(
enums::AttemptStatus::Authorizing
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::CaptureInitiated
| enums::AttemptStatus::Charged
| enums::AttemptStatus::Pending
| enums::AttemptStatus::VoidInitiated,
EventType::Authorized,
) => attempt_status,
_ => enums::AttemptStatus::from(&worldpay_status),
};
Ok(PaymentsSyncRouterData {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: data.request.connector_transaction_id.clone(),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: optional_correlation_id,
incremental_authorization_allowed: None,
charges: None,
}),
..data.clone()
})
}
}
impl api::PaymentCapture for Worldpay {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Worldpay {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}api/payments/{}/partialSettlements",
self.base_url(connectors),
urlencoding::encode(&connector_payment_id),
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_to_capture = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_req = WorldpayPartialRequest::try_from((req, amount_to_capture))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
match res.status_code {
202 => {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
Ok(PaymentsCaptureRouterData {
status: enums::AttemptStatus::from(response.outcome.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::foreign_try_from((
response,
Some(data.request.connector_transaction_id.clone()),
))?,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: optional_correlation_id,
incremental_authorization_allowed: None,
charges: None,
}),
..data.clone()
})
}
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentSession for Worldpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Worldpay {}
impl api::PaymentAuthorize for Worldpay {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Worldpay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = worldpay::WorldpayRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.minor_amount,
req,
))?;
let auth = worldpay::WorldpayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let connector_req =
WorldpayPaymentsRequest::try_from((&connector_router_data, &auth.entity_id))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
optional_correlation_id,
data.request.amount,
))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentsCompleteAuthorize for Worldpay {}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Worldpay
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
let stage = match req.status {
enums::AttemptStatus::DeviceDataCollectionPending => "3dsDeviceData".to_string(),
enums::AttemptStatus::AuthenticationPending => "3dsChallenges".to_string(),
_ => {
return Err(
errors::ConnectorError::RequestEncodingFailedWithReason(format!(
"Invalid payment status for complete authorize: {:?}",
req.status
))
.into(),
);
}
};
Ok(format!(
"{}api/payments/{connector_payment_id}/{stage}",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = WorldpayCompleteAuthorizationRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("WorldpayPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
optional_correlation_id,
data.request.amount,
))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Worldpay {}
impl api::RefundExecute for Worldpay {}
impl api::RefundSync for Worldpay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Worldpay {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &RefundExecuteRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_to_refund = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_req = WorldpayPartialRequest::try_from((req, amount_to_refund))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}api/payments/{}/partialRefunds",
self.base_url(connectors),
urlencoding::encode(&connector_payment_id),
))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
match res.status_code {
202 => {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
Ok(RefundExecuteRouterData {
response: Ok(RefundsResponseData {
refund_status: enums::RefundStatus::from(response.outcome.clone()),
connector_refund_id: ResponseIdStr::foreign_try_from((
response,
optional_correlation_id,
))?
.id,
}),
..data.clone()
})
}
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Worldpay {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}api/payments/{}",
self.base_url(connectors),
urlencoding::encode(&req.request.get_connector_refund_id()?),
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: WorldpayEventResponse =
res.response
.parse_struct("Worldpay EventResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(RefundSyncRouterData {
response: Ok(RefundsResponseData {
connector_refund_id: data.request.refund_id.clone(),
refund_status: enums::RefundStatus::from(response.last_event),
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Worldpay {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Sha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let mut event_signature =
get_header_key_value("Event-Signature", request.headers)?.split(',');
let sign_header = event_signature
.next_back()
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
let signature = sign_header
.split('/')
.next_back() | crates/hyperswitch_connectors/src/connectors/worldpay.rs#chunk0 | hyperswitch_connectors | chunk | 8,190 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl auth_service::AuthServiceExchangeToken for Plaid {} | crates/pm_auth/src/connector/plaid.rs | pm_auth | impl_block | 11 | rust | null | Plaid | auth_service::AuthServiceExchangeToken for | impl auth_service::AuthServiceExchangeToken for for Plaid | null | null | null | null | null | null | null | null |
pub struct PaymentMethodListResponseForSession {
/// The list of payment methods that are enabled for the business profile
pub payment_methods_enabled: Vec<ResponsePaymentMethodTypes>,
/// The list of saved payment methods of the customer
pub customer_payment_methods: Vec<CustomerPaymentMethodResponseItem>,
} | crates/api_models/src/payment_methods.rs | api_models | struct_definition | 63 | rust | PaymentMethodListResponseForSession | null | null | null | null | null | null | null | null | null | null | null |
pub struct ShippingAddress {
address: Option<Address>,
name: Option<ShippingName>,
} | crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs | hyperswitch_connectors | struct_definition | 20 | rust | ShippingAddress | null | null | null | null | null | null | null | null | null | null | null |
pub struct RequestExtendedAuthorizationBool(bool); | crates/common_types/src/primitive_wrappers.rs | common_types | struct_definition | 8 | rust | RequestExtendedAuthorizationBool | null | null | null | null | null | null | null | null | null | null | null |
pub struct SignifydPaymentsCheckoutRequest {
checkout_id: String,
order_id: String,
purchase: Purchase,
coverage_requests: Option<CoverageRequests>,
} | crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs | hyperswitch_connectors | struct_definition | 37 | rust | SignifydPaymentsCheckoutRequest | null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorValidation for Opennode {} | crates/hyperswitch_connectors/src/connectors/opennode.rs | hyperswitch_connectors | impl_block | 8 | rust | null | Opennode | ConnectorValidation for | impl ConnectorValidation for for Opennode | null | null | null | null | null | null | null | null |
impl AuthEventMetricsAccumulator {
pub fn collect(self) -> AuthEventMetricsBucketValue {
AuthEventMetricsBucketValue {
authentication_count: self.authentication_count.collect(),
authentication_attempt_count: self.authentication_attempt_count.collect(),
authentication_success_count: self.authentication_success_count.collect(),
challenge_flow_count: self.challenge_flow_count.collect(),
challenge_attempt_count: self.challenge_attempt_count.collect(),
challenge_success_count: self.challenge_success_count.collect(),
frictionless_flow_count: self.frictionless_flow_count.collect(),
frictionless_success_count: self.frictionless_success_count.collect(),
error_message_count: self.authentication_error_message.collect(),
authentication_funnel: self.authentication_funnel.collect(),
authentication_exemption_approved_count: self
.authentication_exemption_approved_count
.collect(),
authentication_exemption_requested_count: self
.authentication_exemption_requested_count
.collect(),
}
}
} | crates/analytics/src/auth_events/accumulator.rs | analytics | impl_block | 192 | rust | null | AuthEventMetricsAccumulator | null | impl AuthEventMetricsAccumulator | null | null | null | null | null | null | null | null |
impl EliminationRoutingAlgorithm {
pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
self.enabled_feature = feature_to_enable
}
} | crates/api_models/src/routing.rs | api_models | impl_block | 37 | rust | null | EliminationRoutingAlgorithm | null | impl EliminationRoutingAlgorithm | null | null | null | null | null | null | null | null |
pub async fn get_action_url(
state: SessionState,
user_from_token: auth::UserFromToken,
request: api::ActionUrlRequest,
_req_state: ReqState,
) -> RouterResponse<api::ActionUrlResponse> {
utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id)
.await?;
let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf);
let tracking_id =
utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector)
.await?;
match (is_enabled, request.connector) {
(Some(true), enums::Connector::Paypal) => {
let action_url = Box::pin(paypal::get_action_url_from_paypal(
state,
tracking_id,
request.return_url,
))
.await?;
Ok(ApplicationResponse::Json(api::ActionUrlResponse::PayPal(
api::PayPalActionUrlResponse { action_url },
)))
}
_ => Err(ApiErrorResponse::FlowNotSupported {
flow: "Connector onboarding".to_string(),
connector: request.connector.to_string(),
}
.into()),
}
} | crates/router/src/core/connector_onboarding.rs | router | function_signature | 272 | rust | null | null | null | null | get_action_url | null | null | null | null | null | null | null |
pub fn payment_method_session_list_payment_methods() {} | crates/openapi/src/routes/payment_method.rs | openapi | function_signature | 10 | rust | null | null | null | null | payment_method_session_list_payment_methods | null | null | null | null | null | null | null |
File: crates/euclid/src/backend/interpreter/types.rs
Public structs: 2
use std::{collections::HashMap, fmt, ops::Deref, string::ToString};
use serde::Serialize;
use crate::{backend::inputs, frontend::ast::ValueType, types::EuclidKey};
#[derive(Debug, Clone, Serialize, thiserror::Error)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum InterpreterErrorType {
#[error("Invalid key received '{0}'")]
InvalidKey(String),
#[error("Invalid Comparison")]
InvalidComparison,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
pub struct InterpreterError {
pub error_type: InterpreterErrorType,
pub metadata: HashMap<String, serde_json::Value>,
}
impl fmt::Display for InterpreterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
InterpreterErrorType::fmt(&self.error_type, f)
}
}
pub struct Context(HashMap<String, Option<ValueType>>);
impl Deref for Context {
type Target = HashMap<String, Option<ValueType>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<inputs::BackendInput> for Context {
fn from(input: inputs::BackendInput) -> Self {
let ctx = HashMap::<String, Option<ValueType>>::from_iter([
(
EuclidKey::PaymentMethod.to_string(),
input
.payment_method
.payment_method
.map(|pm| ValueType::EnumVariant(pm.to_string())),
),
(
EuclidKey::PaymentMethodType.to_string(),
input
.payment_method
.payment_method_type
.map(|pt| ValueType::EnumVariant(pt.to_string())),
),
(
EuclidKey::AuthenticationType.to_string(),
input
.payment
.authentication_type
.map(|at| ValueType::EnumVariant(at.to_string())),
),
(
EuclidKey::CaptureMethod.to_string(),
input
.payment
.capture_method
.map(|cm| ValueType::EnumVariant(cm.to_string())),
),
(
EuclidKey::PaymentAmount.to_string(),
Some(ValueType::Number(input.payment.amount)),
),
(
EuclidKey::PaymentCurrency.to_string(),
Some(ValueType::EnumVariant(input.payment.currency.to_string())),
),
]);
Self(ctx)
}
}
| crates/euclid/src/backend/interpreter/types.rs | euclid | full_file | 527 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct AccessTokenAuthenticationResponse {
pub code: Secret<String>,
pub expires: i64,
} | crates/hyperswitch_domain_models/src/router_data.rs | hyperswitch_domain_models | struct_definition | 22 | rust | AccessTokenAuthenticationResponse | null | null | null | null | null | null | null | null | null | null | null |
pub async fn send_request(
client_proxy: &Proxy,
request: Request,
option_timeout_secs: Option<u64>,
) -> CustomResult<reqwest::Response, HttpClientError> {
logger::info!(method=?request.method, headers=?request.headers, payload=?request.body, ?request);
let url = url::Url::parse(&request.url).change_context(HttpClientError::UrlParsingFailed)?;
let client = client::create_client(
client_proxy,
request.certificate,
request.certificate_key,
request.ca_certificate,
)?;
let headers = request.headers.construct_header_map()?;
let metrics_tag = router_env::metric_attributes!((
consts::METRICS_HOST_TAG_NAME,
url.host_str().unwrap_or_default().to_owned()
));
let request = {
match request.method {
Method::Get => client.get(url),
Method::Post => {
let client = client.post(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData(form)) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(HttpClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Put => {
let client = client.put(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData(form)) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(HttpClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Patch => {
let client = client.patch(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData(form)) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(HttpClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Delete => client.delete(url),
}
.add_headers(headers)
.timeout(Duration::from_secs(
option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT),
))
};
// We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here.
let cloned_send_request = request.try_clone().map(|cloned_request| async {
cloned_request
.send()
.await
.map_err(|error| match error {
error if error.is_timeout() => {
metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);
HttpClientError::RequestTimeoutReceived
}
error if is_connection_closed_before_message_could_complete(&error) => {
metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);
HttpClientError::ConnectionClosedIncompleteMessage
}
_ => HttpClientError::RequestNotSent(error.to_string()),
})
.attach_printable("Unable to send request to connector")
});
let send_request = async {
request
.send()
.await
.map_err(|error| match error {
error if error.is_timeout() => {
metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);
HttpClientError::RequestTimeoutReceived
}
error if is_connection_closed_before_message_could_complete(&error) => {
metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);
HttpClientError::ConnectionClosedIncompleteMessage
}
_ => HttpClientError::RequestNotSent(error.to_string()),
})
.attach_printable("Unable to send request to connector")
};
let response = common_utils::metrics::utils::record_operation_time(
send_request,
&metrics::EXTERNAL_REQUEST_TIME,
metrics_tag,
)
.await;
// Retry once if the response is connection closed.
//
// This is just due to the racy nature of networking.
// hyper has a connection pool of idle connections, and it selected one to send your request.
// Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool.
// But occasionally, a connection will be selected from the pool
// and written to at the same time the server is deciding to close the connection.
// Since hyper already wrote some of the request,
// it can’t really retry it automatically on a new connection, since the server may have acted already
match response {
Ok(response) => Ok(response),
Err(error)
if error.current_context() == &HttpClientError::ConnectionClosedIncompleteMessage =>
{
metrics::AUTO_RETRY_CONNECTION_CLOSED.add(1, metrics_tag);
match cloned_send_request {
Some(cloned_request) => {
logger::info!(
"Retrying request due to connection closed before message could complete"
);
common_utils::metrics::utils::record_operation_time(
cloned_request,
&metrics::EXTERNAL_REQUEST_TIME,
metrics_tag,
)
.await
}
None => {
logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable");
Err(error)
}
}
}
err @ Err(_) => err,
}
} | crates/external_services/src/http_client.rs | external_services | function_signature | 1,278 | rust | null | null | null | null | send_request | null | null | null | null | null | null | null |
File: crates/hyperswitch_interfaces/src/api/refunds.rs
//! Refunds interface
use hyperswitch_domain_models::{
router_flow_types::{Execute, RSync},
router_request_types::RefundsData,
router_response_types::RefundsResponseData,
};
use crate::api::{self, ConnectorCommon};
/// trait RefundExecute
pub trait RefundExecute:
api::ConnectorIntegration<Execute, RefundsData, RefundsResponseData>
{
}
/// trait RefundSync
pub trait RefundSync: api::ConnectorIntegration<RSync, RefundsData, RefundsResponseData> {}
/// trait Refund
pub trait Refund: ConnectorCommon + RefundExecute + RefundSync {}
| crates/hyperswitch_interfaces/src/api/refunds.rs | hyperswitch_interfaces | full_file | 147 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentToken for Gocardless {} | crates/hyperswitch_connectors/src/connectors/gocardless.rs | hyperswitch_connectors | impl_block | 10 | rust | null | Gocardless | api::PaymentToken for | impl api::PaymentToken for for Gocardless | null | null | null | null | null | null | null | null |
impl RefundExecute for Wellsfargo {} | crates/hyperswitch_connectors/src/connectors/wellsfargo.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Wellsfargo | RefundExecute for | impl RefundExecute for for Wellsfargo | null | null | null | null | null | null | null | null |
pub fn spawn_async_lineage_context_update_to_db(
state: &SessionState,
user_id: &str,
lineage_context: LineageContext,
) {
let state = state.clone();
let lineage_context = lineage_context.clone();
let user_id = user_id.to_owned();
tokio::spawn(async move {
match state
.global_store
.update_user_by_user_id(
&user_id,
diesel_models::user::UserUpdate::LineageContextUpdate { lineage_context },
)
.await
{
Ok(_) => {
logger::debug!("Successfully updated lineage context for user {}", user_id);
}
Err(e) => {
logger::error!(
"Failed to update lineage context for user {}: {:?}",
user_id,
e
);
}
}
});
} | crates/router/src/utils/user.rs | router | function_signature | 178 | rust | null | null | null | null | spawn_async_lineage_context_update_to_db | null | null | null | null | null | null | null |
pub fn get_dummy_connector_id(self) -> &'static str {
match self {
Self::PhonyPay => "phonypay",
Self::FauxPay => "fauxpay",
Self::PretendPay => "pretendpay",
Self::StripeTest => "stripe_test",
Self::AdyenTest => "adyen_test",
Self::CheckoutTest => "checkout_test",
Self::PaypalTest => "paypal_test",
}
} | crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs | hyperswitch_connectors | function_signature | 101 | rust | null | null | null | null | get_dummy_connector_id | null | null | null | null | null | null | null |
impl GetCaptureMethod for PaymentsAuthorizeData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
} | crates/hyperswitch_connectors/src/connectors/aci/transformers.rs | hyperswitch_connectors | impl_block | 34 | rust | null | PaymentsAuthorizeData | GetCaptureMethod for | impl GetCaptureMethod for for PaymentsAuthorizeData | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
Public functions: 1
Public structs: 42
use common_utils::{
ext_traits::Encode,
types::{MinorUnit, StringMinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, RouterData,
},
router_flow_types::{
refunds::{Execute, RSync},
Dsync, Fetch, Retrieve, Upload,
},
router_request_types::{
DisputeSyncData, FetchDisputesRequestData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsSyncData, ResponseId,
RetrieveFileRequestData, SetupMandateRequestData, UploadFileRequestData,
},
router_response_types::{
DisputeSyncResponse, FetchDisputesResponse, MandateReference, PaymentsResponseData,
RefundsResponseData, RetrieveFileResponse, UploadFileResponse,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
AcceptDisputeRouterData, DisputeSyncRouterData, FetchDisputeRouterData,
RefundsResponseRouterData, ResponseRouterData, RetrieveFileRouterData,
SubmitEvidenceRouterData,
},
utils::{
self as connector_utils, CardData, PaymentsAuthorizeRequestData,
PaymentsSetupMandateRequestData, RouterData as UtilsRouterData,
},
};
pub mod worldpayvantiv_constants {
pub const WORLDPAYVANTIV_VERSION: &str = "12.23";
pub const XML_VERSION: &str = "1.0";
pub const XML_ENCODING: &str = "UTF-8";
pub const XMLNS: &str = "http://www.vantivcnp.com/schema";
pub const MAX_PAYMENT_REFERENCE_ID_LENGTH: usize = 28;
pub const XML_STANDALONE: &str = "yes";
pub const XML_CHARGEBACK: &str = "http://www.vantivcnp.com/chargebacks";
pub const MAC_FIELD_NUMBER: &str = "39";
pub const CUSTOMER_ID_MAX_LENGTH: usize = 50;
pub const CUSTOMER_REFERENCE_MAX_LENGTH: usize = 17;
}
pub struct WorldpayvantivRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for WorldpayvantivRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct WorldpayvantivAuthType {
pub(super) user: Secret<String>,
pub(super) password: Secret<String>,
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WorldpayvantivAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1,
} => Ok(Self {
user: api_key.to_owned(),
password: api_secret.to_owned(),
merchant_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, strum::Display, Serialize, Deserialize, PartialEq, Clone, Copy)]
#[strum(serialize_all = "lowercase")]
pub enum OperationId {
Sale,
Auth,
Capture,
Void,
// VoidPostCapture
VoidPC,
Refund,
}
// Represents the payment metadata for Worldpay Vantiv.
// The `report_group` field is an Option<String> to account for cases where the report group might not be provided in the metadata.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorldpayvantivPaymentMetadata {
pub report_group: Option<String>,
}
// Represents the merchant connector account metadata for Worldpay Vantiv
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorldpayvantivMetadataObject {
pub report_group: String,
pub merchant_config_currency: common_enums::Currency,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for WorldpayvantivMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata = connector_utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize)]
#[serde(rename = "cnpOnlineRequest", rename_all = "camelCase")]
pub struct CnpOnlineRequest {
#[serde(rename = "@version")]
pub version: String,
#[serde(rename = "@xmlns")]
pub xmlns: String,
#[serde(rename = "@merchantId")]
pub merchant_id: Secret<String>,
pub authentication: Authentication,
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization: Option<Authorization>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sale: Option<Sale>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture: Option<Capture>,
#[serde(skip_serializing_if = "Option::is_none")]
pub auth_reversal: Option<AuthReversal>,
#[serde(skip_serializing_if = "Option::is_none")]
pub void: Option<Void>,
#[serde(skip_serializing_if = "Option::is_none")]
pub credit: Option<RefundRequest>,
}
#[derive(Debug, Serialize)]
pub struct Authentication {
pub user: Secret<String>,
pub password: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Void {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
pub cnp_txn_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthReversal {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
pub cnp_txn_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Capture {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
pub cnp_txn_id: String,
pub amount: MinorUnit,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VantivAddressData {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_line1: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_line2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_line3: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub zip: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<common_utils::pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<common_enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum VantivProcessingType {
InitialCOF,
MerchantInitiatedCOF,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Authorization {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
#[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
pub order_id: String,
pub amount: MinorUnit,
pub order_source: OrderSource,
#[serde(skip_serializing_if = "Option::is_none")]
pub bill_to_address: Option<VantivAddressData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ship_to_address: Option<VantivAddressData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<WorldpayvantivCardData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<TokenizationData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub enhanced_data: Option<EnhancedData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_type: Option<VantivProcessingType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub original_network_transaction_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_partial_auth: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cardholder_authentication: Option<CardholderAuthentication>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardholderAuthentication {
authentication_value: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Sale {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
#[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
pub order_id: String,
pub amount: MinorUnit,
pub order_source: OrderSource,
#[serde(skip_serializing_if = "Option::is_none")]
pub bill_to_address: Option<VantivAddressData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ship_to_address: Option<VantivAddressData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<WorldpayvantivCardData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<TokenizationData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub enhanced_data: Option<EnhancedData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_type: Option<VantivProcessingType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub original_network_transaction_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_partial_auth: Option<bool>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnhancedData {
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_reference: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sales_tax: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_exempt: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub discount_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub duty_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ship_from_postal_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub destination_postal_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub destination_country_code: Option<common_enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
pub detail_tax: Option<DetailTax>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line_item_data: Option<Vec<LineItemData>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DetailTax {
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_included_in_total: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_acceptor_tax_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LineItemData {
#[serde(skip_serializing_if = "Option::is_none")]
pub item_sequence_number: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub quantity: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit_of_measure: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line_item_total: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line_item_total_with_tax: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_discount_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commodity_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit_cost: Option<MinorUnit>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundRequest {
#[serde(rename = "@reportGroup")]
pub report_group: String,
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
pub cnp_txn_id: String,
pub amount: MinorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum OrderSource {
Ecommerce,
ApplePay,
MailOrder,
Telephone,
AndroidPay,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizationData {
cnp_token: Secret<String>,
exp_date: Secret<String>,
}
#[derive(Debug)]
struct VantivMandateDetail {
processing_type: Option<VantivProcessingType>,
network_transaction_id: Option<Secret<String>>,
token: Option<TokenizationData>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayvantivCardData {
#[serde(rename = "type")]
pub card_type: WorldpayvativCardType,
pub number: cards::CardNumber,
pub exp_date: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_validation_num: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
pub enum WorldpayvativCardType {
#[serde(rename = "VI")]
Visa,
#[serde(rename = "MC")]
MasterCard,
#[serde(rename = "AX")]
AmericanExpress,
#[serde(rename = "DI")]
Discover,
#[serde(rename = "DC")]
DinersClub,
#[serde(rename = "JC")]
JCB,
#[serde(rename = "")]
UnionPay,
}
#[derive(Debug, Clone, Serialize, strum::EnumString)]
pub enum WorldPayVativApplePayNetwork {
Visa,
MasterCard,
AmEx,
Discover,
DinersClub,
JCB,
UnionPay,
}
impl From<WorldPayVativApplePayNetwork> for WorldpayvativCardType {
fn from(network: WorldPayVativApplePayNetwork) -> Self {
match network {
WorldPayVativApplePayNetwork::Visa => Self::Visa,
WorldPayVativApplePayNetwork::MasterCard => Self::MasterCard,
WorldPayVativApplePayNetwork::AmEx => Self::AmericanExpress,
WorldPayVativApplePayNetwork::Discover => Self::Discover,
WorldPayVativApplePayNetwork::DinersClub => Self::DinersClub,
WorldPayVativApplePayNetwork::JCB => Self::JCB,
WorldPayVativApplePayNetwork::UnionPay => Self::UnionPay,
}
}
}
#[derive(Debug, Clone, Serialize, strum::EnumString)]
#[serde(rename_all = "UPPERCASE")]
#[strum(ascii_case_insensitive)]
pub enum WorldPayVativGooglePayNetwork {
Visa,
Mastercard,
Amex,
Discover,
Dinersclub,
Jcb,
Unionpay,
}
impl From<WorldPayVativGooglePayNetwork> for WorldpayvativCardType {
fn from(network: WorldPayVativGooglePayNetwork) -> Self {
match network {
WorldPayVativGooglePayNetwork::Visa => Self::Visa,
WorldPayVativGooglePayNetwork::Mastercard => Self::MasterCard,
WorldPayVativGooglePayNetwork::Amex => Self::AmericanExpress,
WorldPayVativGooglePayNetwork::Discover => Self::Discover,
WorldPayVativGooglePayNetwork::Dinersclub => Self::DinersClub,
WorldPayVativGooglePayNetwork::Jcb => Self::JCB,
WorldPayVativGooglePayNetwork::Unionpay => Self::UnionPay,
}
}
}
impl TryFrom<common_enums::CardNetwork> for WorldpayvativCardType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(card_network: common_enums::CardNetwork) -> Result<Self, Self::Error> {
match card_network {
common_enums::CardNetwork::Visa => Ok(Self::Visa),
common_enums::CardNetwork::Mastercard => Ok(Self::MasterCard),
common_enums::CardNetwork::AmericanExpress => Ok(Self::AmericanExpress),
common_enums::CardNetwork::Discover => Ok(Self::Discover),
common_enums::CardNetwork::DinersClub => Ok(Self::DinersClub),
common_enums::CardNetwork::JCB => Ok(Self::JCB),
common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay),
_ => Err(errors::ConnectorError::NotSupported {
message: "Card network".to_string(),
connector: "worldpayvantiv",
}
.into()),
}
}
}
impl TryFrom<&connector_utils::CardIssuer> for WorldpayvativCardType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(card_issuer: &connector_utils::CardIssuer) -> Result<Self, Self::Error> {
match card_issuer {
connector_utils::CardIssuer::Visa => Ok(Self::Visa),
connector_utils::CardIssuer::Master => Ok(Self::MasterCard),
connector_utils::CardIssuer::AmericanExpress => Ok(Self::AmericanExpress),
connector_utils::CardIssuer::Discover => Ok(Self::Discover),
connector_utils::CardIssuer::DinersClub => Ok(Self::DinersClub),
connector_utils::CardIssuer::JCB => Ok(Self::JCB),
_ => Err(errors::ConnectorError::NotSupported {
message: "Card network".to_string(),
connector: "worldpayvantiv",
}
.into()),
}
}
}
impl<F> TryFrom<ResponseRouterData<F, VantivSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VantivSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = determine_attempt_status(&item)?;
if connector_utils::is_payment_failure(status) {
let error_code = item
.response
.payment_detail
.as_ref()
.and_then(|detail| detail.response_reason_code.clone())
.unwrap_or(consts::NO_ERROR_CODE.to_string());
let error_message = item
.response
.payment_detail
.as_ref()
.and_then(|detail| detail.response_reason_message.clone())
.unwrap_or(item.response.payment_status.to_string());
let connector_transaction_id = item
.response
.payment_detail
.as_ref()
.and_then(|detail| detail.payment_id.map(|id| id.to_string()));
Ok(Self {
status,
response: Err(ErrorResponse {
code: error_code.clone(),
message: error_message.clone(),
reason: Some(error_message.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
} else {
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
fn get_bill_to_address<T>(item: &T) -> Option<VantivAddressData>
where
T: UtilsRouterData,
{
let billing_address = item.get_optional_billing();
billing_address.and_then(|billing_address| {
billing_address
.address
.clone()
.map(|address| VantivAddressData {
name: address.get_optional_full_name(),
address_line1: item.get_optional_billing_line1(),
address_line2: item.get_optional_billing_line2(),
address_line3: item.get_optional_billing_line3(),
city: item.get_optional_billing_city(),
state: item.get_optional_billing_state(),
zip: item.get_optional_billing_zip(),
email: item.get_optional_billing_email(),
country: item.get_optional_billing_country(),
phone: item.get_optional_billing_phone_number(),
})
})
}
fn extract_customer_id<T>(item: &T) -> Option<String>
where
T: UtilsRouterData,
{
item.get_optional_customer_id().and_then(|customer_id| {
let customer_id_str = customer_id.get_string_repr().to_string();
if customer_id_str.len() <= worldpayvantiv_constants::CUSTOMER_ID_MAX_LENGTH {
Some(customer_id_str)
} else {
None
}
})
}
fn get_valid_transaction_id(
id: String,
error_field_name: &str,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
if id.len() <= worldpayvantiv_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH {
Ok(id.clone())
} else {
Err(errors::ConnectorError::MaxFieldLengthViolated {
connector: "Worldpayvantiv".to_string(),
field_name: error_field_name.to_string(),
max_length: worldpayvantiv_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH,
received_length: id.len(),
}
.into())
}
}
fn get_ship_to_address<T>(item: &T) -> Option<VantivAddressData>
where
T: UtilsRouterData,
{
let shipping_address = item.get_optional_shipping();
shipping_address.and_then(|shipping_address| {
shipping_address
.address
.clone()
.map(|address| VantivAddressData {
name: address.get_optional_full_name(),
address_line1: item.get_optional_shipping_line1(),
address_line2: item.get_optional_shipping_line2(),
address_line3: item.get_optional_shipping_line3(),
city: item.get_optional_shipping_city(),
state: item.get_optional_shipping_state(),
zip: item.get_optional_shipping_zip(),
email: item.get_optional_shipping_email(),
country: item.get_optional_shipping_country(),
phone: item.get_optional_shipping_phone_number(),
})
})
}
impl TryFrom<&WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>> for CnpOnlineRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds()
&& matches!(
item.router_data.request.payment_method_data,
PaymentMethodData::Card(_)
)
{
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Worldpayvantiv",
})?
}
let worldpayvantiv_metadata =
WorldpayvantivMetadataObject::try_from(&item.router_data.connector_meta_data)?;
if worldpayvantiv_metadata.merchant_config_currency != item.router_data.request.currency {
Err(errors::ConnectorError::CurrencyNotSupported {
message: item.router_data.request.currency.to_string(),
connector: "Worldpayvantiv",
})?
};
let (card, cardholder_authentication) = get_vantiv_card_data(
&item.router_data.request.payment_method_data,
item.router_data.payment_method_token.clone(),
)?;
let report_group = item
.router_data
.request
.metadata
.clone()
.map(|payment_metadata| {
connector_utils::to_connector_meta::<WorldpayvantivPaymentMetadata>(Some(
payment_metadata,
))
})
.transpose()?
.and_then(|worldpayvantiv_metadata| worldpayvantiv_metadata.report_group)
.unwrap_or(worldpayvantiv_metadata.report_group);
let worldpayvantiv_auth_type =
WorldpayvantivAuthType::try_from(&item.router_data.connector_auth_type)?;
let authentication = Authentication {
user: worldpayvantiv_auth_type.user,
password: worldpayvantiv_auth_type.password,
};
let customer_id = extract_customer_id(item.router_data);
let bill_to_address = get_bill_to_address(item.router_data);
let ship_to_address = get_ship_to_address(item.router_data);
let processing_info = get_processing_info(&item.router_data.request)?;
let enhanced_data = get_enhanced_data(item.router_data)?;
let order_source = OrderSource::from((
item.router_data.request.payment_method_data.clone(),
item.router_data.request.payment_channel.clone(),
));
let (authorization, sale) =
if item.router_data.request.is_auto_capture()? && item.amount != MinorUnit::zero() {
let merchant_txn_id = get_valid_transaction_id(
item.router_data.connector_request_reference_id.clone(),
"sale.id",
)?;
(
None,
Some(Sale {
id: format!("{}_{merchant_txn_id}", OperationId::Sale),
report_group: report_group.clone(),
customer_id,
order_id: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
order_source,
bill_to_address,
ship_to_address,
card: card.clone(),
token: processing_info.token,
processing_type: processing_info.processing_type,
original_network_transaction_id: processing_info.network_transaction_id,
enhanced_data,
allow_partial_auth: item
.router_data
.request
.enable_partial_authorization
.and_then(|enable_partial_authorization| {
enable_partial_authorization.then_some(true)
}),
}),
)
} else {
let operation_id = if item.router_data.request.is_auto_capture()? {
OperationId::Sale
} else {
OperationId::Auth
};
let merchant_txn_id = get_valid_transaction_id(
item.router_data.connector_request_reference_id.clone(),
"authorization.id",
)?;
(
Some(Authorization {
id: format!("{operation_id}_{merchant_txn_id}"),
report_group: report_group.clone(),
customer_id,
order_id: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
order_source,
bill_to_address,
ship_to_address,
card: card.clone(),
token: processing_info.token,
processing_type: processing_info.processing_type,
original_network_transaction_id: processing_info.network_transaction_id,
cardholder_authentication,
enhanced_data,
allow_partial_auth: item
.router_data
.request
.enable_partial_authorization
.and_then(|enable_partial_authorization| {
enable_partial_authorization.then_some(true)
}),
}),
None,
)
};
Ok(Self {
version: worldpayvantiv_constants::WORLDPAYVANTIV_VERSION.to_string(),
xmlns: worldpayvantiv_constants::XMLNS.to_string(),
merchant_id: worldpayvantiv_auth_type.merchant_id,
authentication,
authorization,
sale,
capture: None,
auth_reversal: None,
credit: None,
void: None,
})
}
}
impl TryFrom<&SetupMandateRouterData> for CnpOnlineRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
if item.is_three_ds()
&& matches!(item.request.payment_method_data, PaymentMethodData::Card(_))
{
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Worldpayvantiv",
})?
}
let worldpayvantiv_metadata =
WorldpayvantivMetadataObject::try_from(&item.connector_meta_data)?;
if worldpayvantiv_metadata.merchant_config_currency != item.request.currency {
Err(errors::ConnectorError::CurrencyNotSupported {
message: item.request.currency.to_string(),
connector: "Worldpayvantiv",
})?
};
let (card, cardholder_authentication) = get_vantiv_card_data(
&item.request.payment_method_data,
item.payment_method_token.clone(),
)?;
let report_group = item
.request
.metadata
.clone()
.map(|payment_metadata| {
connector_utils::to_connector_meta::<WorldpayvantivPaymentMetadata>(Some(
payment_metadata.expose(),
))
})
.transpose()?
.and_then(|worldpayvantiv_metadata| worldpayvantiv_metadata.report_group)
.unwrap_or(worldpayvantiv_metadata.report_group);
let worldpayvantiv_auth_type = WorldpayvantivAuthType::try_from(&item.connector_auth_type)?;
let authentication = Authentication {
user: worldpayvantiv_auth_type.user,
password: worldpayvantiv_auth_type.password,
};
let customer_id = extract_customer_id(item);
let bill_to_address = get_bill_to_address(item);
let ship_to_address = get_ship_to_address(item);
let processing_type = if item.request.is_customer_initiated_mandate_payment() {
Some(VantivProcessingType::InitialCOF)
} else {
None
};
let enhanced_data = get_enhanced_data(item)?;
let order_source = OrderSource::from((
item.request.payment_method_data.clone(),
item.request.payment_channel.clone(),
));
let merchant_txn_id = get_valid_transaction_id(
item.connector_request_reference_id.clone(),
"authorization.id",
)?;
let authorization_data = Authorization {
id: format!("{}_{merchant_txn_id}", OperationId::Sale),
report_group: report_group.clone(),
customer_id,
order_id: item.connector_request_reference_id.clone(),
amount: MinorUnit::zero(),
order_source,
bill_to_address,
ship_to_address,
card: card.clone(),
token: None,
processing_type,
original_network_transaction_id: None,
cardholder_authentication,
enhanced_data,
allow_partial_auth: item.request.enable_partial_authorization.and_then(
|enable_partial_authorization| enable_partial_authorization.then_some(true),
),
};
Ok(Self {
version: worldpayvantiv_constants::WORLDPAYVANTIV_VERSION.to_string(),
xmlns: worldpayvantiv_constants::XMLNS.to_string(),
merchant_id: worldpayvantiv_auth_type.merchant_id,
authentication,
authorization: Some(authorization_data),
sale: None,
capture: None,
auth_reversal: None,
credit: None,
void: None,
})
}
}
impl From<(PaymentMethodData, Option<common_enums::PaymentChannel>)> for OrderSource {
fn from(
(payment_method_data, payment_channel): (
PaymentMethodData,
Option<common_enums::PaymentChannel>,
),
) -> Self {
if let PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::ApplePay(_),
) = &payment_method_data
{
return Self::ApplePay;
}
if let PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(_),
) = &payment_method_data
{
return Self::AndroidPay;
}
match payment_channel {
Some(common_enums::PaymentChannel::Ecommerce)
| Some(common_enums::PaymentChannel::Other(_))
| None => Self::Ecommerce,
Some(common_enums::PaymentChannel::MailOrder) => Self::MailOrder,
Some(common_enums::PaymentChannel::TelephoneOrder) => Self::Telephone,
}
}
}
fn get_enhanced_data<T>(
item: &T,
) -> Result<Option<EnhancedData>, error_stack::Report<errors::ConnectorError>>
where
T: UtilsRouterData,
{
let l2_l3_data = item.get_optional_l2_l3_data();
if let Some(l2_l3_data) = l2_l3_data {
let line_item_data = l2_l3_data.order_details.as_ref().map(|order_details| {
order_details
.iter()
.enumerate()
.map(|(i, order)| LineItemData {
item_sequence_number: Some((i + 1).to_string()),
item_description: order
.description
.as_ref()
.map(|desc| desc.chars().take(19).collect::<String>()),
product_code: order.product_id.clone(),
quantity: Some(order.quantity.to_string().clone()),
unit_of_measure: order.unit_of_measure.clone(),
tax_amount: order.total_tax_amount,
line_item_total: Some(order.amount),
line_item_total_with_tax: order.total_tax_amount.map(|tax| tax + order.amount),
item_discount_amount: order.unit_discount_amount,
commodity_code: order.commodity_code.clone(),
unit_cost: Some(order.amount),
})
.collect()
});
let tax_exempt = match l2_l3_data.tax_status {
Some(common_enums::TaxStatus::Exempt) => Some(true),
Some(common_enums::TaxStatus::Taxable) => Some(false),
None => None,
};
let customer_reference =
get_vantiv_customer_reference(&l2_l3_data.merchant_order_reference_id);
let detail_tax: Option<DetailTax> = if l2_l3_data.merchant_tax_registration_id.is_some()
&& l2_l3_data.order_details.is_some()
{
Some(DetailTax {
tax_included_in_total: match tax_exempt {
Some(false) => Some(true),
Some(true) | None => Some(false),
},
card_acceptor_tax_id: l2_l3_data.merchant_tax_registration_id.clone(),
tax_amount: l2_l3_data.order_details.as_ref().map(|orders| {
orders
.iter()
.filter_map(|order| order.total_tax_amount)
.fold(MinorUnit::zero(), |acc, tax| acc + tax)
}),
})
} else {
None
};
let enhanced_data = EnhancedData {
customer_reference,
sales_tax: l2_l3_data.order_tax_amount,
tax_exempt,
discount_amount: l2_l3_data.discount_amount,
shipping_amount: l2_l3_data.shipping_cost,
duty_amount: l2_l3_data.duty_amount,
ship_from_postal_code: l2_l3_data.shipping_origin_zip, | crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs#chunk0 | hyperswitch_connectors | chunk | 8,179 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl Responder {
Box::pin(oss_api::server_wrap(
Flow::RoutingRetrieveDefaultConfig,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
routing::retrieve_default_routing_config(
state,
auth.profile_id,
merchant_context,
transaction_type,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/routing.rs | router | impl_block | 181 | rust | null | Responder | null | impl Responder | null | null | null | null | null | null | null | null |
impl Trustpayments {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
} | crates/hyperswitch_connectors/src/connectors/trustpayments.rs | hyperswitch_connectors | impl_block | 34 | rust | null | Trustpayments | null | impl Trustpayments | null | null | null | null | null | null | null | null |
/// The Applicative trait provides a pure behavior,
/// which can be used to create values of type f a from values of type a.
pub trait Applicative<R> {
/// The Associative type acts as a (f a) wrapper for Self.
type WrappedSelf<T>;
/// Applicative::pure(_) is abstraction with lifts any arbitrary type to underlying higher
/// order type
fn pure(v: R) -> Self::WrappedSelf<R>;
} | crates/common_utils/src/fp_utils.rs | common_utils | trait_definition | 96 | rust | null | null | Applicative | null | null | null | null | null | null | null | null | null |
impl Permission {
pub fn scope(&self) -> PermissionScope {
match self {
#(#scope_impl_per),*
}
}
pub fn entity_type(&self) -> EntityType {
match self {
#(#entity_impl_per),*
}
}
pub fn resource(&self) -> Resource {
match self {
#(#resource_impl_per),*
}
}
} | crates/router_derive/src/macros/generate_permissions.rs | router_derive | impl_block | 85 | rust | null | Permission | null | impl Permission | null | null | null | null | null | null | null | null |
pub async fn organization_update() {} | crates/openapi/src/routes/organization.rs | openapi | function_signature | 7 | rust | null | null | null | null | organization_update | null | null | null | null | null | null | null |
pub struct TwoFactorAuthStatusResponseWithAttempts {
pub totp: TwoFactorAuthAttempts,
pub recovery_code: TwoFactorAuthAttempts,
} | crates/api_models/src/user.rs | api_models | struct_definition | 31 | rust | TwoFactorAuthStatusResponseWithAttempts | null | null | null | null | null | null | null | null | null | null | null |
impl EmailToken {
pub async fn new_token(
email: domain::UserEmail,
entity: Option<Entity>,
flow: domain::Origin,
settings: &configs::Settings,
) -> UserResult<String> {
let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(expiration_duration)?.as_secs();
let token_payload = Self {
email: email.get_secret().expose(),
flow,
exp,
entity,
};
jwt::generate_jwt(&token_payload, settings).await
}
pub fn get_email(&self) -> UserResult<domain::UserEmail> {
pii::Email::try_from(self.email.clone())
.change_context(UserErrors::InternalServerError)
.and_then(domain::UserEmail::from_pii_email)
}
pub fn get_entity(&self) -> Option<&Entity> {
self.entity.as_ref()
}
pub fn get_flow(&self) -> domain::Origin {
self.flow.clone()
}
} | crates/router/src/services/email/types.rs | router | impl_block | 226 | rust | null | EmailToken | null | impl EmailToken | null | null | null | null | null | null | null | null |
pub fn is_invitable(&self) -> bool {
self.is_invitable
} | crates/router/src/services/authorization/roles.rs | router | function_signature | 19 | rust | null | null | null | null | is_invitable | null | null | null | null | null | null | null |
pub struct CardDetail {
/// Card Number
#[schema(value_type = String,example = "4111111145551142")]
pub card_number: CardNumber,
/// Card Expiry Month
#[schema(value_type = String,example = "10")]
pub card_exp_month: masking::Secret<String>,
/// Card Expiry Year
#[schema(value_type = String,example = "25")]
pub card_exp_year: masking::Secret<String>,
/// Card Holder Name
#[schema(value_type = String,example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>,example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
/// Card Issuing Country
#[schema(value_type = CountryAlpha2)]
pub card_issuing_country: Option<api_enums::CountryAlpha2>,
/// Card's Network
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<api_enums::CardNetwork>,
/// Issuer Bank for Card
pub card_issuer: Option<String>,
/// Card Type
pub card_type: Option<CardType>,
/// The CVC number for the card
/// This is optional in case the card needs to be vaulted
#[schema(value_type = String, example = "242")]
pub card_cvc: Option<masking::Secret<String>>,
} | crates/api_models/src/payment_methods.rs | api_models | struct_definition | 340 | rust | CardDetail | null | null | null | null | null | null | null | null | null | null | null |
pub struct Mandate {
scheme: GocardlessScheme,
metadata: MandateMetaData,
payer_ip_address: Option<Secret<String, IpAddress>>,
links: MandateLink,
} | crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs | hyperswitch_connectors | struct_definition | 41 | rust | Mandate | null | null | null | null | null | null | null | null | null | null | null |
pub fn is_us_local_network(&self) -> bool {
match self {
Self::Star | Self::Pulse | Self::Accel | Self::Nyce => true,
Self::Interac
| Self::CartesBancaires
| Self::Visa
| Self::Mastercard
| Self::AmericanExpress
| Self::JCB
| Self::DinersClub
| Self::Discover
| Self::UnionPay
| Self::RuPay
| Self::Maestro => false,
}
} | crates/common_enums/src/enums.rs | common_enums | function_signature | 123 | rust | null | null | null | null | is_us_local_network | null | null | null | null | null | null | null |
File: crates/test_utils/tests/connectors/aci_ui.rs
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AciSeleniumTest;
impl SeleniumTest for AciSeleniumTest {
fn get_connector_name(&self) -> String {
"aci".to_string()
}
}
async fn should_make_aci_card_mandate_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/180"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_alipay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/213"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("submit-success"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_interac_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/14"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input[value='Continue payment']"))),
Event::Trigger(Trigger::Click(By::Css("input[value='Confirm']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/208"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-middle"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/211"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input.pps-button"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/212"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/209"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Name("sc"), "10")),
Event::Trigger(Trigger::SendKeys(By::Name("extensionSc"), "4000")),
Event::Trigger(Trigger::SendKeys(By::Name("customerName1"), "Hopper")),
Event::Trigger(Trigger::Click(By::Css("input[value='Absenden']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_trustly_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/13"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::XPath(
r#"//*[@id="app"]/div[1]/div/div[2]/div/ul/div[4]/div/div[1]/div[2]/div[1]/span"#,
))),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"123456789",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"783213",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::Click(By::Css("div.sc-jJMGnK.laKGqb"))),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"355508",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_przelewy24_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/12"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("pf31"))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-lg.btn-info.btn-block",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-success.btn-lg.accept-button",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_aci_card_mandate_payment_test() {
tester!(should_make_aci_card_mandate_payment);
}
#[test]
#[serial]
fn should_make_aci_alipay_payment_test() {
tester!(should_make_aci_alipay_payment);
}
#[test]
#[serial]
fn should_make_aci_interac_payment_test() {
tester!(should_make_aci_interac_payment);
}
#[test]
#[serial]
fn should_make_aci_eps_payment_test() {
tester!(should_make_aci_eps_payment);
}
#[test]
#[serial]
fn should_make_aci_ideal_payment_test() {
tester!(should_make_aci_ideal_payment);
}
#[test]
#[serial]
fn should_make_aci_sofort_payment_test() {
tester!(should_make_aci_sofort_payment);
}
#[test]
#[serial]
fn should_make_aci_giropay_payment_test() {
tester!(should_make_aci_giropay_payment);
}
#[test]
#[serial]
fn should_make_aci_trustly_payment_test() {
tester!(should_make_aci_trustly_payment);
}
#[test]
#[serial]
fn should_make_aci_przelewy24_payment_test() {
tester!(should_make_aci_przelewy24_payment);
}
| crates/test_utils/tests/connectors/aci_ui.rs | test_utils | full_file | 2,248 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn get_id(&self) -> &id_type::GlobalPaymentId {
self.payment_id
} | crates/router/src/services/kafka/payment_intent_event.rs | router | function_signature | 23 | rust | null | null | null | null | get_id | null | null | null | null | null | null | null |
impl RedisTokenManager {
/// Lock connector customer
#[instrument(skip_all)]
pub async fn lock_connector_customer_status(
state: &SessionState,
connector_customer_id: &str,
payment_id: &id_type::GlobalPaymentId,
) -> CustomResult<bool, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let lock_key = format!("customer:{connector_customer_id}:status");
let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;
let result: bool = match redis_conn
.set_key_if_not_exists_with_expiry(
&lock_key.into(),
payment_id.get_string_repr(),
Some(*seconds),
)
.await
{
Ok(resp) => resp == SetnxReply::KeySet,
Err(error) => {
tracing::error!(operation = "lock_stream", err = ?error);
false
}
};
tracing::debug!(
connector_customer_id = connector_customer_id,
payment_id = payment_id.get_string_repr(),
lock_acquired = %result,
"Connector customer lock attempt"
);
Ok(result)
}
/// Unlock connector customer status
#[instrument(skip_all)]
pub async fn unlock_connector_customer_status(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let lock_key = format!("customer:{connector_customer_id}:status");
match redis_conn.delete_key(&lock_key.into()).await {
Ok(DelReply::KeyDeleted) => {
tracing::debug!(
connector_customer_id = connector_customer_id,
"Connector customer unlocked"
);
Ok(true)
}
Ok(DelReply::KeyNotDeleted) => {
tracing::debug!("Tried to unlock a stream which is already unlocked");
Ok(false)
}
Err(err) => {
tracing::error!(?err, "Failed to delete lock key");
Ok(false)
}
}
}
/// Get all payment processor tokens for a connector customer
#[instrument(skip_all)]
pub async fn get_connector_customer_payment_processor_tokens(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let tokens_key = format!("customer:{connector_customer_id}:tokens");
let get_hash_err =
errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());
let payment_processor_tokens: HashMap<String, String> = redis_conn
.get_hash_fields(&tokens_key.into())
.await
.change_context(get_hash_err)?;
// build the result map using iterator adapters (explicit match preserved for logging)
let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =
payment_processor_tokens
.into_iter()
.filter_map(|(token_id, token_data)| {
match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {
Ok(token_status) => Some((token_id, token_status)),
Err(err) => {
tracing::warn!(
connector_customer_id = %connector_customer_id,
token_id = %token_id,
error = %err,
"Failed to deserialize token data, skipping",
);
None
}
}
})
.collect();
tracing::debug!(
connector_customer_id = connector_customer_id,
"Fetched payment processor tokens",
);
Ok(payment_processor_token_info_map)
}
/// Update connector customer payment processor tokens or add if doesn't exist
#[instrument(skip_all)]
pub async fn update_or_add_connector_customer_payment_processor_tokens(
state: &SessionState,
connector_customer_id: &str,
payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,
) -> CustomResult<(), errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let tokens_key = format!("customer:{connector_customer_id}:tokens");
// allocate capacity up-front to avoid rehashing
let mut serialized_payment_processor_tokens: HashMap<String, String> =
HashMap::with_capacity(payment_processor_token_info_map.len());
// serialize all tokens, preserving explicit error handling and attachable diagnostics
for (payment_processor_token_id, payment_processor_token_status) in
payment_processor_token_info_map
{
let serialized = serde_json::to_string(&payment_processor_token_status)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed to serialize token status")?;
serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);
}
let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;
// Update or add tokens
redis_conn
.set_hash_fields(
&tokens_key.into(),
serialized_payment_processor_tokens,
Some(*seconds),
)
.await
.change_context(errors::StorageError::RedisError(
errors::RedisError::SetHashFieldFailed.into(),
))?;
tracing::info!(
connector_customer_id = %connector_customer_id,
"Successfully updated or added customer tokens",
);
Ok(())
}
/// Get current date in `yyyy-mm-dd` format.
pub fn get_current_date() -> String {
let today = date_time::now().date();
let (year, month, day) = (today.year(), today.month(), today.day());
format!("{year:04}-{month:02}-{day:02}",)
}
/// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).
pub fn normalize_retry_window(
payment_processor_token: &mut PaymentProcessorTokenStatus,
today: Date,
) {
let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();
for days_ago in 0..RETRY_WINDOW_DAYS {
let date = today - Duration::days(days_ago.into());
payment_processor_token
.daily_retry_history
.get(&date)
.map(|&retry_count| {
normalized_retry_history.insert(date, retry_count);
});
}
payment_processor_token.daily_retry_history = normalized_retry_history;
}
/// Get all payment processor tokens with retry information and wait times.
pub fn get_tokens_with_retry_metadata(
state: &SessionState,
payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,
) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {
let today = OffsetDateTime::now_utc().date();
let card_config = &state.conf.revenue_recovery.card_config;
let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =
HashMap::with_capacity(payment_processor_token_info_map.len());
for (payment_processor_token_id, payment_processor_token_status) in
payment_processor_token_info_map.iter()
{
let card_network = payment_processor_token_status
.payment_processor_token_details
.card_network
.clone();
// Calculate retry information.
let retry_info = Self::payment_processor_token_retry_info(
state,
payment_processor_token_status,
today,
card_network.clone(),
);
// Determine the wait time (max of monthly and daily wait hours).
let retry_wait_time_hours = retry_info
.monthly_wait_hours
.max(retry_info.daily_wait_hours);
// Obtain network-specific limits and compute remaining monthly retries.
let card_network_config = card_config.get_network_config(card_network);
let monthly_retry_remaining = card_network_config
.max_retry_count_for_thirty_day
.saturating_sub(retry_info.total_30_day_retries);
// Build the per-token result struct.
let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {
token_status: payment_processor_token_status.clone(),
retry_wait_time_hours,
monthly_retry_remaining,
};
result.insert(payment_processor_token_id.clone(), token_with_retry_info);
}
tracing::debug!("Fetched payment processor tokens with retry metadata",);
result
}
/// Sum retries over exactly the last 30 days
fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {
(0..RETRY_WINDOW_DAYS)
.map(|i| {
let date = today - Duration::days(i.into());
token
.daily_retry_history
.get(&date)
.copied()
.unwrap_or(INITIAL_RETRY_COUNT)
})
.sum()
}
/// Calculate wait hours
fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {
let expiry_time = target_date.midnight().assume_utc();
(expiry_time - now).whole_hours().max(0)
}
/// Calculate retry counts for exactly the last 30 days
pub fn payment_processor_token_retry_info(
state: &SessionState,
token: &PaymentProcessorTokenStatus,
today: Date,
network_type: Option<CardNetwork>,
) -> TokenRetryInfo {
let card_config = &state.conf.revenue_recovery.card_config;
let card_network_config = card_config.get_network_config(network_type);
let now = OffsetDateTime::now_utc();
let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);
let monthly_wait_hours =
if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {
(0..RETRY_WINDOW_DAYS)
.map(|i| today - Duration::days(i.into()))
.find(|date| token.daily_retry_history.get(date).copied().unwrap_or(0) > 0)
.map(|date| Self::calculate_wait_hours(date + Duration::days(31), now))
.unwrap_or(0)
} else {
0
};
let today_retries = token
.daily_retry_history
.get(&today)
.copied()
.unwrap_or(INITIAL_RETRY_COUNT);
let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {
Self::calculate_wait_hours(today + Duration::days(1), now)
} else {
0
};
TokenRetryInfo {
monthly_wait_hours,
daily_wait_hours,
total_30_day_retries,
}
}
// Upsert payment processor token
#[instrument(skip_all)]
pub async fn upsert_payment_processor_token(
state: &SessionState,
connector_customer_id: &str,
token_data: PaymentProcessorTokenStatus,
) -> CustomResult<bool, errors::StorageError> {
let mut token_map =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let token_id = token_data
.payment_processor_token_details
.payment_processor_token
.clone();
let was_existing = token_map.contains_key(&token_id);
let error_code = token_data.error_code.clone();
let today = OffsetDateTime::now_utc().date();
token_map
.get_mut(&token_id)
.map(|existing_token| {
error_code.map(|err| existing_token.error_code = Some(err));
Self::normalize_retry_window(existing_token, today);
for (date, &value) in &token_data.daily_retry_history {
existing_token
.daily_retry_history
.entry(*date)
.and_modify(|v| *v += value)
.or_insert(value);
}
})
.or_else(|| {
token_map.insert(token_id.clone(), token_data);
None
});
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
token_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Upsert payment processor tokens",
);
Ok(!was_existing)
}
// Update payment processor token error code with billing connector response
#[instrument(skip_all)]
pub async fn update_payment_processor_token_error_code_from_process_tracker(
state: &SessionState,
connector_customer_id: &str,
error_code: &Option<String>,
is_hard_decline: &Option<bool>,
payment_processor_token_id: Option<&str>,
) -> CustomResult<bool, errors::StorageError> {
let today = OffsetDateTime::now_utc().date();
let updated_token = match payment_processor_token_id {
Some(token_id) => {
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?
.values()
.find(|status| {
status
.payment_processor_token_details
.payment_processor_token
== token_id
})
.map(|status| PaymentProcessorTokenStatus {
payment_processor_token_details: status
.payment_processor_token_details
.clone(),
inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),
error_code: error_code.clone(),
daily_retry_history: status.daily_retry_history.clone(),
scheduled_at: None,
is_hard_decline: *is_hard_decline,
})
}
None => None,
};
match updated_token {
Some(mut token) => {
Self::normalize_retry_window(&mut token, today);
match token.error_code {
None => token.daily_retry_history.clear(),
Some(_) => {
let current_count = token
.daily_retry_history
.get(&today)
.copied()
.unwrap_or(INITIAL_RETRY_COUNT);
token.daily_retry_history.insert(today, current_count + 1);
}
}
let mut tokens_map = HashMap::new();
tokens_map.insert(
token
.payment_processor_token_details
.payment_processor_token
.clone(),
token.clone(),
);
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
tokens_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Updated payment processor tokens with error code",
);
Ok(true)
}
None => {
tracing::debug!(
connector_customer_id = connector_customer_id,
"No Token found with token id to update error code",
);
Ok(false)
}
}
}
// Update payment processor token schedule time
#[instrument(skip_all)]
pub async fn update_payment_processor_token_schedule_time(
state: &SessionState,
connector_customer_id: &str,
payment_processor_token: &str,
schedule_time: Option<PrimitiveDateTime>,
) -> CustomResult<bool, errors::StorageError> {
let updated_token =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?
.values()
.find(|status| {
status
.payment_processor_token_details
.payment_processor_token
== payment_processor_token
})
.map(|status| PaymentProcessorTokenStatus {
payment_processor_token_details: status.payment_processor_token_details.clone(),
inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),
error_code: status.error_code.clone(),
daily_retry_history: status.daily_retry_history.clone(),
scheduled_at: schedule_time,
is_hard_decline: status.is_hard_decline,
});
match updated_token {
Some(token) => {
let mut tokens_map = HashMap::new();
tokens_map.insert(
token
.payment_processor_token_details
.payment_processor_token
.clone(),
token.clone(),
);
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
tokens_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Updated payment processor tokens with schedule time",
);
Ok(true)
}
None => {
tracing::debug!(
connector_customer_id = connector_customer_id,
"payment processor tokens with not found",
);
Ok(false)
}
}
}
// Get payment processor token with schedule time
#[instrument(skip_all)]
pub async fn get_payment_processor_token_with_schedule_time(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {
let tokens =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let scheduled_token = tokens
.values()
.find(|status| status.scheduled_at.is_some())
.cloned();
tracing::debug!(
connector_customer_id = connector_customer_id,
"Fetched payment processor token with schedule time",
);
Ok(scheduled_token)
}
// Get payment processor token using token id
#[instrument(skip_all)]
pub async fn get_payment_processor_token_using_token_id(
state: &SessionState,
connector_customer_id: &str,
payment_processor_token: &str,
) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {
// Get all tokens for the customer
let tokens_map =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let token_details = tokens_map.get(payment_processor_token).cloned();
tracing::debug!(
token_found = token_details.is_some(),
customer_id = connector_customer_id,
"Fetched payment processor token & Checked existence ",
);
Ok(token_details)
}
// Check if all tokens are hard declined or no token found for the customer
#[instrument(skip_all)]
pub async fn are_all_tokens_hard_declined(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let tokens_map =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let all_hard_declined = tokens_map
.values()
.all(|token| token.is_hard_decline.unwrap_or(false));
tracing::debug!(
connector_customer_id = connector_customer_id,
all_hard_declined,
"Checked if all tokens are hard declined or no token found for the customer",
);
Ok(all_hard_declined)
}
// Get token based on retry type
pub async fn get_token_based_on_retry_type(
state: &SessionState,
connector_customer_id: &str,
retry_algorithm_type: RevenueRecoveryAlgorithmType,
last_token_used: Option<&str>,
) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {
let mut token = None;
match retry_algorithm_type {
RevenueRecoveryAlgorithmType::Monitoring => {
logger::error!("Monitoring type found for Revenue Recovery retry payment");
}
RevenueRecoveryAlgorithmType::Cascading => {
token = match last_token_used {
Some(token_id) => {
Self::get_payment_processor_token_using_token_id(
state,
connector_customer_id,
token_id,
)
.await?
}
None => None,
};
}
RevenueRecoveryAlgorithmType::Smart => {
token = Self::get_payment_processor_token_with_schedule_time(
state,
connector_customer_id,
)
.await?;
}
}
token = token.and_then(|t| {
t.is_hard_decline
.unwrap_or(false)
.then(|| {
logger::error!("Token is hard declined");
})
.map_or(Some(t), |_| None)
});
Ok(token)
}
} | crates/router/src/types/storage/revenue_recovery_redis_operation.rs | router | impl_block | 4,321 | rust | null | RedisTokenManager | null | impl RedisTokenManager | null | null | null | null | null | null | null | null |
pub struct CountAccumulator {
pub count: Option<i64>,
} | crates/analytics/src/refunds/accumulator.rs | analytics | struct_definition | 17 | rust | CountAccumulator | null | null | null | null | null | null | null | null | null | null | null |
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.payment_attempts.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Opensearch Payment Attempts index must not be empty".into(),
))
})?;
when(self.payment_intents.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Opensearch Payment Intents index must not be empty".into(),
))
})?;
when(self.refunds.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Opensearch Refunds index must not be empty".into(),
))
})?;
when(self.disputes.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Opensearch Disputes index must not be empty".into(),
))
})?;
when(
self.sessionizer_payment_attempts.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Opensearch Sessionizer Payment Attempts index must not be empty".into(),
))
},
)?;
when(
self.sessionizer_payment_intents.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Opensearch Sessionizer Payment Intents index must not be empty".into(),
))
},
)?;
when(self.sessionizer_refunds.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Opensearch Sessionizer Refunds index must not be empty".into(),
))
})?;
when(self.sessionizer_disputes.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Opensearch Sessionizer Disputes index must not be empty".into(),
))
})?;
Ok(())
} | crates/analytics/src/opensearch.rs | analytics | function_signature | 404 | rust | null | null | null | null | validate | null | null | null | null | null | null | null |
impl api::Payment for Custombilling {} | crates/hyperswitch_connectors/src/connectors/custombilling.rs | hyperswitch_connectors | impl_block | 8 | rust | null | Custombilling | api::Payment for | impl api::Payment for for Custombilling | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
Public structs: 29
// Core related api layer.
#[derive(Debug, Clone)]
pub struct Authorize;
#[derive(Debug, Clone)]
pub struct AuthorizeSessionToken;
#[derive(Debug, Clone)]
pub struct CompleteAuthorize;
#[derive(Debug, Clone)]
pub struct Approve;
// Used in gift cards balance check
#[derive(Debug, Clone)]
pub struct Balance;
#[derive(Debug, Clone)]
pub struct InitPayment;
#[derive(Debug, Clone)]
pub struct Capture;
#[derive(Debug, Clone)]
pub struct PSync;
#[derive(Debug, Clone)]
pub struct Void;
#[derive(Debug, Clone)]
pub struct PostCaptureVoid;
#[derive(Debug, Clone)]
pub struct Reject;
#[derive(Debug, Clone)]
pub struct Session;
#[derive(Debug, Clone)]
pub struct PaymentMethodToken;
#[derive(Debug, Clone)]
pub struct CreateConnectorCustomer;
#[derive(Debug, Clone)]
pub struct SetupMandate;
#[derive(Debug, Clone)]
pub struct PreProcessing;
#[derive(Debug, Clone)]
pub struct IncrementalAuthorization;
#[derive(Debug, Clone)]
pub struct PostProcessing;
#[derive(Debug, Clone)]
pub struct CalculateTax;
#[derive(Debug, Clone)]
pub struct SdkSessionUpdate;
#[derive(Debug, Clone)]
pub struct PaymentCreateIntent;
#[derive(Debug, Clone)]
pub struct PaymentGetIntent;
#[derive(Debug, Clone)]
pub struct PaymentUpdateIntent;
#[derive(Debug, Clone)]
pub struct PostSessionTokens;
#[derive(Debug, Clone)]
pub struct RecordAttempt;
#[derive(Debug, Clone)]
pub struct UpdateMetadata;
#[derive(Debug, Clone)]
pub struct CreateOrder;
#[derive(Debug, Clone)]
pub struct PaymentGetListAttempts;
#[derive(Debug, Clone)]
pub struct ExternalVaultProxy;
| crates/hyperswitch_domain_models/src/router_flow_types/payments.rs | hyperswitch_domain_models | full_file | 369 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct StaxTokenResponse {
id: Secret<String>,
} | crates/hyperswitch_connectors/src/connectors/stax/transformers.rs | hyperswitch_connectors | struct_definition | 14 | rust | StaxTokenResponse | null | null | null | null | null | null | null | null | null | null | null |
pub fn extract_token_from_body(body: &[u8]) -> CustomResult<String, errors::ConnectorError> {
let parsed: serde_json::Value = serde_json::from_slice(body)
.map_err(|_| report!(errors::ConnectorError::ResponseDeserializationFailed))?;
parsed
.get("_links")
.and_then(|links| links.get("about"))
.and_then(|about| about.get("href"))
.and_then(|href| href.as_str())
.and_then(|url| url.rsplit('/').next())
.map(|id| id.to_string())
.ok_or_else(|| report!(errors::ConnectorError::ResponseHandlingFailed))
} | crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs | hyperswitch_connectors | function_signature | 144 | rust | null | null | null | null | extract_token_from_body | null | null | null | null | null | null | null |
pub(crate) fn get_dispute_stage(code: &str) -> Result<enums::DisputeStage, errors::ConnectorError> {
match code {
"CHARGEBACK" => Ok(enums::DisputeStage::Dispute),
"PRE_ARBITRATION" => Ok(enums::DisputeStage::PreArbitration),
"RETRIEVAL" => Ok(enums::DisputeStage::PreDispute),
_ => Err(errors::ConnectorError::WebhookBodyDecodingFailed),
}
} | crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs | hyperswitch_connectors | function_signature | 111 | rust | null | null | null | null | get_dispute_stage | null | null | null | null | null | null | null |
pub struct CompleteAuthorize; | crates/hyperswitch_domain_models/src/router_flow_types/payments.rs | hyperswitch_domain_models | struct_definition | 5 | rust | CompleteAuthorize | null | null | null | null | null | null | null | null | null | null | null |
pub struct FullyParsedGooglePayToken {
pub signature: Secret<String>,
pub protocol_version: String,
pub encrypted_message: String,
pub ephemeral_public_key: String,
pub tag: String,
pub key_value: String,
pub key_expiration: String,
pub signatures: Vec<String>,
} | crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs | hyperswitch_connectors | struct_definition | 67 | rust | FullyParsedGooglePayToken | null | null | null | null | null | null | null | null | null | null | null |
/// uses the above rules and lowers the whole ast Program into DirProgram by specifying
/// default_selection that is ast ConnectorSelection, a vector of DirRules and clones the metadata
/// whatever comes in the ast_program
pub fn lower_program<O: EuclidDirFilter>(
program: ast::Program<O>,
) -> Result<dir::DirProgram<O>, AnalysisError> {
Ok(dir::DirProgram {
default_selection: program.default_selection,
rules: program
.rules
.into_iter()
.map(lower_rule)
.collect::<Result<_, _>>()?,
metadata: program.metadata,
})
} | crates/euclid/src/frontend/ast/lowering.rs | euclid | function_signature | 131 | rust | null | null | null | null | lower_program | null | null | null | null | null | null | null |
impl BizEmailProd {
pub fn new(
state: &SessionState,
data: ProdIntent,
theme_id: Option<String>,
theme_config: EmailThemeConfig,
) -> UserResult<Self> {
Ok(Self {
recipient_email: domain::UserEmail::from_pii_email(
state.conf.email.prod_intent_recipient_email.clone(),
)?,
settings: state.conf.clone(),
user_name: data.poc_name.unwrap_or_default(),
poc_email: data.poc_email.unwrap_or_default(),
legal_business_name: data.legal_business_name.unwrap_or_default(),
business_location: data
.business_location
.unwrap_or(common_enums::CountryAlpha2::AD)
.to_string(),
business_website: data.business_website.unwrap_or_default(),
theme_id,
theme_config,
product_type: data.product_type,
})
}
} | crates/router/src/services/email/types.rs | router | impl_block | 185 | rust | null | BizEmailProd | null | impl BizEmailProd | null | null | null | null | null | null | null | null |
impl ThreeDSRequestor {
pub fn new(
app_ip: Option<std::net::IpAddr>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
force_3ds_challenge: bool,
message_version: SemanticVersion,
) -> Self {
// if sca exemption is provided, we need to set the challenge indicator to NoChallengeRequestedTransactionalRiskAnalysis
let three_ds_requestor_challenge_ind = if force_3ds_challenge {
Some(SingleOrListElement::get_version_checked(
message_version,
ThreeDSRequestorChallengeIndicator::ChallengeRequestedMandate,
))
} else if let Some(common_enums::ScaExemptionType::TransactionRiskAnalysis) =
psd2_sca_exemption_type
{
Some(SingleOrListElement::get_version_checked(
message_version,
ThreeDSRequestorChallengeIndicator::NoChallengeRequestedTransactionalRiskAnalysis,
))
} else {
None
};
Self {
three_ds_requestor_authentication_ind: ThreeDSRequestorAuthenticationIndicator::Payment,
three_ds_requestor_authentication_info: None,
three_ds_requestor_challenge_ind,
three_ds_requestor_prior_authentication_info: None,
three_ds_requestor_dec_req_ind: None,
three_ds_requestor_dec_max_time: None,
app_ip,
three_ds_requestor_spc_support: None,
spc_incomp_ind: None,
}
}
} | crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs | hyperswitch_connectors | impl_block | 312 | rust | null | ThreeDSRequestor | null | impl ThreeDSRequestor | null | null | null | null | null | null | null | null |
pub fn to_storage_model(self) -> diesel_models::PaymentAttemptUpdate {
match self {
Self::Update {
net_amount,
currency,
status,
authentication_type,
payment_method,
payment_token,
payment_method_data,
payment_method_type,
payment_experience,
business_sub_label,
amount_to_capture,
capture_method,
fingerprint_id,
network_transaction_id,
payment_method_billing_address_id,
updated_by,
} => DieselPaymentAttemptUpdate::Update {
amount: net_amount.get_order_amount(),
currency,
status,
authentication_type,
payment_method,
payment_token,
payment_method_data,
payment_method_type,
payment_experience,
business_sub_label,
amount_to_capture,
capture_method,
surcharge_amount: net_amount.get_surcharge_amount(),
tax_amount: net_amount.get_tax_on_surcharge(),
fingerprint_id,
payment_method_billing_address_id,
network_transaction_id,
updated_by,
},
Self::UpdateTrackers {
payment_token,
connector,
straight_through_algorithm,
amount_capturable,
updated_by,
surcharge_amount,
tax_amount,
merchant_connector_id,
routing_approach,
} => DieselPaymentAttemptUpdate::UpdateTrackers {
payment_token,
connector,
straight_through_algorithm,
amount_capturable,
surcharge_amount,
tax_amount,
updated_by,
merchant_connector_id,
routing_approach: routing_approach.map(|approach| match approach {
storage_enums::RoutingApproach::Other(_) => {
// we need to make sure Other variant is not stored in DB, in the rare case
// where we attempt to store an unknown value, we default to the default value
storage_enums::RoutingApproach::default()
}
_ => approach,
}),
},
Self::AuthenticationTypeUpdate {
authentication_type,
updated_by,
} => DieselPaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
updated_by,
},
Self::BlocklistUpdate {
status,
error_code,
error_message,
updated_by,
} => DieselPaymentAttemptUpdate::BlocklistUpdate {
status,
error_code,
error_message,
updated_by,
},
Self::ConnectorMandateDetailUpdate {
connector_mandate_detail,
updated_by,
} => DieselPaymentAttemptUpdate::ConnectorMandateDetailUpdate {
connector_mandate_detail,
updated_by,
},
Self::PaymentMethodDetailsUpdate {
payment_method_id,
updated_by,
} => DieselPaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
updated_by,
},
Self::ConfirmUpdate {
net_amount,
currency,
status,
authentication_type,
capture_method,
payment_method,
browser_info,
connector,
payment_token,
payment_method_data,
payment_method_type,
payment_experience,
business_sub_label,
straight_through_algorithm,
error_code,
error_message,
fingerprint_id,
updated_by,
merchant_connector_id: connector_id,
payment_method_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
payment_method_billing_address_id,
client_source,
client_version,
customer_acceptance,
connector_mandate_detail,
card_discovery,
routing_approach,
connector_request_reference_id,
network_transaction_id,
} => DieselPaymentAttemptUpdate::ConfirmUpdate {
amount: net_amount.get_order_amount(),
currency,
status,
authentication_type,
capture_method,
payment_method,
browser_info,
connector,
payment_token,
payment_method_data,
payment_method_type,
payment_experience,
business_sub_label,
straight_through_algorithm,
error_code,
error_message,
surcharge_amount: net_amount.get_surcharge_amount(),
tax_amount: net_amount.get_tax_on_surcharge(),
fingerprint_id,
updated_by,
merchant_connector_id: connector_id,
payment_method_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
payment_method_billing_address_id,
client_source,
client_version,
customer_acceptance,
shipping_cost: net_amount.get_shipping_cost(),
order_tax_amount: net_amount.get_order_tax_amount(),
connector_mandate_detail,
card_discovery,
routing_approach: routing_approach.map(|approach| match approach {
// we need to make sure Other variant is not stored in DB, in the rare case
// where we attempt to store an unknown value, we default to the default value
storage_enums::RoutingApproach::Other(_) => {
storage_enums::RoutingApproach::default()
}
_ => approach,
}),
connector_request_reference_id,
network_transaction_id,
},
Self::VoidUpdate {
status,
cancellation_reason,
updated_by,
} => DieselPaymentAttemptUpdate::VoidUpdate {
status,
cancellation_reason,
updated_by,
},
Self::ResponseUpdate {
status,
connector,
connector_transaction_id,
authentication_type,
payment_method_id,
mandate_id,
connector_metadata,
payment_token,
error_code,
error_message,
error_reason,
connector_response_reference_id,
amount_capturable,
updated_by,
authentication_data,
encoded_data,
unified_code,
unified_message,
capture_before,
extended_authorization_applied,
payment_method_data,
connector_mandate_detail,
charges,
setup_future_usage_applied,
network_transaction_id,
debit_routing_savings: _,
} => DieselPaymentAttemptUpdate::ResponseUpdate {
status,
connector,
connector_transaction_id,
authentication_type,
payment_method_id,
mandate_id,
connector_metadata,
payment_token,
error_code,
error_message,
error_reason,
connector_response_reference_id,
amount_capturable,
updated_by,
authentication_data,
encoded_data,
unified_code,
unified_message,
capture_before,
extended_authorization_applied,
payment_method_data,
connector_mandate_detail,
charges,
setup_future_usage_applied,
network_transaction_id,
},
Self::UnresolvedResponseUpdate {
status,
connector,
connector_transaction_id,
payment_method_id,
error_code,
error_message,
error_reason,
connector_response_reference_id,
updated_by,
} => DieselPaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
connector,
connector_transaction_id,
payment_method_id,
error_code,
error_message,
error_reason,
connector_response_reference_id,
updated_by,
},
Self::StatusUpdate { status, updated_by } => {
DieselPaymentAttemptUpdate::StatusUpdate { status, updated_by }
}
Self::ErrorUpdate {
connector,
status,
error_code,
error_message,
error_reason,
amount_capturable,
updated_by,
unified_code,
unified_message,
connector_transaction_id,
payment_method_data,
authentication_type,
issuer_error_code,
issuer_error_message,
} => DieselPaymentAttemptUpdate::ErrorUpdate {
connector,
status,
error_code,
error_message,
error_reason,
amount_capturable,
updated_by,
unified_code,
unified_message,
connector_transaction_id,
payment_method_data,
authentication_type,
issuer_error_code,
issuer_error_message,
},
Self::CaptureUpdate {
multiple_capture_count,
updated_by,
amount_to_capture,
} => DieselPaymentAttemptUpdate::CaptureUpdate {
multiple_capture_count,
updated_by,
amount_to_capture,
},
Self::PreprocessingUpdate {
status,
payment_method_id,
connector_metadata,
preprocessing_step_id,
connector_transaction_id,
connector_response_reference_id,
updated_by,
} => DieselPaymentAttemptUpdate::PreprocessingUpdate {
status,
payment_method_id,
connector_metadata,
preprocessing_step_id,
connector_transaction_id,
connector_response_reference_id,
updated_by,
},
Self::RejectUpdate {
status,
error_code,
error_message,
updated_by,
} => DieselPaymentAttemptUpdate::RejectUpdate {
status,
error_code,
error_message,
updated_by,
},
Self::AmountToCaptureUpdate {
status,
amount_capturable,
updated_by,
} => DieselPaymentAttemptUpdate::AmountToCaptureUpdate {
status,
amount_capturable,
updated_by,
},
Self::ConnectorResponse {
authentication_data,
encoded_data,
connector_transaction_id,
connector,
charges,
updated_by,
} => DieselPaymentAttemptUpdate::ConnectorResponse {
authentication_data,
encoded_data,
connector_transaction_id,
charges,
connector,
updated_by,
},
Self::IncrementalAuthorizationAmountUpdate {
net_amount,
amount_capturable,
} => DieselPaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
amount: net_amount.get_order_amount(),
amount_capturable,
},
Self::AuthenticationUpdate {
status,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
updated_by,
} => DieselPaymentAttemptUpdate::AuthenticationUpdate {
status,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
updated_by,
},
Self::ManualUpdate {
status,
error_code,
error_message,
error_reason,
updated_by,
unified_code,
unified_message,
connector_transaction_id,
} => DieselPaymentAttemptUpdate::ManualUpdate {
status,
error_code,
error_message,
error_reason,
updated_by,
unified_code,
unified_message,
connector_transaction_id,
},
Self::PostSessionTokensUpdate {
updated_by,
connector_metadata,
} => DieselPaymentAttemptUpdate::PostSessionTokensUpdate {
updated_by,
connector_metadata,
},
}
} | crates/hyperswitch_domain_models/src/payments/payment_attempt.rs | hyperswitch_domain_models | function_signature | 2,119 | rust | null | null | null | null | to_storage_model | null | null | null | null | null | null | null |
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector
}
} | connector-template/mod.rs | connector-template | function_signature | 28 | rust | null | null | null | null | new | null | null | null | null | null | null | null |
impl Customers {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/customers").app_data(web::Data::new(state));
#[cfg(all(feature = "olap", feature = "v2"))]
{
route = route
.service(web::resource("/list").route(web::get().to(customers::customers_list)))
.service(
web::resource("/total-payment-methods")
.route(web::get().to(payment_methods::get_total_payment_method_count)),
)
.service(
web::resource("/{id}/saved-payment-methods")
.route(web::get().to(payment_methods::list_customer_payment_method_api)),
)
}
#[cfg(all(feature = "oltp", feature = "v2"))]
{
route = route
.service(web::resource("").route(web::post().to(customers::customers_create)))
.service(
web::resource("/{id}")
.route(web::put().to(customers::customers_update))
.route(web::get().to(customers::customers_retrieve))
.route(web::delete().to(customers::customers_delete)),
)
}
route
}
} | crates/router/src/routes/app.rs | router | impl_block | 259 | rust | null | Customers | null | impl Customers | null | null | null | null | null | null | null | null |
Documentation: api-reference/v2/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx
# Type: Doc File
---
openapi: put /v2/payment-method-sessions/{id}/update-saved-payment-method
---
| api-reference/v2/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx | null | doc_file | 50 | doc | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
Public functions: 1
Public structs: 20
use cards::CardNumber;
use common_enums::enums;
use common_utils::{
pii::{IpAddress, SecretSerdeValue},
request::Method,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
PaymentsAuthorizeData, PaymentsPreProcessingData, PaymentsSyncData, ResponseId,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsPreProcessingRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, BrowserInformationData, CardData, PaymentsAuthorizeRequestData,
PaymentsPreProcessingRequestData, RouterData as _,
},
};
pub struct PaysafeRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PaysafeRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PaysafeConnectorMetadataObject {
pub account_id: Secret<String>,
}
impl TryFrom<&Option<SecretSerdeValue>> for PaysafeConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentHandleRequest {
pub merchant_ref_num: String,
pub amount: MinorUnit,
pub settle_with_auth: bool,
pub card: PaysafeCard,
pub currency_code: enums::Currency,
pub payment_type: PaysafePaymentType,
pub transaction_type: TransactionType,
pub return_links: Vec<ReturnLink>,
pub account_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ReturnLink {
pub rel: LinkType,
pub href: String,
pub method: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LinkType {
OnCompleted,
OnFailed,
OnCancelled,
Default,
}
#[derive(Debug, Serialize)]
pub enum PaysafePaymentType {
#[serde(rename = "CARD")]
Card,
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "PAYMENT")]
Payment,
}
impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePaymentHandleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaysafeRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Paysafe",
})?
};
let metadata: PaysafeConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
match item.router_data.request.get_payment_method_data()?.clone() {
PaymentMethodData::Card(req_card) => {
let card = PaysafeCard {
card_num: req_card.card_number.clone(),
card_expiry: PaysafeCardExpiry {
month: req_card.card_exp_month.clone(),
year: req_card.get_expiry_year_4_digit(),
},
cvv: if req_card.card_cvc.clone().expose().is_empty() {
None
} else {
Some(req_card.card_cvc.clone())
},
holder_name: item.router_data.get_optional_billing_full_name(),
};
let account_id = metadata.account_id;
let amount = item.amount;
let payment_type = PaysafePaymentType::Card;
let transaction_type = TransactionType::Payment;
let redirect_url = item.router_data.request.get_router_return_url()?;
let return_links = vec![
ReturnLink {
rel: LinkType::Default,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCompleted,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnFailed,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCancelled,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
];
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
settle_with_auth: matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
),
card,
currency_code: item.router_data.request.get_currency()?,
payment_type,
transaction_type,
return_links,
account_id,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentHandleResponse {
pub id: String,
pub merchant_ref_num: String,
pub payment_handle_token: Secret<String>,
pub status: PaysafePaymentHandleStatus,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafePaymentHandleStatus {
Initiated,
Payable,
#[default]
Processing,
Failed,
Expired,
Completed,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaysafeMeta {
pub payment_handle_token: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
PaysafePaymentHandleResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaysafePaymentHandleResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
preprocessing_id: Some(
item.response
.payment_handle_token
.to_owned()
.peek()
.to_string(),
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, PaysafePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaysafePaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: get_paysafe_payment_status(
item.response.status,
item.data.request.capture_method,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentsRequest {
pub merchant_ref_num: String,
pub amount: MinorUnit,
pub settle_with_auth: bool,
pub payment_handle_token: Secret<String>,
pub currency_code: enums::Currency,
pub customer_ip: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeCard {
pub card_num: CardNumber,
pub card_expiry: PaysafeCardExpiry,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvv: Option<Secret<String>>,
pub holder_name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaysafeCardExpiry {
pub month: Secret<String>,
pub year: Secret<String>,
}
impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaysafeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Paysafe",
})?
};
let payment_handle_token = Secret::new(item.router_data.get_preprocessing_id()?);
let amount = item.amount;
let customer_ip = Some(
item.router_data
.request
.get_browser_info()?
.get_ip_address()?,
);
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
payment_handle_token,
amount,
settle_with_auth: item.router_data.request.is_auto_capture()?,
currency_code: item.router_data.request.currency,
customer_ip,
})
}
}
pub struct PaysafeAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PaysafeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
username: api_key.to_owned(),
password: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Paysafe Payment Status
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafePaymentStatus {
Received,
Completed,
Held,
Failed,
#[default]
Pending,
Cancelled,
Processing,
}
pub fn get_paysafe_payment_status(
status: PaysafePaymentStatus,
capture_method: Option<common_enums::CaptureMethod>,
) -> common_enums::AttemptStatus {
match status {
PaysafePaymentStatus::Completed => match capture_method {
Some(common_enums::CaptureMethod::Manual) => common_enums::AttemptStatus::Authorized,
Some(common_enums::CaptureMethod::Automatic) | None => {
common_enums::AttemptStatus::Charged
}
Some(common_enums::CaptureMethod::SequentialAutomatic)
| Some(common_enums::CaptureMethod::ManualMultiple)
| Some(common_enums::CaptureMethod::Scheduled) => {
common_enums::AttemptStatus::Unresolved
}
},
PaysafePaymentStatus::Failed => common_enums::AttemptStatus::Failure,
PaysafePaymentStatus::Pending
| PaysafePaymentStatus::Processing
| PaysafePaymentStatus::Received
| PaysafePaymentStatus::Held => common_enums::AttemptStatus::Pending,
PaysafePaymentStatus::Cancelled => common_enums::AttemptStatus::Voided,
}
}
// Paysafe Payments Response Structure
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentsSyncResponse {
pub payments: Vec<PaysafePaymentsResponse>,
}
// Paysafe Payments Response Structure
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentsResponse {
pub id: String,
pub merchant_ref_num: Option<String>,
pub status: PaysafePaymentStatus,
pub settlements: Option<Vec<PaysafeSettlementResponse>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeSettlementResponse {
pub merchant_ref_num: Option<String>,
pub id: String,
pub status: PaysafeSettlementStatus,
}
impl<F>
TryFrom<
ResponseRouterData<F, PaysafePaymentsSyncResponse, PaymentsSyncData, PaymentsResponseData>,
> for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaysafePaymentsSyncResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let payment_handle = item
.response
.payments
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(Self {
status: get_paysafe_payment_status(
payment_handle.status,
item.data.request.capture_method,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeCaptureRequest {
pub merchant_ref_num: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<MinorUnit>,
}
impl TryFrom<&PaysafeRouterData<&PaymentsCaptureRouterData>> for PaysafeCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaysafeRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let amount = Some(item.amount);
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
})
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafeSettlementStatus {
Received,
Initiated,
Completed,
Expired,
Failed,
#[default]
Pending,
Cancelled,
}
impl From<PaysafeSettlementStatus> for common_enums::AttemptStatus {
fn from(item: PaysafeSettlementStatus) -> Self {
match item {
PaysafeSettlementStatus::Completed
| PaysafeSettlementStatus::Pending
| PaysafeSettlementStatus::Received => Self::Charged,
PaysafeSettlementStatus::Failed | PaysafeSettlementStatus::Expired => Self::Failure,
PaysafeSettlementStatus::Cancelled => Self::Voided,
PaysafeSettlementStatus::Initiated => Self::Pending,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, PaysafeSettlementResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaysafeSettlementResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&PaysafeRouterData<&PaymentsCancelRouterData>> for PaysafeCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaysafeRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> {
let amount = Some(item.amount);
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VoidResponse {
pub merchant_ref_num: Option<String>,
pub id: String,
pub status: PaysafeVoidStatus,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafeVoidStatus {
Received,
Completed,
Held,
Failed,
#[default]
Pending,
Cancelled,
}
impl From<PaysafeVoidStatus> for common_enums::AttemptStatus {
fn from(item: PaysafeVoidStatus) -> Self {
match item {
PaysafeVoidStatus::Completed
| PaysafeVoidStatus::Pending
| PaysafeVoidStatus::Received => Self::Voided,
PaysafeVoidStatus::Failed | PaysafeVoidStatus::Held => Self::Failure,
PaysafeVoidStatus::Cancelled => Self::Voided,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, VoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeRefundRequest {
pub merchant_ref_num: String,
pub amount: MinorUnit,
}
impl<F> TryFrom<&PaysafeRouterData<&RefundsRouterData<F>>> for PaysafeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaysafeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let amount = item.amount;
Ok(Self {
merchant_ref_num: item.router_data.request.refund_id.clone(),
amount,
})
}
}
// Type definition for Refund Response
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Received,
Initiated,
Completed,
Expired,
Failed,
#[default]
Pending,
Cancelled,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Received | RefundStatus::Completed => Self::Success,
RefundStatus::Failed | RefundStatus::Cancelled | RefundStatus::Expired => Self::Failure,
RefundStatus::Pending | RefundStatus::Initiated => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaysafeErrorResponse {
pub error: Error,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Error {
pub code: String,
pub message: String,
pub details: Option<Vec<String>>,
#[serde(rename = "fieldErrors")]
pub field_errors: Option<Vec<FieldError>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FieldError {
pub field: String,
pub error: String,
}
| crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs | hyperswitch_connectors | full_file | 4,906 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct AccountNumber {
/// Type of account number
#[serde(rename = "_type")]
pub account_type: AccountType,
/// Currency of the account (Mandatory for debtor, Optional for creditor)
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<api_models::enums::Currency>,
/// Actual account number
pub value: Secret<String>,
} | crates/hyperswitch_connectors/src/connectors/nordea/requests.rs | hyperswitch_connectors | struct_definition | 85 | rust | AccountNumber | null | null | null | null | null | null | null | null | null | null | null |
pub struct IdealData {
ideal: IdealDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
} | crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs | hyperswitch_connectors | struct_definition | 31 | rust | IdealData | null | null | null | null | null | null | null | null | null | null | null |
pub async fn update_with_attempt_id(
self,
conn: &PgPooledConn,
fraud_check: FraudCheckUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::attempt_id
.eq(self.attempt_id.to_owned())
.and(dsl::merchant_id.eq(self.merchant_id.to_owned())),
FraudCheckUpdateInternal::from(fraud_check),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
} | crates/diesel_models/src/query/fraud_check.rs | diesel_models | function_signature | 166 | rust | null | null | null | null | update_with_attempt_id | null | null | null | null | null | null | null |
pub async fn connector_selection<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
request_straight_through: Option<serde_json::Value>,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let request_straight_through: Option<api::routing::StraightThroughAlgorithm> =
request_straight_through
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through routing rules format")?;
let mut routing_data = storage::RoutingData {
routed_through: payment_data.get_payment_attempt().connector.clone(),
merchant_connector_id: payment_data
.get_payment_attempt()
.merchant_connector_id
.clone(),
algorithm: request_straight_through.clone(),
routing_info: payment_data
.get_payment_attempt()
.straight_through_algorithm
.clone()
.map(|val| val.parse_value("PaymentRoutingInfo"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through algorithm format found in payment attempt")?
.unwrap_or(storage::PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
}),
};
let decided_connector = decide_connector(
state.clone(),
merchant_context,
business_profile,
payment_data,
request_straight_through,
&mut routing_data,
eligible_connectors,
mandate_type,
)
.await?;
let encoded_info = routing_data
.routing_info
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error serializing payment routing info to serde value")?;
payment_data.set_connector_in_payment_attempt(routing_data.routed_through);
payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id);
payment_data.set_straight_through_algorithm_in_payment_attempt(encoded_info);
Ok(decided_connector)
} | crates/router/src/core/payments.rs | router | function_signature | 498 | rust | null | null | null | null | connector_selection | null | null | null | null | null | null | null |
pub async fn signout_external_token(
state: SessionState,
json_payload: external_service_auth_api::ExternalSignoutTokenRequest,
) -> RouterResponse<()> {
let token = authentication::decode_jwt::<ExternalToken>(&json_payload.token.expose(), &state)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
authentication::blacklist::insert_user_in_blacklist(&state, &token.user_id)
.await
.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;
Ok(service_api::ApplicationResponse::StatusOk)
} | crates/router/src/core/external_service_auth.rs | router | function_signature | 119 | rust | null | null | null | null | signout_external_token | null | null | null | null | null | null | null |
impl api::ConnectorAccessToken for Archipel {} | crates/hyperswitch_connectors/src/connectors/archipel.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Archipel | api::ConnectorAccessToken for | impl api::ConnectorAccessToken for for Archipel | null | null | null | null | null | null | null | null |
pub async fn construct_payment_router_data_for_setup_mandate<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
let auth_type = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
// TODO: Take Globalid and convert to connector reference id
let customer_id = customer
.to_owned()
.map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone()))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Invalid global customer generated, not able to convert to reference id",
)?;
let connector_customer_id = customer.as_ref().and_then(|customer| {
customer
.get_connector_customer_id(merchant_connector_account)
.map(String::from)
});
let payment_method = payment_data.payment_attempt.payment_method_type;
let router_base_url = &state.base_url;
let attempt = &payment_data.payment_attempt;
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_id,
None,
));
let webhook_url = match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
merchant_connector_account,
) => Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account.get_id().get_string_repr(),
)),
// TODO: Implement for connectors that require a webhook URL to be included in the request payload.
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
todo!("Add webhook URL to request for this connector")
}
};
let router_return_url = payment_data
.payment_intent
.create_finish_redirection_url(
router_base_url,
merchant_context
.get_merchant_account()
.publishable_key
.as_ref(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to construct finish redirection url")?
.to_string();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("connector_request_reference_id not found in payment_attempt")?;
let email = customer
.as_ref()
.and_then(|customer| customer.email.clone())
.map(pii::Email::from);
let browser_info = payment_data
.payment_attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
// TODO: few fields are repeated in both routerdata and request
let request = types::SetupMandateRequestData {
currency: payment_data.payment_intent.amount_details.currency,
payment_method_data: payment_data
.payment_method_data
.get_required_value("payment_method_data")?,
amount: Some(
payment_data
.payment_attempt
.amount_details
.get_net_amount()
.get_amount_as_i64(),
),
confirm: true,
statement_descriptor_suffix: None,
customer_acceptance: None,
mandate_id: None,
setup_future_usage: Some(payment_data.payment_intent.setup_future_usage),
off_session: None,
setup_mandate_details: None,
router_return_url: Some(router_return_url.clone()),
webhook_url,
browser_info,
email,
customer_name: None,
return_url: Some(router_return_url),
payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
request_incremental_authorization: matches!(
payment_data
.payment_intent
.request_incremental_authorization,
RequestIncrementalAuthorization::True
),
metadata: payment_data.payment_intent.metadata,
minor_amount: Some(payment_data.payment_attempt.amount_details.get_net_amount()),
shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,
capture_method: Some(payment_data.payment_intent.capture_method),
complete_authorize_url,
connector_testing_data: None,
customer_id: None,
enable_partial_authorization: None,
payment_channel: None,
enrolled_for_3ds: true,
related_transaction_id: None,
};
let connector_mandate_request_reference_id = payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|detail| detail.get_connector_token_request_reference_id());
// TODO: evaluate the fields in router data, if they are required or not
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
// TODO: evaluate why we need customer id at the connector level. We already have connector customer id.
customer_id,
connector: connector_id.to_owned(),
// TODO: evaluate why we need payment id at the connector level. We already have connector reference id
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
// TODO: evaluate why we need attempt id at the connector level. We already have connector reference id
attempt_id: payment_data
.payment_attempt
.get_id()
.get_string_repr()
.to_owned(),
status: payment_data.payment_attempt.status,
payment_method,
connector_auth_type: auth_type,
description: payment_data
.payment_intent
.description
.as_ref()
.map(|description| description.get_string_repr())
.map(ToOwned::to_owned),
// TODO: Create unified address
address: payment_data.payment_address.clone(),
auth_type: payment_data.payment_attempt.authentication_type,
connector_meta_data: None,
connector_wallets_details: None,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_status: None,
payment_method_token: None,
connector_customer: connector_customer_id,
recurring_mandate_payment_data: None,
// TODO: This has to be generated as the reference id based on the connector configuration
// Some connectros might not accept accept the global id. This has to be done when generating the reference id
connector_request_reference_id,
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
// TODO: take this based on the env
test_mode: Some(true),
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
};
Ok(router_data)
} | crates/router/src/core/payments/transformers.rs | router | function_signature | 1,746 | rust | null | null | null | null | construct_payment_router_data_for_setup_mandate | null | null | null | null | null | null | null |
pub struct VoltRefundWebhookObjectResource {
pub refund: String,
pub external_reference: Option<String>,
pub status: VoltWebhookRefundsStatus,
} | crates/hyperswitch_connectors/src/connectors/volt/transformers.rs | hyperswitch_connectors | struct_definition | 36 | rust | VoltRefundWebhookObjectResource | null | null | null | null | null | null | null | null | null | null | null |
pub struct DisputeSyncData {
pub dispute_id: String,
pub connector_dispute_id: String,
} | crates/hyperswitch_domain_models/src/router_request_types.rs | hyperswitch_domain_models | struct_definition | 24 | rust | DisputeSyncData | null | null | null | null | null | null | null | null | null | null | null |
File: crates/common_utils/src/fp_utils.rs
Public functions: 1
//! Functional programming utilities
/// The Applicative trait provides a pure behavior,
/// which can be used to create values of type f a from values of type a.
pub trait Applicative<R> {
/// The Associative type acts as a (f a) wrapper for Self.
type WrappedSelf<T>;
/// Applicative::pure(_) is abstraction with lifts any arbitrary type to underlying higher
/// order type
fn pure(v: R) -> Self::WrappedSelf<R>;
}
impl<R> Applicative<R> for Option<R> {
type WrappedSelf<T> = Option<T>;
fn pure(v: R) -> Self::WrappedSelf<R> {
Some(v)
}
}
impl<R, E> Applicative<R> for Result<R, E> {
type WrappedSelf<T> = Result<T, E>;
fn pure(v: R) -> Self::WrappedSelf<R> {
Ok(v)
}
}
/// This function wraps the evaluated result of `f` into current context,
/// based on the condition provided into the `predicate`
pub fn when<W: Applicative<(), WrappedSelf<()> = W>, F>(predicate: bool, f: F) -> W
where
F: FnOnce() -> W,
{
if predicate {
f()
} else {
W::pure(())
}
}
| crates/common_utils/src/fp_utils.rs | common_utils | full_file | 296 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct WalletTokenData {
pub payment_method_id: String,
} | crates/router/src/types/storage/payment_method.rs | router | struct_definition | 15 | rust | WalletTokenData | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentVoid for Custombilling {} | crates/hyperswitch_connectors/src/connectors/custombilling.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Custombilling | api::PaymentVoid for | impl api::PaymentVoid for for Custombilling | null | null | null | null | null | null | null | null |
pub(super) async fn retrieve_payment_token_data(
state: &SessionState,
token: String,
payment_method: Option<&storage_enums::PaymentMethod>,
) -> errors::RouterResult<storage::PaymentTokenData> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!(
"pm_token_{}_{}_hyperswitch",
token,
payment_method
.get_required_value("payment_method")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method is required")?
);
let token_data_string = redis_conn
.get_key::<Option<String>>(&key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?
.ok_or(error_stack::Report::new(
errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".to_owned(),
},
))?;
token_data_string
.clone()
.parse_struct("PaymentTokenData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to deserialize hyperswitch token data")
} | crates/router/src/core/payment_methods/utils.rs | router | function_signature | 282 | rust | null | null | null | null | retrieve_payment_token_data | null | null | null | null | null | null | null |
pub struct HelcimVerifyRequest {
currency: enums::Currency,
ip_address: Secret<String, IpAddress>,
card_data: HelcimCard,
billing_address: HelcimBillingAddress,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
} | crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs | hyperswitch_connectors | struct_definition | 65 | rust | HelcimVerifyRequest | null | null | null | null | null | null | null | null | null | null | null |
impl BillingConnectorPaymentsSyncResponseData {
async fn handle_billing_connector_payment_sync_call(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
None,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedBillingConnectorPaymentsSyncIntegrationInterface<
router_flow_types::BillingConnectorPaymentsSync,
revenue_recovery_request::BillingConnectorPaymentsSyncRequest,
revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
BillingConnectorPaymentsSyncFlowRouterData::construct_router_data_for_billing_connector_payment_sync_call(
state,
connector_name,
merchant_connector_account,
merchant_context,
id,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(
"Failed while constructing router data for billing connector psync call",
)?
.inner();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")?;
let additional_recovery_details = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")
}
}?;
Ok(Self(additional_recovery_details))
}
async fn get_billing_connector_payment_details(
should_billing_connector_payment_api_called: bool,
state: &SessionState,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<
Option<revenue_recovery_response::BillingConnectorPaymentsSyncResponse>,
errors::RevenueRecoveryError,
> {
let response_data = match should_billing_connector_payment_api_called {
true => {
let billing_connector_transaction_id = object_ref_id
.clone()
.get_connector_transaction_id_as_string()
.change_context(
errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed,
)
.attach_printable("Billing connector Payments api call failed")?;
let billing_connector_payment_details =
Self::handle_billing_connector_payment_sync_call(
state,
merchant_context,
billing_connector_account,
connector_name,
&billing_connector_transaction_id,
)
.await?;
Some(billing_connector_payment_details.inner())
}
false => None,
};
Ok(response_data)
}
fn inner(self) -> revenue_recovery_response::BillingConnectorPaymentsSyncResponse {
self.0
}
} | crates/router/src/core/webhooks/recovery_incoming.rs | router | impl_block | 736 | rust | null | BillingConnectorPaymentsSyncResponseData | null | impl BillingConnectorPaymentsSyncResponseData | null | null | null | null | null | null | null | null |
impl api::RefundExecute for Itaubank {} | crates/hyperswitch_connectors/src/connectors/itaubank.rs | hyperswitch_connectors | impl_block | 11 | rust | null | Itaubank | api::RefundExecute for | impl api::RefundExecute for for Itaubank | null | null | null | null | null | null | null | null |
pub fn add_connector_mandate_details_in_payment_method(
payment_method_type: Option<storage_enums::PaymentMethodType>,
authorized_amount: Option<i64>,
authorized_currency: Option<storage_enums::Currency>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
connector_mandate_id: Option<String>,
mandate_metadata: Option<Secret<serde_json::Value>>,
connector_mandate_request_reference_id: Option<String>,
) -> Option<CommonMandateReference> {
let mut mandate_details = HashMap::new();
if let Some((mca_id, connector_mandate_id)) =
merchant_connector_id.clone().zip(connector_mandate_id)
{
mandate_details.insert(
mca_id,
PaymentsMandateReferenceRecord {
connector_mandate_id,
payment_method_type,
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
mandate_metadata,
connector_mandate_status: Some(ConnectorMandateStatus::Active),
connector_mandate_request_reference_id,
},
);
Some(CommonMandateReference {
payments: Some(PaymentsMandateReference(mandate_details)),
payouts: None,
})
} else {
None
}
} | crates/router/src/core/payments/tokenization.rs | router | function_signature | 275 | rust | null | null | null | null | add_connector_mandate_details_in_payment_method | null | null | null | null | null | null | null |
impl api::Payment for UnifiedAuthenticationService {} | crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs | hyperswitch_connectors | impl_block | 9 | rust | null | UnifiedAuthenticationService | api::Payment for | impl api::Payment for for UnifiedAuthenticationService | null | null | null | null | null | null | null | null |
pub struct SquareErrorResponse {
pub errors: Vec<SquareErrorDetails>,
} | crates/hyperswitch_connectors/src/connectors/square/transformers.rs | hyperswitch_connectors | struct_definition | 16 | rust | SquareErrorResponse | null | null | null | null | null | null | null | null | null | null | null |
pub struct ThreeDsDecisionRule; | crates/router/src/routes/app.rs | router | struct_definition | 7 | rust | ThreeDsDecisionRule | null | null | null | null | null | null | null | null | null | null | null |
pub struct SignifydPaymentsRecordReturnRequest {
order_id: String,
return_id: String,
refund_transaction_id: Option<String>,
refund: SignifydRefund,
} | crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs | hyperswitch_connectors | struct_definition | 40 | rust | SignifydPaymentsRecordReturnRequest | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentAuthorize for Jpmorgan {} | crates/hyperswitch_connectors/src/connectors/jpmorgan.rs | hyperswitch_connectors | impl_block | 10 | rust | null | Jpmorgan | api::PaymentAuthorize for | impl api::PaymentAuthorize for for Jpmorgan | null | null | null | null | null | null | null | null |
File: crates/payment_methods/src/core/migration.rs
Public functions: 9
Public structs: 3
use actix_multipart::form::{self, bytes, text};
use api_models::payment_methods as pm_api;
use csv::Reader;
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::{api, merchant_context};
use masking::PeekInterface;
use rdkafka::message::ToBytes;
use router_env::{instrument, tracing};
use crate::core::errors;
#[cfg(feature = "v1")]
use crate::{controller as pm, state};
pub mod payment_methods;
pub use payment_methods::migrate_payment_method;
#[cfg(feature = "v1")]
type PmMigrationResult<T> =
errors::CustomResult<api::ApplicationResponse<T>, errors::ApiErrorResponse>;
#[cfg(feature = "v1")]
pub async fn migrate_payment_methods(
state: &state::PaymentMethodsState,
payment_methods: Vec<pm_api::PaymentMethodRecord>,
merchant_id: &common_utils::id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
mca_ids: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
controller: &dyn pm::PaymentMethodsController,
) -> PmMigrationResult<Vec<pm_api::PaymentMethodMigrationResponse>> {
let mut result = Vec::with_capacity(payment_methods.len());
for record in payment_methods {
let req = pm_api::PaymentMethodMigrate::try_from((
&record,
merchant_id.clone(),
mca_ids.as_ref(),
))
.map_err(|err| errors::ApiErrorResponse::InvalidRequestData {
message: format!("error: {err:?}"),
})
.attach_printable("record deserialization failed");
let res = match req {
Ok(migrate_request) => {
let res = migrate_payment_method(
state,
migrate_request,
merchant_id,
merchant_context,
controller,
)
.await;
match res {
Ok(api::ApplicationResponse::Json(response)) => Ok(response),
Err(e) => Err(e.to_string()),
_ => Err("Failed to migrate payment method".to_string()),
}
}
Err(e) => Err(e.to_string()),
};
result.push(pm_api::PaymentMethodMigrationResponse::from((res, record)));
}
Ok(api::ApplicationResponse::Json(result))
}
#[derive(Debug, form::MultipartForm)]
pub struct PaymentMethodsMigrateForm {
#[multipart(limit = "1MB")]
pub file: bytes::Bytes,
pub merchant_id: text::Text<common_utils::id_type::MerchantId>,
pub merchant_connector_id:
Option<text::Text<common_utils::id_type::MerchantConnectorAccountId>>,
pub merchant_connector_ids: Option<text::Text<String>>,
}
struct MerchantConnectorValidator;
impl MerchantConnectorValidator {
fn parse_comma_separated_ids(
ids_string: &str,
) -> Result<Vec<common_utils::id_type::MerchantConnectorAccountId>, errors::ApiErrorResponse>
{
// Estimate capacity based on comma count
let capacity = ids_string.matches(',').count() + 1;
let mut result = Vec::with_capacity(capacity);
for id in ids_string.split(',') {
let trimmed_id = id.trim();
if !trimmed_id.is_empty() {
let mca_id =
common_utils::id_type::MerchantConnectorAccountId::wrap(trimmed_id.to_string())
.map_err(|_| errors::ApiErrorResponse::InvalidRequestData {
message: format!("Invalid merchant_connector_account_id: {trimmed_id}"),
})?;
result.push(mca_id);
}
}
Ok(result)
}
fn validate_form_csv_conflicts(
records: &[pm_api::PaymentMethodRecord],
form_has_single_id: bool,
form_has_multiple_ids: bool,
) -> Result<(), errors::ApiErrorResponse> {
if form_has_single_id {
// If form has merchant_connector_id, CSV records should not have merchant_connector_ids
for (index, record) in records.iter().enumerate() {
if record.merchant_connector_ids.is_some() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Record at line {} has merchant_connector_ids but form has merchant_connector_id. Only one should be provided",
index + 1
),
});
}
}
}
if form_has_multiple_ids {
// If form has merchant_connector_ids, CSV records should not have merchant_connector_id
for (index, record) in records.iter().enumerate() {
if record.merchant_connector_id.is_some() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Record at line {} has merchant_connector_id but form has merchant_connector_ids. Only one should be provided",
index + 1
),
});
}
}
}
Ok(())
}
}
type MigrationValidationResult = Result<
(
common_utils::id_type::MerchantId,
Vec<pm_api::PaymentMethodRecord>,
Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
),
errors::ApiErrorResponse,
>;
impl PaymentMethodsMigrateForm {
pub fn validate_and_get_payment_method_records(self) -> MigrationValidationResult {
// Step 1: Validate form-level conflicts
let form_has_single_id = self.merchant_connector_id.is_some();
let form_has_multiple_ids = self.merchant_connector_ids.is_some();
if form_has_single_id && form_has_multiple_ids {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Both merchant_connector_id and merchant_connector_ids cannot be provided"
.to_string(),
});
}
// Ensure at least one is provided
if !form_has_single_id && !form_has_multiple_ids {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Either merchant_connector_id or merchant_connector_ids must be provided"
.to_string(),
});
}
// Step 2: Parse CSV
let records = parse_csv(self.file.data.to_bytes()).map_err(|e| {
errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
}
})?;
// Step 3: Validate CSV vs Form conflicts
MerchantConnectorValidator::validate_form_csv_conflicts(
&records,
form_has_single_id,
form_has_multiple_ids,
)?;
// Step 4: Prepare the merchant connector account IDs for return
let mca_ids = if let Some(ref single_id) = self.merchant_connector_id {
Some(vec![(**single_id).clone()])
} else if let Some(ref ids_string) = self.merchant_connector_ids {
let parsed_ids = MerchantConnectorValidator::parse_comma_separated_ids(ids_string)?;
if parsed_ids.is_empty() {
None
} else {
Some(parsed_ids)
}
} else {
None
};
// Step 5: Return the updated structure
Ok((self.merchant_id.clone(), records, mca_ids))
}
}
fn parse_csv(data: &[u8]) -> csv::Result<Vec<pm_api::PaymentMethodRecord>> {
let mut csv_reader = Reader::from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for result in csv_reader.deserialize() {
let mut record: pm_api::PaymentMethodRecord = result?;
id_counter += 1;
record.line_number = Some(id_counter);
records.push(record);
}
Ok(records)
}
#[instrument(skip_all)]
pub fn validate_card_expiry(
card_exp_month: &masking::Secret<String>,
card_exp_year: &masking::Secret<String>,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
let exp_month = card_exp_month
.peek()
.to_string()
.parse::<u8>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_month",
})?;
::cards::CardExpirationMonth::try_from(exp_month).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Month".to_string(),
},
)?;
let year_str = card_exp_year.peek().to_string();
validate_card_exp_year(year_str).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Year".to_string(),
},
)?;
Ok(())
}
fn validate_card_exp_year(year: String) -> Result<(), errors::ValidationError> {
let year_str = year.to_string();
if year_str.len() == 2 || year_str.len() == 4 {
year_str
.parse::<u16>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: "card_exp_year".to_string(),
})?;
Ok(())
} else {
Err(errors::ValidationError::InvalidValue {
message: "invalid card expiration year".to_string(),
})
}
}
#[derive(Debug)]
pub struct RecordMigrationStatus {
pub card_migrated: Option<bool>,
pub network_token_migrated: Option<bool>,
pub connector_mandate_details_migrated: Option<bool>,
pub network_transaction_migrated: Option<bool>,
}
#[derive(Debug)]
pub struct RecordMigrationStatusBuilder {
pub card_migrated: Option<bool>,
pub network_token_migrated: Option<bool>,
pub connector_mandate_details_migrated: Option<bool>,
pub network_transaction_migrated: Option<bool>,
}
impl RecordMigrationStatusBuilder {
pub fn new() -> Self {
Self {
card_migrated: None,
network_token_migrated: None,
connector_mandate_details_migrated: None,
network_transaction_migrated: None,
}
}
pub fn card_migrated(&mut self, card_migrated: bool) {
self.card_migrated = Some(card_migrated);
}
pub fn network_token_migrated(&mut self, network_token_migrated: Option<bool>) {
self.network_token_migrated = network_token_migrated;
}
pub fn connector_mandate_details_migrated(
&mut self,
connector_mandate_details_migrated: Option<bool>,
) {
self.connector_mandate_details_migrated = connector_mandate_details_migrated;
}
pub fn network_transaction_id_migrated(&mut self, network_transaction_migrated: Option<bool>) {
self.network_transaction_migrated = network_transaction_migrated;
}
pub fn build(self) -> RecordMigrationStatus {
RecordMigrationStatus {
card_migrated: self.card_migrated,
network_token_migrated: self.network_token_migrated,
connector_mandate_details_migrated: self.connector_mandate_details_migrated,
network_transaction_migrated: self.network_transaction_migrated,
}
}
}
impl Default for RecordMigrationStatusBuilder {
fn default() -> Self {
Self::new()
}
}
| crates/payment_methods/src/core/migration.rs | payment_methods | full_file | 2,336 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::DisputesFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
disputes::get_filters_for_disputes(state, merchant_context, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/disputes.rs | router | function_signature | 195 | rust | null | null | null | null | get_disputes_filters | null | null | null | null | null | null | null |
pub trait IncomingWebhook: ConnectorCommon + Sync {
/// fn get_webhook_body_decoding_algorithm
fn get_webhook_body_decoding_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::NoAlgorithm))
}
/// fn get_webhook_body_decoding_message
fn get_webhook_body_decoding_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
}
/// fn decode_webhook_body
async fn decode_webhook_body(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_name: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let algorithm = self.get_webhook_body_decoding_algorithm(request)?;
let message = self
.get_webhook_body_decoding_message(request)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let secret = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
algorithm
.decode_message(&secret.secret, message.into())
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
/// fn get_webhook_source_verification_algorithm
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::NoAlgorithm))
}
/// fn get_webhook_source_verification_merchant_secret
async fn get_webhook_source_verification_merchant_secret(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> {
let debug_suffix =
format!("For merchant_id: {merchant_id:?}, and connector_name: {connector_name}");
let default_secret = "default_secret".to_string();
let merchant_secret = match connector_webhook_details {
Some(merchant_connector_webhook_details) => {
let connector_webhook_details = merchant_connector_webhook_details
.parse_value::<api_models::admin::MerchantConnectorWebhookDetails>(
"MerchantConnectorWebhookDetails",
)
.change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable_lazy(|| {
format!(
"Deserializing MerchantConnectorWebhookDetails failed {debug_suffix}",
)
})?;
api_models::webhooks::ConnectorWebhookSecrets {
secret: connector_webhook_details
.merchant_secret
.expose()
.into_bytes(),
additional_secret: connector_webhook_details.additional_secret,
}
}
None => api_models::webhooks::ConnectorWebhookSecrets {
secret: default_secret.into_bytes(),
additional_secret: None,
},
};
//need to fetch merchant secret from config table with caching in future for enhanced performance
//If merchant has not set the secret for webhook source verification, "default_secret" is returned.
//So it will fail during verification step and goes to psync flow.
Ok(merchant_secret)
}
/// fn get_webhook_source_verification_signature
fn get_webhook_source_verification_signature(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(Vec::new())
}
/// fn get_webhook_source_verification_message
fn get_webhook_source_verification_message(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(Vec::new())
}
/// fn verify_webhook_source
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let algorithm = self
.get_webhook_source_verification_algorithm(request)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
algorithm
.verify_signature(&connector_webhook_secrets.secret, &signature, &message)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
}
/// fn get_webhook_object_reference_id
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError>;
/// fn get_webhook_event_type
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError>;
/// fn get_webhook_resource_object
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError>;
/// fn get_webhook_api_response
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
Ok(ApplicationResponse::StatusOk)
}
/// fn get_dispute_details
fn get_dispute_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<crate::disputes::DisputePayload, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_dispute_details method".to_string()).into())
}
/// fn get_external_authentication_details
fn get_external_authentication_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<crate::authentication::ExternalAuthenticationPayload, errors::ConnectorError>
{
Err(errors::ConnectorError::NotImplemented(
"get_external_authentication_details method".to_string(),
)
.into())
}
/// fn get_mandate_details
fn get_mandate_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
errors::ConnectorError,
> {
Ok(None)
}
/// fn get_network_txn_id
fn get_network_txn_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>,
errors::ConnectorError,
> {
Ok(None)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
/// get revenue recovery invoice details
fn get_revenue_recovery_attempt_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData,
errors::ConnectorError,
> {
Err(errors::ConnectorError::NotImplemented(
"get_revenue_recovery_attempt_details method".to_string(),
)
.into())
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
/// get revenue recovery transaction details
fn get_revenue_recovery_invoice_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData,
errors::ConnectorError,
> {
Err(errors::ConnectorError::NotImplemented(
"get_revenue_recovery_invoice_details method".to_string(),
)
.into())
}
} | crates/hyperswitch_interfaces/src/webhooks.rs | hyperswitch_interfaces | trait_definition | 2,076 | rust | null | null | IncomingWebhook | null | null | null | null | null | null | null | null | null |
pub struct AirwallexIntentRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
amount: StringMajorUnit,
currency: enums::Currency,
//ID created in merchant's order system that corresponds to this PaymentIntent.
merchant_order_id: String,
// This data is required to whitelist Hyperswitch at Airwallex.
referrer_data: ReferrerData,
order: Option<AirwallexOrderData>,
} | crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs | hyperswitch_connectors | struct_definition | 105 | rust | AirwallexIntentRequest | null | null | null | null | null | null | null | null | null | null | null |
pub async fn sync_onboarding_status(
state: SessionState,
user_from_token: auth::UserFromToken,
request: api::OnboardingSyncRequest,
_req_state: ReqState,
) -> RouterResponse<api::OnboardingStatus> {
utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id)
.await?;
let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf);
let tracking_id =
utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector)
.await?;
match (is_enabled, request.connector) {
(Some(true), enums::Connector::Paypal) => {
let status = Box::pin(paypal::sync_merchant_onboarding_status(
state.clone(),
tracking_id,
))
.await?;
if let api::OnboardingStatus::PayPal(api::PayPalOnboardingStatus::Success(
ref paypal_onboarding_data,
)) = status
{
let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
let auth_details = oss_types::ConnectorAuthType::SignatureKey {
api_key: connector_onboarding_conf.paypal.client_secret.clone(),
key1: connector_onboarding_conf.paypal.client_id.clone(),
api_secret: Secret::new(
paypal_onboarding_data.payer_id.get_string_repr().to_owned(),
),
};
let update_mca_data = paypal::update_mca(
&state,
user_from_token.merchant_id,
request.connector_id.to_owned(),
auth_details,
)
.await?;
return Ok(ApplicationResponse::Json(api::OnboardingStatus::PayPal(
api::PayPalOnboardingStatus::ConnectorIntegrated(Box::new(update_mca_data)),
)));
}
Ok(ApplicationResponse::Json(status))
}
_ => Err(ApiErrorResponse::FlowNotSupported {
flow: "Connector onboarding".to_string(),
connector: request.connector.to_string(),
}
.into()),
}
} | crates/router/src/core/connector_onboarding.rs | router | function_signature | 449 | rust | null | null | null | null | sync_onboarding_status | null | null | null | null | null | null | null |
pub fn get_month(&self) -> &CardExpirationMonth {
&self.month
} | crates/cards/src/lib.rs | cards | function_signature | 20 | rust | null | null | null | null | get_month | null | null | null | null | null | null | null |
pub struct MerchantAccountCreate {
pub merchant_name: Secret<common_utils::new_type::MerchantName>,
pub merchant_details: Option<MerchantDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub organization_id: id_type::OrganizationId,
/// Product Type of this merchant account
#[schema(value_type = Option<MerchantProductType>)]
pub product_type: Option<api_enums::MerchantProductType>,
} | crates/api_models/src/admin.rs | api_models | struct_definition | 94 | rust | MerchantAccountCreate | null | null | null | null | null | null | null | null | null | null | null |
- **samsung_pay:** Collect customer address details form Samsung Pay based on business profile config and connector required fields ([#7320](https://github.com/juspay/hyperswitch/pull/7320)) ([`c14519e`](https://github.com/juspay/hyperswitch/commit/c14519ebd958abc79879244f8180686b2be30d31))
### Bug Fixes
- **connector:** [DATATRANS] Fix Force Sync Flow ([#7331](https://github.com/juspay/hyperswitch/pull/7331)) ([`0e96e24`](https://github.com/juspay/hyperswitch/commit/0e96e2470c6906fe77b35c14821e3ebcfa454e39))
- **routing:** Fixed 5xx error logs in dynamic routing metrics ([#7335](https://github.com/juspay/hyperswitch/pull/7335)) ([`049fcdb`](https://github.com/juspay/hyperswitch/commit/049fcdb3fb19c6af45392a5ef3a0cbf642598af8))
- **samsung_pay:** Add payment_method_type duplication check ([#7337](https://github.com/juspay/hyperswitch/pull/7337)) ([`11ff437`](https://github.com/juspay/hyperswitch/commit/11ff437456f9d97205ce07e4d4df63006f3ad0c6))
### Miscellaneous Tasks
- **masking:** Add peek_mut to PeekInterface ([#7281](https://github.com/juspay/hyperswitch/pull/7281)) ([`890a265`](https://github.com/juspay/hyperswitch/commit/890a265e7b1b06aeea100994efbebe3ce898a125))
**Full Changelog:** [`2025.02.21.0...2025.02.24.0`](https://github.com/juspay/hyperswitch/compare/2025.02.21.0...2025.02.24.0)
- - -
## 2025.02.21.0
### Features
- **core:** Add support for confirmation flow for click to pay ([#6982](https://github.com/juspay/hyperswitch/pull/6982)) ([`74bbf4b`](https://github.com/juspay/hyperswitch/commit/74bbf4bf271d45e61e594857707250c95a86f43f))
- **router:**
- Add Payments - List endpoint for v2 ([#7191](https://github.com/juspay/hyperswitch/pull/7191)) ([`d1f537e`](https://github.com/juspay/hyperswitch/commit/d1f537e22909a3580dbf9069852f4257fdbad66b))
- [Xendit] add support for split payments ([#7143](https://github.com/juspay/hyperswitch/pull/7143)) ([`451acba`](https://github.com/juspay/hyperswitch/commit/451acba005a85228925da5b6c252815d58f96fd7))
### Bug Fixes
- **connector:** [DATATRANS] Add new payment status ([#7327](https://github.com/juspay/hyperswitch/pull/7327)) ([`2b74a94`](https://github.com/juspay/hyperswitch/commit/2b74a94e3abf6f493058b4a4981f45be558ea3d2))
- **payment_methods_v2:** Update fingerprint implementation in v2 ([#7270](https://github.com/juspay/hyperswitch/pull/7270)) ([`e475f63`](https://github.com/juspay/hyperswitch/commit/e475f63967a7922d1a0211d75ad4567a3182f3e8))
**Full Changelog:** [`2025.02.20.0...2025.02.21.0`](https://github.com/juspay/hyperswitch/compare/2025.02.20.0...2025.02.21.0)
- - -
## 2025.02.20.0
### Features
- **core:** Add hypersense integration api ([#7218](https://github.com/juspay/hyperswitch/pull/7218)) ([`22633be`](https://github.com/juspay/hyperswitch/commit/22633be55cfc42dc4a7171c3193da594d0557bfb))
### Bug Fixes
- **connector:** [SCRIPT] Update template generating script and updated connector doc ([#7301](https://github.com/juspay/hyperswitch/pull/7301)) ([`2d9df53`](https://github.com/juspay/hyperswitch/commit/2d9df53491b1ef662736efec60ec5e5368466bb4))
### Refactors
- **utils:** Match string for state with SDK's naming convention ([#7300](https://github.com/juspay/hyperswitch/pull/7300)) ([`f3ca200`](https://github.com/juspay/hyperswitch/commit/f3ca2009c1902094a72b8bf43e89b406e44ecfd4))
**Full Changelog:** [`2025.02.19.0...2025.02.20.0`](https://github.com/juspay/hyperswitch/compare/2025.02.19.0...2025.02.20.0)
- - -
## 2025.02.19.0
### Features
- **connector:** [Moneris] Add payments flow ([#7249](https://github.com/juspay/hyperswitch/pull/7249)) ([`d18d98a`](https://github.com/juspay/hyperswitch/commit/d18d98a1f687aef1e0f21f6a26387cb9ca7a347d))
- **core:** Api ,domain and diesel model changes for extended authorization ([#6607](https://github.com/juspay/hyperswitch/pull/6607)) ([`e14d6c4`](https://github.com/juspay/hyperswitch/commit/e14d6c4465bb1276a348a668051c084af72de8e3))
- **payments:** [Payment links] Add configs for payment link ([#7288](https://github.com/juspay/hyperswitch/pull/7288)) ([`72080c6`](https://github.com/juspay/hyperswitch/commit/72080c67c7927b53d5ca013983f379e9b027c51f))
**Full Changelog:** [`2025.02.18.0...2025.02.19.0`](https://github.com/juspay/hyperswitch/compare/2025.02.18.0...2025.02.19.0)
- - -
## 2025.02.18.0
### Features
- **coingate:** Add Crypto Pay Flow ([#7247](https://github.com/juspay/hyperswitch/pull/7247)) ([`c868ff3`](https://github.com/juspay/hyperswitch/commit/c868ff38e0234fa83f1615e751af12cb7d32a3d9))
### Refactors
- **utils:** Use to_state_code of hyperswitch_connectors in router ([#7278](https://github.com/juspay/hyperswitch/pull/7278)) ([`b97370d`](https://github.com/juspay/hyperswitch/commit/b97370d59fd167af9c24f4470f4668ce2ee76a89))
**Full Changelog:** [`2025.02.15.0...2025.02.18.0`](https://github.com/juspay/hyperswitch/compare/2025.02.15.0...2025.02.18.0)
- - -
## 2025.02.15.0
### Features
- **connector:** [Datatrans] add mandate flow ([#7245](https://github.com/juspay/hyperswitch/pull/7245)) ([`e2043de`](https://github.com/juspay/hyperswitch/commit/e2043dee224bac63b4288e53475176f0941c4abb))
- **core:**
- Add card_discovery filter to payment list and payments Response ([#7230](https://github.com/juspay/hyperswitch/pull/7230)) ([`3c7cb9e`](https://github.com/juspay/hyperswitch/commit/3c7cb9e59dc28bf79cf83793ae168491cfed717f))
- Introduce accounts schema for accounts related tables ([#7113](https://github.com/juspay/hyperswitch/pull/7113)) ([`0ba4ccf`](https://github.com/juspay/hyperswitch/commit/0ba4ccfc8b38a918a56eab66715005b4c448172b))
- **payment_methods_v2:** Add support for network tokenization ([#7145](https://github.com/juspay/hyperswitch/pull/7145)) ([`0b972e3`](https://github.com/juspay/hyperswitch/commit/0b972e38abd08380b75165dfd755087769f35a62))
- **router:** Add v2 endpoint retrieve payment aggregate based on merchant profile ([#7196](https://github.com/juspay/hyperswitch/pull/7196)) ([`c17eb01`](https://github.com/juspay/hyperswitch/commit/c17eb01e35749343b3bf4fdda51782ea962ee57a))
- **utils:** Add iso representation for each state for european countries ([#7273](https://github.com/juspay/hyperswitch/pull/7273)) ([`c337be6`](https://github.com/juspay/hyperswitch/commit/c337be66f9ca8b3f0a2c0a510298d4f48f09f588))
### Bug Fixes
- **cypress:** Resolve cypress issue for NMI connector ([#7267](https://github.com/juspay/hyperswitch/pull/7267)) ([`0d5c6fa`](https://github.com/juspay/hyperswitch/commit/0d5c6faae06c9e6e793a271c121a43818fb3e53f))
### Refactors
- **payments:** Add platform merchant account checks for payment intent ([#7204](https://github.com/juspay/hyperswitch/pull/7204)) ([`12ef8ee`](https://github.com/juspay/hyperswitch/commit/12ef8ee0fc63829429697c42b98f4c773f12cade))
- **payments_v2:** Create customer at connector end and populate connector customer ID ([#7246](https://github.com/juspay/hyperswitch/pull/7246)) ([`17f9e6e`](https://github.com/juspay/hyperswitch/commit/17f9e6ee9e99366fa0236a3f4266483d1d8dfa22))
- **router:** Add revenue_recovery_metadata to payment intent in diesel and api model for v2 flow ([#7176](https://github.com/juspay/hyperswitch/pull/7176)) ([`2ee22cd`](https://github.com/juspay/hyperswitch/commit/2ee22cdf8aced4881c1aab70cd10797a4deb57ed))
**Full Changelog:** [`2025.02.14.0...2025.02.15.0`](https://github.com/juspay/hyperswitch/compare/2025.02.14.0...2025.02.15.0)
- - -
## 2025.02.14.0
### Features
- **connector:** [Moneris] add template code ([#7216](https://github.com/juspay/hyperswitch/pull/7216)) ([`b09905e`](https://github.com/juspay/hyperswitch/commit/b09905ecb4c7b33576b3ca1f13affe5341ea6e6f))
- **core:** Add support to generate session token response from both `connector_wallets_details` and `metadata` ([#7140](https://github.com/juspay/hyperswitch/pull/7140)) ([`66d9c73`](https://github.com/juspay/hyperswitch/commit/66d9c731f528cd33a1a94815485d6efceb493742))
### Bug Fixes
- **connectors:** [fiuu] zero amount mandate flow for wallets ([#7251](https://github.com/juspay/hyperswitch/pull/7251)) ([`6aac16e`](https://github.com/juspay/hyperswitch/commit/6aac16e0c997d36e653f91be0f2a6660a3378dd5))
**Full Changelog:** [`2025.02.13.0...2025.02.14.0`](https://github.com/juspay/hyperswitch/compare/2025.02.13.0...2025.02.14.0)
- - -
## 2025.02.13.0
### Features
- **core:** 3ds decision manager for v2 ([#7089](https://github.com/juspay/hyperswitch/pull/7089)) ([`52ae92b`](https://github.com/juspay/hyperswitch/commit/52ae92bc5df3612d4a15f23c00883db7a5d8d44d))
### Bug Fixes
- **v2:** Trait gating in v2 ([#7223](https://github.com/juspay/hyperswitch/pull/7223)) ([`fd81197`](https://github.com/juspay/hyperswitch/commit/fd8119782a5d78a4be4561b44d0f68f498fe25b9))
### Refactors
- **connector:** [Adyen] Removed deprecated PMTs from Ayden (Giropay, Sofort) ([#7100](https://github.com/juspay/hyperswitch/pull/7100)) ([`40a36fd`](https://github.com/juspay/hyperswitch/commit/40a36fd319ccdb495deb077005ffcaea9cdf2427))
- **cypress:** Make amount configurable ([#7219](https://github.com/juspay/hyperswitch/pull/7219)) ([`055f628`](https://github.com/juspay/hyperswitch/commit/055f62858e6d0bcc6d27f563b30804365106d4a6))
- **schema:** Add a new column for storing large connector transaction IDs ([#7017](https://github.com/juspay/hyperswitch/pull/7017)) ([`fa09db1`](https://github.com/juspay/hyperswitch/commit/fa09db1534884037947c6d488e33a3ce600c2a0c))
**Full Changelog:** [`2025.02.12.0...2025.02.13.0`](https://github.com/juspay/hyperswitch/compare/2025.02.12.0...2025.02.13.0)
- - -
## 2025.02.12.0
### Features
- **connector:**
- [INESPAY] Enable Inespay In Dashboard ([#7233](https://github.com/juspay/hyperswitch/pull/7233)) ([`90ea076`](https://github.com/juspay/hyperswitch/commit/90ea0764aeb8524cac88031e1e887966a5c4fa76))
- [GETNET] add Connector Template Code ([#7105](https://github.com/juspay/hyperswitch/pull/7105)) ([`60310b4`](https://github.com/juspay/hyperswitch/commit/60310b485dd78d601a7e25f9b4bc8da53b425ce3))
- **payment_methods_session_v2:** Add payment methods session endpoints ([#7107](https://github.com/juspay/hyperswitch/pull/7107)) ([`9615382`](https://github.com/juspay/hyperswitch/commit/96153824a73f359623bf77f199013d2ca9ff5e43))
### Bug Fixes
- **payments:** [Payment links] Add fix for payment link redirection url ([#7232](https://github.com/juspay/hyperswitch/pull/7232)) ([`1d607d7`](https://github.com/juspay/hyperswitch/commit/1d607d7970abe204bc6101a81ba26652eadcbd04))
### Refactors
- **core:** Add support for expand attempt list in psync v2 ([#7209](https://github.com/juspay/hyperswitch/pull/7209)) ([`d093317`](https://github.com/juspay/hyperswitch/commit/d09331701997b70672d4d768e8139c12fffb7ad1))
**Full Changelog:** [`2025.02.11.0...2025.02.12.0`](https://github.com/juspay/hyperswitch/compare/2025.02.11.0...2025.02.12.0)
- - -
## 2025.02.11.0
### Features
- **connector:** [Datatrans] Add Wasm Changes ([#7229](https://github.com/juspay/hyperswitch/pull/7229)) ([`7b015c5`](https://github.com/juspay/hyperswitch/commit/7b015c5de061f6d6794dfcf5c7711809d325f46b))
- **router:** Add adyen split payments support ([#6952](https://github.com/juspay/hyperswitch/pull/6952)) ([`323d763`](https://github.com/juspay/hyperswitch/commit/323d763087fd7453f05153b97d6b53e211cf74ba))
### Bug Fixes
- **connector:**
- [fiuu] update PSync and webhooks response ([#7211](https://github.com/juspay/hyperswitch/pull/7211)) ([`1c54211`](https://github.com/juspay/hyperswitch/commit/1c54211b2f8aa650fc4dbb7ab3d796e21d50461a))
- Fix incorrect mapping of attempt status in NMI connector ([#7200](https://github.com/juspay/hyperswitch/pull/7200)) ([`76c3459`](https://github.com/juspay/hyperswitch/commit/76c34595ef612ca1a3b750653e6460b980163d63))
### Refactors
- **connector:** [Authorizedotnet] fix refund status mapping ([#7208](https://github.com/juspay/hyperswitch/pull/7208)) ([`bfcaf00`](https://github.com/juspay/hyperswitch/commit/bfcaf003427caf9580a2520b3f2efc8773818905))
- **router:** Add feature_metadata for merchant_connector_account create v2 flow ([#7144](https://github.com/juspay/hyperswitch/pull/7144)) ([`647e163`](https://github.com/juspay/hyperswitch/commit/647e163117a564f4be56b7b6a31b13007d3066f0))
**Full Changelog:** [`2025.02.10.0...2025.02.11.0`](https://github.com/juspay/hyperswitch/compare/2025.02.10.0...2025.02.11.0)
- - -
## 2025.02.10.0
### Features
- **connector:**
- [DataTrans] ADD 3DS Flow ([#6026](https://github.com/juspay/hyperswitch/pull/6026)) ([`4693d21`](https://github.com/juspay/hyperswitch/commit/4693d21b7c26055ed33fadd3f53943715ab71516))
- [DATATRANS] Add Support for External 3DS ([#7226](https://github.com/juspay/hyperswitch/pull/7226)) ([`45882bd`](https://github.com/juspay/hyperswitch/commit/45882bdb76f7f031776aa10692fabd792627b891))
- **opensearch:** Add amount and customer_id as filters and handle name for different indexes ([#7073](https://github.com/juspay/hyperswitch/pull/7073)) ([`df328c5`](https://github.com/juspay/hyperswitch/commit/df328c5e520b89b09e1b684d039f1d9613d78613))
### Refactors
- **connector:** Move connectors Aci, Braintree, Globalpay, Iatapay, Itaubank, Klarna, Mifinity and Nuvei from router to hyperswitch_connectors crate ([#7167](https://github.com/juspay/hyperswitch/pull/7167)) ([`7dfe400`](https://github.com/juspay/hyperswitch/commit/7dfe400401daf7081f9240ed52064281b302ba57))
- **router:** Add display_name field to connector feature api ([#7121](https://github.com/juspay/hyperswitch/pull/7121)) ([`50784ad`](https://github.com/juspay/hyperswitch/commit/50784ad1c13f0aa66a1da566ddd25e2621021538))
**Full Changelog:** [`2025.02.07.0...2025.02.10.0`](https://github.com/juspay/hyperswitch/compare/2025.02.07.0...2025.02.10.0)
- - -
## 2025.02.07.0
### Features
- **connector:** [COINGATE] Add Template PR ([#7052](https://github.com/juspay/hyperswitch/pull/7052)) ([`dddb1b0`](https://github.com/juspay/hyperswitch/commit/dddb1b06bea4ac89d838641508728d2da4326ba1))
- **core:** Add support for v2 payments get intent using merchant reference id ([#7123](https://github.com/juspay/hyperswitch/pull/7123)) ([`e17ffd1`](https://github.com/juspay/hyperswitch/commit/e17ffd1257adc1618ed60dee81ea1e7df84cb3d5))
- **router:** Add `organization_id` in authentication table and add it in authentication events ([#7168](https://github.com/juspay/hyperswitch/pull/7168)) ([`f211754`](https://github.com/juspay/hyperswitch/commit/f2117542a7dda4dbfa768fdb24229c113e25c93e))
- **routing:** Contract based routing integration ([#6761](https://github.com/juspay/hyperswitch/pull/6761)) ([`60ddddf`](https://github.com/juspay/hyperswitch/commit/60ddddf24a1625b8044c095c5d01754022102813))
### Bug Fixes
- **connector:** Handle unexpected error response from bluesnap connector ([#7120](https://github.com/juspay/hyperswitch/pull/7120)) ([`8ae5267`](https://github.com/juspay/hyperswitch/commit/8ae5267b91cfb37b14df1acf5fd7dfc2570b58ce))
- **dashboard_metadata:** Mask `poc_email` and `data_value` for DashboardMetadata ([#7130](https://github.com/juspay/hyperswitch/pull/7130)) ([`9b1b245`](https://github.com/juspay/hyperswitch/commit/9b1b2455643d7a5744a4084fc1916c84634cb48d))
### Refactors
- **customer:** Return redacted customer instead of error ([#7122](https://github.com/juspay/hyperswitch/pull/7122)) ([`97e9270`](https://github.com/juspay/hyperswitch/commit/97e9270ed4458a24207ea5434d65c54fb4b6237d))
- **dynamic_fields:** Dynamic fields for Adyen and Stripe, renaming klarnaCheckout, WASM for KlarnaCheckout ([#7015](https://github.com/juspay/hyperswitch/pull/7015)) ([`a6367d9`](https://github.com/juspay/hyperswitch/commit/a6367d92f629ef01cdb73aded8a81d2ba198f38c))
- **router:** Store `network_transaction_id` for `off_session` payments irrespective of the `is_connector_agnostic_mit_enabled` config ([#7083](https://github.com/juspay/hyperswitch/pull/7083)) ([`f9a4713`](https://github.com/juspay/hyperswitch/commit/f9a4713a60028e26b98143c6296d9969cd090163))
### Miscellaneous Tasks
- **connector:** [Fiuu] log keys in the PSync response ([#7189](https://github.com/juspay/hyperswitch/pull/7189)) ([`c044fff`](https://github.com/juspay/hyperswitch/commit/c044ffff0c47ee5d3ef5f905c3f590fae4ac9a24))
- **connectors:** [fiuu] update pm_filters for apple pay and google pay ([#7182](https://github.com/juspay/hyperswitch/pull/7182)) ([`2d0ac8d`](https://github.com/juspay/hyperswitch/commit/2d0ac8d46d2ecfd7287b67b646bc0b284ed838a9))
- **roles:** Remove redundant variant from PermissionGroup ([#6985](https://github.com/juspay/hyperswitch/pull/6985)) ([`775dcc5`](https://github.com/juspay/hyperswitch/commit/775dcc5a4e3b41dd1e4d0e4c47eccca15a8a4b3a))
**Full Changelog:** [`2025.02.06.0...2025.02.07.0`](https://github.com/juspay/hyperswitch/compare/2025.02.06.0...2025.02.07.0)
- - -
## 2025.02.06.0
### Features
- **analytics:** Add currency as dimension and filter for disputes ([#7006](https://github.com/juspay/hyperswitch/pull/7006)) ([`12a2f2a`](https://github.com/juspay/hyperswitch/commit/12a2f2ad147346365f828d8fc97eb9fe49a845bb))
- **connector:**
- [INESPAY] Integrate Sepa Bank Debit ([#6755](https://github.com/juspay/hyperswitch/pull/6755)) ([`ce2485c`](https://github.com/juspay/hyperswitch/commit/ce2485c3c77d86a2bce01d20c410ae11ac08c555))
- [Deutschebank] Add Access Token Error struct ([#7127](https://github.com/juspay/hyperswitch/pull/7127)) ([`22072fd`](https://github.com/juspay/hyperswitch/commit/22072fd750940ac7fec6ea971737409518600891))
- **core:**
- Google pay decrypt flow ([#6991](https://github.com/juspay/hyperswitch/pull/6991)) ([`e0ec27d`](https://github.com/juspay/hyperswitch/commit/e0ec27d936fc62a6feb2f8f643a218f3ad7483b5))
- Implement 3ds decision manger for V2 ([#7022](https://github.com/juspay/hyperswitch/pull/7022)) ([`1900959`](https://github.com/juspay/hyperswitch/commit/190095977819efac42da5483bfdae6420a7a402c)) | CHANGELOG.md#chunk13 | null | doc_chunk | 8,191 | doc | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentMethodId {
payment_method_source: PaymentMethodSource,
payment_method_id: Secret<String>,
} | crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs | hyperswitch_connectors | struct_definition | 24 | rust | PaymentMethodId | null | null | null | null | null | null | null | null | null | null | null |
pub struct TriggeredAttemptsAccumulator {
pub count: Option<i64>,
} | crates/analytics/src/frm/accumulator.rs | analytics | struct_definition | 19 | rust | TriggeredAttemptsAccumulator | null | null | null | null | null | null | null | null | null | null | null |
pub fn server(config: routes::AppState) -> Scope {
web::scope("/refunds")
.app_data(web::Data::new(config))
.service(web::resource("").route(web::post().to(refund_create)))
.service(
web::resource("/sync").route(web::post().to(refund_retrieve_with_gateway_creds)),
)
.service(
web::resource("/{refund_id}")
.route(web::get().to(refund_retrieve))
.route(web::post().to(refund_update)),
)
} | crates/router/src/compatibility/stripe/app.rs | router | function_signature | 117 | rust | null | null | null | null | server | null | null | null | null | null | null | null |
pub struct CreditCardResponseInfo {
pub id: String,
pub status: Option<String>,
pub document_type: String,
pub document_number: Secret<String>,
pub birthdate: Option<String>,
pub phone_country_code: Option<String>,
pub phone_area_code: Option<String>,
pub phone_number: Option<Secret<String>>,
pub inserted_at: Option<String>,
} | crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs | hyperswitch_connectors | struct_definition | 80 | rust | CreditCardResponseInfo | null | null | null | null | null | null | null | null | null | null | null |
pub struct DeliverySpecifications {
special_restrictions: Vec<String>,
address_restrictions: AddressRestrictions,
} | crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs | hyperswitch_connectors | struct_definition | 23 | rust | DeliverySpecifications | null | null | null | null | null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.